text:
/** \file
 * Defines the interface for the KDTree class.
 *
 * \author Martin F. Krafft <libkdtree@pobox.madduck.net>
 *
 * Paul Harris figured this stuff out (below)
 * Notes:
 * This is similar to a binary tree, but its not the same.
 * There are a few important differences:
 *
 *  * Each level is sorted by a different criteria (this is fundamental to the design).
 *
 *  * It is possible to have children IDENTICAL to its parent in BOTH branches
 *    This is different to a binary tree, where identical children are always to the right
 *    So, KDTree has the relationships:
 *    * The left branch is <= its parent (in binary tree, this relationship is a plain < )
 *    * The right branch is <= its parent (same as binary tree)
 *
 *    This is done for mostly for performance.
 *    Its a LOT easier to maintain a consistent tree if we use the <= relationship.
 *    Note that this relationship only makes a difference when searching for an exact
 *    item with find() or find_exact, other search, erase and insert functions don't notice
 *    the difference.
 *
 *    In the case of binary trees, you can safely assume that the next identical item
 *    will be the child leaf,
 *    but in the case of KDTree, the next identical item might
 *    be a long way down a subtree, because of the various different sort criteria.
 *
 *    So erase()ing a node from a KDTree could require serious and complicated
 *    tree rebalancing to maintain consistency... IF we required binary-tree-like relationships.
 *
 *    This has no effect on insert()s, a < test is good enough to keep consistency.
 *
 *    It has an effect on find() searches:
 *      * Instead of using compare(child,node) for a < relationship and following 1 branch,
 *        we must use !compare(node,child) for a <= relationship, and test BOTH branches, as
 *        we could potentially go down both branches.
 *
 *    It has no real effect on bounds-based searches (like find_nearest, find_within_range)
 *    as it compares vs a boundary and would follow both branches if required.
 *
 *    This has no real effect on erase()s, a < test is good enough to keep consistency.
 */

#ifndef INCLUDE_KDTREE_KDTREE_HPP
#define INCLUDE_KDTREE_KDTREE_HPP

#include <vector>
#include <list>

#pragma warning( disable : 4290)
#pragma warning( disable : 4099)
#pragma warning( disable : 4396)

#ifdef KDTREE_DEFINE_OSTREAM_OPERATORS
#  include <ostream>
#  include <stack>
#endif

#include <cmath>
#include <cstddef>
#include <cassert>
#include <algorithm>
#include <functional>      // For greater<int>( )

#include <kdtree++/accessor.hpp>
#include <kdtree++/allocator.hpp>
#include <kdtree++/iterator.hpp>
#include <kdtree++/node.hpp>
#include <kdtree++/region.hpp>

// Rob::stupid std less
template<typename Arg>
    struct stdless
    { // wrap operator()
    bool operator()(Arg left,
		Arg right) const{return left<right;}
    };

namespace KDTree
{

#ifdef KDTREE_CHECK_PERFORMANCE
   size_t num_dist_calcs = 0;
#endif

  template < typename _Val,
            typename _Acc = _Bracket_accessor<_Val>,
			typename _Cmp = stdless<typename _Acc::result_type>,
            typename _Alloc = std::allocator<_Node<_Val> > >
    class KDTree : protected _Alloc_base<_Val, _Alloc>
    {
    protected:
      //Rob
      size_t mK;

      // typedef _Alloc allocator_type;
      typedef _Alloc_base<_Val, _Alloc> _Base;
      typedef typename _Base::allocator_type allocator_type;

      typedef _Node_base* _Base_ptr;
      typedef _Node_base const* _Base_const_ptr;
      typedef ::KDTree::_Node<_Val>* _Link_type;
      typedef ::KDTree::_Node<_Val> const* _Link_const_type;

      typedef _Node_compare<_Val, _Acc, _Cmp> _Node_compare;

      typedef _Region<_Val, typename _Acc::result_type, _Acc, _Cmp>
        _Region;

    public:
      typedef _Region Region;
      typedef _Val value_type;
      typedef value_type* pointer;
      typedef value_type const* const_pointer;
      typedef value_type& reference;
      typedef value_type const& const_reference;
      typedef typename _Acc::result_type subvalue_type;
      typedef subvalue_type distance_type;   // NEW TYPE - for returning distances
      // I wanted to distinguish it from subvaluetype, for the future when/if we have
      // types that need a fancy distance calculation.
      // This is not complete yet, eg Region still uses subvalue_type for distance_type.
      typedef size_t size_type;
      typedef ptrdiff_t difference_type;

      KDTree( size_t nK, _Acc const& acc = _Acc(), const allocator_type& __a = allocator_type()) throw ()
        : _Base(__a), _M_header(_Base::_M_allocate_node()), _M_count(0), _M_acc(acc)
      {
		  mK = nK;
         _M_empty_initialise();
      }

      KDTree(const KDTree& __x) throw ()
         : _Base(__x.get_allocator()), _M_header(_Base::_M_allocate_node()), _M_count(0), _M_acc(__x._M_acc)
      {
	     mK = __x.mK;
         _M_empty_initialise();
         this->insert(begin(), __x.begin(), __x.end());
         this->optimise();
      }

      template<typename _InputIterator>
        KDTree(size_t nK, _InputIterator __first, _InputIterator __last,
             _Acc const& acc = _Acc(), const allocator_type& __a = allocator_type()) throw ()
        : _Base(__a), _M_header(_Base::_M_allocate_node()), _M_count(0), _M_acc(acc)
      {
		  mK = nK;
         _M_empty_initialise();
         this->insert(begin(), __first, __last);
         this->optimise();
      }

      KDTree&
      operator=(const KDTree& __x)
      {
         if (this != &__x)
         {
            this->clear();
            this->insert(begin(),__x.begin(),__x.end());
            this->optimize();
         }
         return *this;
      }

      ~KDTree() throw ()
      {
        this->clear();
        _M_deallocate_node(_M_header);
      }

      allocator_type
      get_allocator() const
      {
        return _Base::get_allocator();
      }

      size_type
      size() const
      {
        return _M_count;
      }

      size_type
      max_size() const
      {
        return size_type(-1);
      }

      bool
      empty() const
      {
        return this->size() == 0;
      }

      void
      clear()
      {
        _M_erase_subtree(_M_get_root());
        _M_set_leftmost(_M_header);
        _M_set_rightmost(_M_header);
        _M_set_root(NULL);
        _M_count = 0;
      }

      // typedef _Iterator<_Val, reference, pointer> iterator;
      typedef _Iterator<_Val, const_reference, const_pointer> const_iterator;
      // No mutable iterator at this stage
      typedef const_iterator iterator;

      typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
      typedef std::reverse_iterator<iterator> reverse_iterator;

      const_iterator begin() const { return const_iterator(_M_get_leftmost()); }
      const_iterator end() const { return const_iterator(_M_header); }
      const_reverse_iterator rbegin() const { return const_reverse_iterator(_M_get_rightmost()); }
      const_reverse_iterator rend() const { return const_reverse_iterator(_M_header); }

      // iterator begin() { return iterator(_M_get_leftmost()); }
      // iterator end() { return iterator(_M_header); }
      // reverse_iterator rbegin() { return reverse_iterator(end()); }
      // reverse_iterator rend() { return reverse_iterator(begin()); }

      iterator
      insert(iterator /* ignored */, const_reference __V) throw (std::bad_alloc)
      {
         return this->insert(__V);
      }

      iterator
      insert(const_reference __V) throw (std::bad_alloc)
      {
        if (!_M_get_root())
          {
            _Link_type __n = _M_new_node(__V, _M_header);
            ++_M_count;
            _M_set_root(__n);
            _M_set_leftmost(__n);
            _M_set_rightmost(__n);
            return iterator(__n);
          }
        return _M_insert(_M_get_root(), __V, 0);
      }

      template <class _InputIterator>
      void insert(_InputIterator __first, _InputIterator __last) {
         for (; __first != __last; ++__first)
            this->insert(*__first);
      }

      void
      insert(iterator __pos, size_type __n, const value_type& __x)
      {
        for (; __n > 0; --__n)
          this->insert(__pos, __x);
      }

      template<typename _InputIterator>
      void
      insert(iterator __pos, _InputIterator __first, _InputIterator __last) {
         for (; __first != __last; ++__first)
            this->insert(__pos, *__first);
      }

      // Note: this uses the find() to location the item you want to erase.
      // find() compares by equivalence of location ONLY.  See the comments
      // above find_exact() for why you may not want this.
      //
      // If you want to erase ANY item that has the same location as __V,
      // then use this function.
      //
      // If you want to erase a PARTICULAR item, and not any other item
      // that might happen to have the same location, then you should use
      // erase_exact().
      void
      erase(const_reference __V) throw () {
        this->erase(this->find(__V));
      }

      void
      erase_exact(const_reference __V) throw () {
        this->erase(this->find_exact(__V));
      }

      // note: kept as const because its easier to const-cast it away
      void
      erase(const_iterator const& __IT) throw ()
      {
         assert(__IT != this->end());
        _Link_const_type target = static_cast<_Link_const_type>(__IT._M_node);
        _Link_const_type n = target;
        size_t level = 0;
        while ((n = _S_parent(n)) != _M_header)
           ++level;
        _M_erase( const_cast<_Link_type>(target), level );
        _M_delete_node( const_cast<_Link_type>(target) );
        --_M_count;
      }

/* this does not work since erasure changes sort order
      void
      erase(const_iterator __A, const_iterator const& __B) throw ()
      {
        if (0 && __A == this->begin() && __B == this->end())
          {
            this->clear();
          }
        else
          {
            while (__A != __B)
              this->erase(__A++);
          }
      }
*/

      // compares via equivalence
      // so if you are looking for any item with the same location,
      // according to the standard accessor comparisions,
      // then this is the function for you.
      const_iterator
      find(const_reference __V) const throw ()
      {
        if (!_M_get_root()) return this->end();
        return _M_find(_M_get_root(), __V, 0);
      }

      // compares via equality
      // if you are looking for a particular item in the tree,
      // and (for example) it has an ID that is checked via an == comparison
      // eg
      // struct Item
      // {
      //    unsigned int unique_id;
      //    bool operator==(Item const& a, Item const& b) { return a.unique_id == b.unique_id; }
      //    Location location;
      // };
      // Two items may be equivalent in location.  find() would return
      // either one of them.  But no two items have the same ID, so
      // find_exact() would always return the item with the same location AND id.
      //
      const_iterator
      find_exact(const_reference __V) const throw ()
      {
        if (!_M_get_root()) return this->end();
        return _M_find_exact(_M_get_root(), __V, 0);
      }

      size_t
        count_within_range(const_reference __V, subvalue_type const __R) const throw ()
        {
          if (!_M_get_root()) return 0;
          _Region __region(_M_acc,__V,__R);
          return this->count_within_range(__region);
        }

      size_t
        count_within_range(_Region const& __REGION) const throw ()
        {
          if (!_M_get_root()) return 0;

          _Region __bounds(__REGION);
          return _M_count_within_range(_M_get_root(),
                               __REGION, __bounds, 0);
        }

      template <typename SearchVal, class Visitor>
        Visitor
        visit_within_range(SearchVal V, subvalue_type const R, Visitor visitor) const throw ()
        {
          if (!_M_get_root()) return visitor;
          _Region region(_M_acc,V,R);
          return this->visit_within_range(region, visitor);
        }

      template <class Visitor>
        Visitor
        visit_within_range(_Region const& REGION, Visitor visitor) const throw ()
        {
          if (_M_get_root())
            {
              _Region bounds(REGION);
              return _M_visit_within_range(visitor, _M_get_root(), REGION, bounds, 0);
            }
          return visitor;
        }

      template <typename SearchVal, typename _OutputIterator>
        _OutputIterator
         find_within_range(SearchVal __V, subvalue_type const __R,
                          _OutputIterator __outIT) const throw ()
		{
          if (!_M_get_root()) return __outIT;
          _Region __region(mK,_M_acc,__V,__R);

          return this->find_within_range(__region, __outIT);
        }

      template <typename _OutputIterator>
        _OutputIterator
        find_within_range(_Region const& __REGION,
                          _OutputIterator __outIT) const throw ()
        {
          if (_M_get_root())
            {
              _Region __bounds(__REGION);
              __outIT = _M_find_within_range(__outIT, _M_get_root(),
                                   __REGION, __bounds, 0);
            }
          return __outIT;
        }

      template <typename SearchVal>
         std::pair<const_iterator,distance_type>
        find_nearest(SearchVal __V, subvalue_type const __Max_R ) const throw ()
        {
          if (!_M_get_root())
             return std::pair<const_iterator,distance_type>(this->end(),__Max_R);
          _Region __region(_M_acc,__V);  // note: zero-area!
          typename _Region::_CenterPt __pt(__region,__Max_R);
          return this->find_nearest(__pt);
        }

      template <typename SearchVal, class Predicate>
         std::pair<const_iterator,distance_type>
        find_nearest_if(SearchVal __V, subvalue_type const __Max_R, Predicate predicate ) const throw ()
        {
          if (!_M_get_root())
             return std::pair<const_iterator,distance_type>(this->end(),__Max_R);
          _Region __region(mK,_M_acc,__V);  // note: zero-area!
          typename _Region::_CenterPt __pt(__region,__Max_R);
          return this->find_nearest_if(__pt,predicate);
        }

      std::pair<const_iterator,distance_type>
        find_nearest( typename _Region::_CenterPt const& __CENTER ) const throw ()
        {
          if (_M_get_root())
          {
             // note: we set the initial 'bounds' to the exact point.
             // they expand from there outwards.
             _Region __bounds(__CENTER.first);
             std::pair<const_iterator,distance_type> best = _M_find_nearest(_M_get_root(), __CENTER, __bounds, 0, always_true());
             // ensure we return end() if we didn't find it
             // however, also return the best distance we did find, it might be useful to someone.
             if (best.second > __CENTER.second)
                best.first = this->end();
             return best;
          }
         return std::pair<const_iterator,distance_type>(this->end(),__CENTER.second);
        }

      template <class Predicate>
      std::pair<const_iterator,distance_type>
        find_nearest_if( typename _Region::_CenterPt const& __CENTER, Predicate predicate ) const throw ()
        {
          if (_M_get_root())
          {
             // note: we set the initial 'bounds' to the exact point.
             // they expand from there outwards.
             _Region __bounds(__CENTER.first);
             std::pair<const_iterator,distance_type> best = _M_find_nearest(_M_get_root(), __CENTER, __bounds, 0, predicate);
             // ensure we return end() if we didn't find it
             // however, also return the best distance we did find, it might be useful to someone.
             if (best.second > __CENTER.second)
                best.first = this->end();
             return best;
          }
         return std::pair<const_iterator,distance_type>(this->end(),__CENTER.second);
        }

      void
      optimise()
      {
        std::vector<value_type> __v(this->begin(),this->end());
        this->clear();
        _M_optimise(__v.begin(), __v.end(), 0);
      }

      void
      optimize()
      { // cater for people who cannot spell :)
        this->optimise();
      }

      void check_tree()
      {
         _M_check_node(_M_get_root(),0);
      }

    protected:

      void _M_check_children( _Link_const_type child, _Link_const_type parent, size_t const level, bool to_the_left )
      {
         assert(parent);
         if (child)
         {
            _Node_compare compare(level % mK,_M_acc);
            // REMEMBER! its a <= relationship for BOTH branches
            // for left-case (true), child<=node --> !(node<child)
            // for right-case (false), node<=child --> !(child<node)
            assert(!to_the_left or !compare(parent,child));  // check the left
            assert(to_the_left or !compare(child,parent));   // check the right
            // and recurse down the tree, checking everything
            _M_check_children(_S_left(child),parent,level,to_the_left);
            _M_check_children(_S_right(child),parent,level,to_the_left);
         }
      }

      void _M_check_node( _Link_const_type node, size_t const level )
      {
         if (node)
         {
            // (comparing on this level)
            // everything to the left of this node must be smaller than this
            _M_check_children( _S_left(node), node, level, true );
            // everything to the right of this node must be larger than this
            _M_check_children( _S_right(node), node, level, false );

            _M_check_node( _S_left(node), level+1 );
            _M_check_node( _S_right(node), level+1 );
         }
      }

      void _M_empty_initialise()
      {
        _M_set_leftmost(_M_header);
        _M_set_rightmost(_M_header);
        _M_set_root(NULL);
      }

      iterator
      _M_insert_left(_Link_type __N, const_reference __V)
      {
        _S_set_left(__N, _M_new_node(__V)); ++_M_count;
        _S_set_parent( _S_left(__N), __N );
        if (__N == _M_get_leftmost())
           _M_set_leftmost( _S_left(__N) );
        return iterator(_S_left(__N));
      }

      iterator
      _M_insert_right(_Link_type __N, const_reference __V)
      {
        _S_set_right(__N, _M_new_node(__V)); ++_M_count;
        _S_set_parent( _S_right(__N), __N );
        if (__N == _M_get_rightmost())
           _M_set_rightmost( _S_right(__N) );
        return iterator(_S_right(__N));
      }

      iterator
      _M_insert(_Link_type __N, const_reference __V,
             size_t const __L) throw (std::bad_alloc)
      {
        if (_Node_compare(__L % mK,_M_acc)(__V, __N))
          {
            if (!_S_left(__N))
              return _M_insert_left(__N, __V);
            return _M_insert(_S_left(__N), __V, __L+1);
          }
        else
          {
            if (!_S_right(__N) || __N == _M_get_rightmost())
              return _M_insert_right(__N, __V);
            return _M_insert(_S_right(__N), __V, __L+1);
          }
      }

      _Link_type
      _M_erase(_Link_type dead_dad, size_t const level) throw ()
      {
         // find a new step_dad, he will become a drop-in replacement.
        _Link_type step_dad = _M_get_erase_replacement(dead_dad, level);

         // tell dead_dad's parent that his new child is step_dad
        if (dead_dad == _M_get_root())
           _S_set_parent(_M_header, step_dad);
        else if (_S_left(_S_parent(dead_dad)) == dead_dad)
            _S_set_left(_S_parent(dead_dad), step_dad);
        else
            _S_set_right(_S_parent(dead_dad), step_dad);

        // deal with the left and right edges of the tree...
        // if the dead_dad was at the edge, then substitude...
        // but if there IS no new dead, then left_most is the dead_dad's parent
         if (dead_dad == _M_get_leftmost())
           _M_set_leftmost( (step_dad ? step_dad : _S_parent(dead_dad)) );
         if (dead_dad == _M_get_rightmost())
           _M_set_rightmost( (step_dad ? step_dad : _S_parent(dead_dad)) );

        if (step_dad)
          {
             // step_dad gets dead_dad's parent
            _S_set_parent(step_dad, _S_parent(dead_dad));

            // first tell the children that step_dad is their new dad
            if (_S_left(dead_dad))
               _S_set_parent(_S_left(dead_dad), step_dad);
            if (_S_right(dead_dad))
               _S_set_parent(_S_right(dead_dad), step_dad);

            // step_dad gets dead_dad's children
            _S_set_left(step_dad, _S_left(dead_dad));
            _S_set_right(step_dad, _S_right(dead_dad));
          }

        return step_dad;
      }

      _Link_type
      _M_get_erase_replacement(_Link_type node, size_t const level) throw ()
      {
         // if 'node' is null, then we can't do any better
        if (_S_is_leaf(node))
           return NULL;

        std::pair<_Link_type,size_t> candidate;
        // if there is nothing to the left, find a candidate on the right tree
        if (!_S_left(node))
          candidate = _M_get_j_min( std::pair<_Link_type,size_t>(_S_right(node),level), level+1);
        // ditto for the right
        else if ((!_S_right(node)))
          candidate = _M_get_j_max( std::pair<_Link_type,size_t>(_S_left(node),level), level+1);
        // we have both children ...
        else
         {
            // we need to do a little more work in order to find a good candidate
            // this is actually a technique used to choose a node from either the
            // left or right branch RANDOMLY, so that the tree has a greater change of
            // staying balanced.
            // If this were a true binary tree, we would always hunt down the right branch.
            // See top for notes.
            _Node_compare compare(level % mK,_M_acc);
            // compare the children based on this level's criteria...
            // (this gives virtually random results)
            if (compare(_S_right(node), _S_left(node)))
               // the right is smaller, get our replacement from the SMALLEST on the right
               candidate = _M_get_j_min(std::pair<_Link_type,size_t>(_S_right(node),level), level+1);
            else
               candidate = _M_get_j_max( std::pair<_Link_type,size_t>(_S_left(node),level), level+1);
         }

        // we have a candidate replacement by now.
        // remove it from the tree, but don't delete it.
        // it must be disconnected before it can be reconnected.
        _Link_type parent = _S_parent(candidate.first);
        if (_S_left(parent) == candidate.first)
           _S_set_left(parent, _M_erase(candidate.first, candidate.second));
        else
           _S_set_right(parent, _M_erase(candidate.first, candidate.second));

        return candidate.first;
      }

      std::pair<_Link_type,size_t>
      _M_get_j_min( std::pair<_Link_type,size_t> const node, size_t const level) throw ()
      {
         typedef std::pair<_Link_type,size_t> Result;
        if (_S_is_leaf(node.first))
            return Result(node.first,level);

        _Node_compare compare(node.second % mK,_M_acc);
        Result candidate = node;
        if (_S_left(node.first))
          {
            Result left = _M_get_j_min(Result(_S_left(node.first), node.second), level+1);
            if (compare(left.first, candidate.first))
                candidate = left;
          }
        if (_S_right(node.first))
          {
            Result right = _M_get_j_min( Result(_S_right(node.first),node.second), level+1);
            if (compare(right.first, candidate.first))
                candidate = right;
          }
        if (candidate.first == node.first)
           return Result(candidate.first,level);

        return candidate;
      }

      std::pair<_Link_type,size_t>
      _M_get_j_max( std::pair<_Link_type,size_t> const node, size_t const level) throw ()
      {
         typedef std::pair<_Link_type,size_t> Result;

        if (_S_is_leaf(node.first))
            return Result(node.first,level);

        _Node_compare compare(node.second % mK,_M_acc);
        Result candidate = node;
        if (_S_left(node.first))
          {
            Result left = _M_get_j_max( Result(_S_left(node.first),node.second), level+1);
            if (compare(candidate.first, left.first))
                candidate = left;
          }
        if (_S_right(node.first))
          {
            Result right = _M_get_j_max(Result(_S_right(node.first),node.second), level+1);
            if (compare(candidate.first, right.first))
                candidate = right;
          }

        if (candidate.first == node.first)
           return Result(candidate.first,level);

        return candidate;
      }

      void
      _M_erase_subtree(_Link_type __n)
      {
        while (__n)
          {
            _M_erase_subtree(_S_right(__n));
            _Link_type __t = _S_left(__n);
            _M_delete_node(__n);
            __n = __t;
          }
      }

      const_iterator
      _M_find(_Link_const_type node, const_reference value, size_t const level) const throw ()
      {
         // be aware! This is very different to normal binary searches, because of the <=
         // relationship used. See top for notes.
         // Basically we have to check ALL branches, as we may have an identical node
         // in different branches.
          const_iterator found = this->end();

        _Node_compare compare(level % mK,_M_acc);
        if (!compare(node,value))   // note, this is a <= test
          {
           // this line is the only difference between _M_find_exact() and _M_find()
            if (_M_matches_node_in_other_ds(node, value, level))
              return const_iterator(node);   // return right away
            if (_S_left(node))
               found = _M_find(_S_left(node), value, level+1);
          }
        if ( _S_right(node) && found == this->end() && !compare(value,node))   // note, this is a <= test
            found = _M_find(_S_right(node), value, level+1);
        return found;
      }

      const_iterator
      _M_find_exact(_Link_const_type node, const_reference value, size_t const level) const throw ()
      {
         // be aware! This is very different to normal binary searches, because of the <=
         // relationship used. See top for notes.
         // Basically we have to check ALL branches, as we may have an identical node
         // in different branches.
          const_iterator found = this->end();

        _Node_compare compare(level % mK,_M_acc);
        if (!compare(node,value))  // note, this is a <= test
        {
           // this line is the only difference between _M_find_exact() and _M_find()
            if (value == *const_iterator(node))
              return const_iterator(node);   // return right away
           if (_S_left(node))
            found = _M_find_exact(_S_left(node), value, level+1);
        }

        // note: no else!  items that are identical can be down both branches
        if ( _S_right(node) && found == this->end() && !compare(value,node))   // note, this is a <= test
            found = _M_find_exact(_S_right(node), value, level+1);
        return found;
      }

      bool
      _M_matches_node_in_d(_Link_const_type __N, const_reference __V,
                           size_t const __L) const throw ()
      {
        _Node_compare compare(__L % mK,_M_acc);
        return !(compare(__N, __V) || compare(__V, __N));
      }

      bool
      _M_matches_node_in_other_ds(_Link_const_type __N, const_reference __V,
                                  size_t const __L = 0) const throw ()
      {
        size_t __i = __L;
        while ((__i = (__i + 1) % mK) != __L % mK)
          if (!_M_matches_node_in_d(__N, __V, __i)) return false;
        return true;
      }

      bool
      _M_matches_node(_Link_const_type __N, const_reference __V,
                      size_t __L = 0) const throw ()
      {
        return _M_matches_node_in_d(__N, __V, __L)
          && _M_matches_node_in_other_ds(__N, __V, __L);
      }

      size_t
        _M_count_within_range(_Link_const_type __N, _Region const& __REGION,
                             _Region const& __BOUNDS,
                             size_t const __L) const throw ()
        {
           size_t count = 0;
          if (__REGION.encloses(_S_value(__N)))
            {
               ++count;
            }
          if (_S_left(__N))
            {
              _Region __bounds(__BOUNDS);
              __bounds.set_high_bound(_S_value(__N), __L);
              if (__REGION.intersects_with(__bounds))
                count += _M_count_within_range(_S_left(__N),
                                     __REGION, __bounds, __L+1);
            }
          if (_S_right(__N))
            {
              _Region __bounds(__BOUNDS);
              __bounds.set_low_bound(_S_value(__N), __L);
              if (__REGION.intersects_with(__bounds))
                count += _M_count_within_range(_S_right(__N),
                                     __REGION, __bounds, __L+1);
            }

          return count;
        }

      template <class Visitor>
        Visitor
        _M_visit_within_range(Visitor visitor,
                             _Link_const_type N, _Region const& REGION,
                             _Region const& BOUNDS,
                             size_t const L) const throw ()
        {
          if (REGION.encloses(_S_value(N)))
            {
              visitor(_S_value(N));
            }
          if (_S_left(N))
            {
              _Region bounds(BOUNDS);
              bounds.set_high_bound(_S_value(N), L);
              if (REGION.intersects_with(bounds))
                visitor = _M_visit_within_range(visitor, _S_left(N),
                                     REGION, bounds, L+1);
            }
          if (_S_right(N))
            {
              _Region bounds(BOUNDS);
              bounds.set_low_bound(_S_value(N), L);
              if (REGION.intersects_with(bounds))
                visitor = _M_visit_within_range(visitor, _S_right(N),
                                     REGION, bounds, L+1);
            }

          return visitor;
        }

      template <typename _OutputIterator>
        _OutputIterator
        _M_find_within_range(_OutputIterator __outIT,
                             _Link_const_type __N, _Region const& __REGION,
                             _Region const& __BOUNDS,
                             size_t const __L) const throw ()
        {
          if (__REGION.encloses(_S_value(__N)))
            {
              *__outIT++ = _S_value(__N);
            }
          if (_S_left(__N))
            {
              _Region __bounds(__BOUNDS);
              __bounds.set_high_bound(_S_value(__N), __L);
              if (__REGION.intersects_with(__bounds))
                __outIT = _M_find_within_range(__outIT, _S_left(__N),
                                     __REGION, __bounds, __L+1);
            }
          if (_S_right(__N))
            {
              _Region __bounds(__BOUNDS);
              __bounds.set_low_bound(_S_value(__N), __L);
              if (__REGION.intersects_with(__bounds))
                __outIT = _M_find_within_range(__outIT, _S_right(__N),
                                     __REGION, __bounds, __L+1);
            }

          return __outIT;
        }

        // quick little power function
        // next-best is __gnu_cxx::power
        // std::pow() is probably not ideal for simple powers. I forget exact details...
        distance_type _M_square( distance_type x ) const { return x*x; }

       // WARNING: Calculates and RETURNS dist^2 (for speed)
       // NOTE: CENTER is a region of zero area.  It is the point we are aiming for.
       //
       // How it works: Starting with a centerpt (single-pt in a region, with a range
       // attached to it), and bounds, it first calculates the distance to THIS node,
       // and adjusts the center's range DOWN if its closer.  No point looking further
       // than it needs to look.  A form of a dynamic find_within_range.
       // It expands the bounds as usual and sees if it intersects the centerpt+range.
       // And so it goes ...

         // substitude predicate for normal find_nearest()s
         struct always_true
         {
            bool operator()( _Val const& ) const { return true; }
         };

         template <class Predicate>
         std::pair<const_iterator,distance_type>
        _M_find_nearest( _Link_const_type __N, typename _Region::_CenterPt __CENTER,
                             _Region const& __BOUNDS,
                             size_t const __L,
                             Predicate predicate ) const throw ()
        {
           std::pair<const_iterator,distance_type> best(this->end(),__CENTER.second);

           // we ignore this node if the predicate isn't true
           if (predicate(*const_iterator(__N)))
           {
              distance_type dist = 0;
              for ( size_t i = 0; i != mK; ++i )
              {
                 dist += _M_square( __CENTER.first._M_low_bounds[i] - _M_acc(_S_value(__N),i) );
              }
#ifdef KDTREE_CHECK_PERFORMANCE
              ++num_dist_calcs;
#endif
              dist = sqrt(dist);

              best.first = __N;
              best.second = dist;
           }

           // adjust our CENTER target
           __CENTER.second = (std::min)(__CENTER.second,best.second);

          if (_S_left(__N))
            {
              _Region __bounds(__BOUNDS);
              __bounds.set_high_bound(_S_value(__N), __L);
              if (__bounds.intersects_with(__CENTER))
              {
                 std::pair<const_iterator,distance_type> left =
                    _M_find_nearest( _S_left(__N), __CENTER, __bounds, __L+1, predicate);
                 // check if better than what I found
                 if (left.second < best.second) best = left;
              }
            }

           // adjust our center target (only useful if left found something closer)
           __CENTER.second = (std::min)(__CENTER.second,best.second);

          if (_S_right(__N))
            {
              _Region __bounds(__BOUNDS);
              __bounds.set_low_bound(_S_value(__N), __L);
              if (__bounds.intersects_with(__CENTER))
              {
                 std::pair<const_iterator,distance_type> right =
                    _M_find_nearest( _S_right(__N), __CENTER, __bounds, __L+1, predicate);
                 // check if better than what I found
                 if (right.second < best.second) best = right;
               }
            }

          return best;
        }

      template <typename _Iter>
        void
        _M_optimise(_Iter const& __A, _Iter const& __B,
                    size_t const __L) throw ()
      {
        if (__A == __B) return;
        _Node_compare compare(__L % mK,_M_acc);
        std::sort(__A, __B, compare);
        _Iter __m = __A + (__B - __A) / 2;
        this->insert(*__m);
        if (__m != __A) _M_optimise(__A, __m, __L+1);
        if (++__m != __B) _M_optimise(__m, __B, __L+1);
      }

      _Link_const_type
      _M_get_root() const
      {
         return static_cast<_Link_const_type>( _M_header->_M_parent );
      }

      _Link_type
      _M_get_root()
      {
         return static_cast<_Link_type>( _M_header->_M_parent );
      }

      void _M_set_root(_Node_base * n)
      {
         _M_header->_M_parent = n;
      }

      _Link_const_type
      _M_get_leftmost() const
      {
        return static_cast<_Link_type>( _M_header->_M_left );
      }

      void
      _M_set_leftmost( _Node_base * a )
      {
         _M_header->_M_left = a;
      }

      _Link_const_type
      _M_get_rightmost() const
      {
        return static_cast<_Link_type>( _M_header->_M_right );
      }

      void
      _M_set_rightmost( _Node_base * a )
      {
         _M_header->_M_right = a;
      }

      static _Link_type
      _S_parent(_Base_ptr N)
      {
        return static_cast<_Link_type>( N->_M_parent );
      }

      static _Link_const_type
      _S_parent(_Base_const_ptr N)
      {
        return static_cast<_Link_const_type>( N->_M_parent );
      }

      static void
      _S_set_parent(_Base_ptr N, _Base_ptr p)
      {
        N->_M_parent = p;
      }

      static void
      _S_set_left(_Base_ptr N, _Base_ptr l)
      {
        N->_M_left = l;
      }

      static _Link_type
      _S_left(_Base_ptr N)
      {
        return static_cast<_Link_type>( N->_M_left );
      }

      static _Link_const_type
      _S_left(_Base_const_ptr N)
      {
        return static_cast<_Link_const_type>( N->_M_left );
      }

      static void
      _S_set_right(_Base_ptr N, _Base_ptr r)
      {
        N->_M_right = r;
      }

      static _Link_type
      _S_right(_Base_ptr N)
      {
        return static_cast<_Link_type>( N->_M_right );
      }

      static _Link_const_type
      _S_right(_Base_const_ptr N)
      {
        return static_cast<_Link_const_type>( N->_M_right );
      }

      static bool
      _S_is_leaf(_Base_const_ptr N)
      {
        return !_S_left(N) && !_S_right(N);
      }

      static const_reference
      _S_value(_Link_const_type N)
      {
        return N->_M_value;
      }

      static const_reference
      _S_value(_Base_const_ptr N)
      {
        return static_cast<_Link_const_type>(N)->_M_value;
      }

      static _Link_const_type
      _S_minimum(_Link_const_type __X)
      {
        return static_cast<_Link_const_type> ( _Node_base::_S_minimum(__X) );
      }

      static _Link_const_type
      _S_maximum(_Link_const_type __X)
      {
        return static_cast<_Link_const_type>( _Node_base::_S_maximum(__X) );
      }

      _Link_type
      _M_new_node(const_reference __V, //  = value_type(),
                  _Base_ptr const __PARENT = NULL,
                  _Base_ptr const __LEFT = NULL,
                  _Base_ptr const __RIGHT = NULL)
      {
        _Link_type __ret = _Base::_M_allocate_node();
        try
          {
            _M_construct_node(__ret, __V, __PARENT, __LEFT, __RIGHT);
          }
        catch(...)
          {
            _M_deallocate_node(__ret);
          }
        return __ret;
      }

      /* WHAT was this for?
      _Link_type
      _M_clone_node(_Link_const_type __X)
      {
        _Link_type __ret = _M_allocate_node(__X->_M_value);
        // TODO
        return __ret;
      }
      */

      void
      _M_delete_node(_Link_type __p)
      {
        _M_destroy_node(__p);
        _M_deallocate_node(__p);
      }

      _Link_type _M_header;
      size_type _M_count;
      _Acc _M_acc;

#ifdef KDTREE_DEFINE_OSTREAM_OPERATORS
      friend std::ostream&
      operator<<(std::ostream& o,
                    KDTree<_Val, _Acc, _Cmp, _Alloc> const& tree) throw ()
    {
      o << "meta node:   " << *tree._M_header << std::endl;

      if (tree.empty())
        return o << "[empty " << tree.mK << "d-tree " << &tree << "]";

      o << "nodes total: " << tree.size() << std::endl;
      o << "dimensions:  " << tree.mK << std::endl;

      typedef KDTree<_Val, _Acc, _Cmp, _Alloc> _Tree;
      typedef typename _Tree::_Link_type _Link_type;

      std::stack<_Link_const_type> s;
      s.push(tree._M_get_root());

      while (!s.empty())
        {
          _Link_const_type n = s.top();
          s.pop();
          o << *n << std::endl;
          if (_Tree::_S_left(n)) s.push(_Tree::_S_left(n));
          if (_Tree::_S_right(n)) s.push(_Tree::_S_right(n));
        }

      return o;
    }
#endif

  };

} // namespace KDTree

#endif // include guard

/* COPYRIGHT --
 *
 * This file is part of libkdtree++, a C++ template KD-Tree sorting container.
 * libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net>
 * and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the
 * terms of the Artistic License 2.0. See the ./COPYING file in the source tree
 * root for more information.
 * Parts of this file are (c) 2004-2007 Paul Harris <paulharris@computer.org>.
 *
 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES
 * OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */


text:
import { EntryItem } from '../types/entries';
import { Pattern } from '../types/patterns';
export declare type TransformFunction<T> = (entry: EntryItem) => T;
export interface IOptions<T = EntryItem> {
    /**
     * The current working directory in which to search.
     */
    cwd: string;
    /**
     * The deep option can be set to true to traverse the entire directory structure,
     * or it can be set to a number to only traverse that many levels deep.
     */
    deep: number | boolean;
    /**
     * Add an array of glob patterns to exclude matches.
     */
    ignore: Pattern[];
    /**
     * Allow patterns to match filenames starting with a period (files & directories),
     * even if the pattern does not explicitly have a period in that spot.
     */
    dot: boolean;
    /**
     * Return `fs.Stats` with `path` property instead of file path.
     */
    stats: boolean;
    /**
     * Return only files.
     */
    onlyFiles: boolean;
    /**
     * Return only directories.
     */
    onlyDirectories: boolean;
    /**
     * Follow symlinked directories when expanding `**` patterns.
     */
    followSymlinkedDirectories: boolean;
    /**
     * Prevent duplicate results.
     */
    unique: boolean;
    /**
     * Add a `/` character to directory entries.
     */
    markDirectories: boolean;
    /**
     * Return absolute paths for matched entries.
     */
    absolute: boolean;
    /**
     * Disable expansion of brace patterns.
     */
    nobrace: boolean;
    /**
     * Enable expansion of brace patterns.
     */
    brace: boolean;
    /**
     * Disable matching with globstars (`**`).
     */
    noglobstar: boolean;
    /**
     * Enable matching with globstars (`**`).
     */
    globstar: boolean;
    /**
     * Disable extglob support, so that extglobs are regarded as literal characters.
     */
    noext: boolean;
    /**
     * Enable extglob support, so that extglobs are regarded as literal characters.
     */
    extension: boolean;
    /**
     * Disable a case-insensitive regex for matching files.
     */
    nocase: boolean;
    /**
     * Enable a case-insensitive regex for matching files.
     */
    case: boolean;
    /**
     * Allow glob patterns without slashes to match a file path based on its basename.
     * For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
     */
    matchBase: boolean;
    /**
     * Allows you to transform a path or `fs.Stats` object before sending to the array.
     */
    transform: TransformFunction<T> | null;
}
export declare type IPartialOptions<T = EntryItem> = Partial<IOptions<T>>;
export declare function prepare(options?: IPartialOptions): IOptions;

redpajama_set_name: RedPajamaGithub


text:
"use strict";
define([], function () {
    function differentiator(stepCollector) {
        var previousPoint = null;
        return function (point, ratio) {
            if (previousPoint) {
                var dx = point.x - previousPoint.x;
                var dy = point.y - previousPoint.y;
                var dz = point.z - previousPoint.z;
                if (dx != 0 || dy != 0 || dz != 0)
                    stepCollector(dx, dy, dz, ratio);
            }
            previousPoint = point;
        };
    }

    function rasterizeLine(line, stepSize, stepCollector) {
        var fromStep = line.from.scale(1 / stepSize).round();
        var toStep = line.to.scale(1 / stepSize).round();
        var dv = toStep.sub(fromStep);
        line.dv = dv;
        var steps = Math.max(Math.abs(dv.x), Math.abs(dv.y), Math.abs(dv.z));
        var filter = differentiator(stepCollector);
        for (var i = 0; i <= steps; i++) {
            var ratio = i / steps;
            filter(fromStep.lerp(toStep, ratio).round(), ratio);
        }
    }

    function rasterizeArc(arc, stepSize, stepCollector, pointAtRatio) {
        var arcSteps = Math.ceil(arc.radius * Math.abs(arc.angularDistance) / stepSize);
        var startPoint = pointAtRatio(0);
        var endPoint = pointAtRatio(1);
        var linearSteps = Math.ceil(Math.abs(endPoint[arc.plane.lastCoord] - startPoint[arc.plane.lastCoord]) / stepSize);
        var steps = Math.max(arcSteps, linearSteps);
        var filter = differentiator(stepCollector);
        for (var i = 0; i <= steps; i++) {
            var ratio = i / steps;
            filter(pointAtRatio(ratio).scale(1 / stepSize).round(), ratio);
        }
    }

    return {
        rasterizeLine: rasterizeLine,
        rasterizeArc: rasterizeArc
    }
});


text:
test:
	./node_modules/.bin/testem

install:
	mkdir -p data lib
	wget -O data/fmr.html http://radio-fmr.net/programmes-emissions/
	wget -O lib/d3.v3.js http://d3js.org/d3.v3.js
	cabal sandbox init
	cabal install --dependencies-only
	cabal run
	npm install

serve:
	python -m SimpleHTTPServer


text:
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider;

namespace Clide.Components.Interop
{
    [PartCreationPolicy(CreationPolicy.Shared)]
    internal class VsHierarchyItemManagerProvider
    {
        [Export(ContractNames.Interop.IVsHierarchyItemManager)]
        [Export(typeof(JoinableLazy<IVsHierarchyItemManager>))]
        readonly JoinableLazy<IVsHierarchyItemManager> hierarchyManager;

        [ImportingConstructor]
        public VsHierarchyItemManagerProvider([Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider services, JoinableTaskContext context)
        {
            hierarchyManager = new JoinableLazy<IVsHierarchyItemManager>(async () =>
            {
                var componentModel = await services.GetServiceAsync(typeof(SComponentModel)) as IComponentModel;

                return componentModel?.GetService<IVsHierarchyItemManager>();
            }, context?.Factory, executeOnMainThread: true);
        }

        [Export(ContractNames.Interop.IVsHierarchyItemManager)]
        public IVsHierarchyItemManager HierarchyManager => hierarchyManager.GetValue();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <help>La classificació de percentil d'aquesta puntuació.</help>
    <label>Percentil</label>
    <name>Percentile__c</name>
</CustomFieldTranslation>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2017 Red Hat, Inc, and individual contributors.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.thorntail</groupId>
    <artifactId>build-parent</artifactId>
    <version>2.2.0.Final-SNAPSHOT</version>
    <relativePath>../../../build-parent/pom.xml</relativePath>
  </parent>

  <artifactId>microprofile-fault-tolerance</artifactId>
  <name>MicroProfile Fault Tolerance</name>
  <description>WildFly: Swarm Fraction for Eclipse MicroProfile Fault Tolerance</description>

  <packaging>jar</packaging>

  <properties>
    <swarm.fraction.stability>stable</swarm.fraction.stability>
    <swarm.fraction.tags>Eclipse MicroProfile,MicroServices,Fault Tolerance</swarm.fraction.tags>
  </properties>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
    <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
               <systemPropertyVariables>
                  <java.util.logging.config.file>${project.build.testOutputDirectory}/logging.properties</java.util.logging.config.file>
               </systemPropertyVariables>
            </configuration>
         </plugin>
      </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>container</artifactId>
    </dependency>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>spi</artifactId>
    </dependency>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>logging</artifactId>
    </dependency>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>cdi</artifactId>
    </dependency>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>hystrix</artifactId>
    </dependency>
    <dependency>
      <groupId>io.thorntail</groupId>
      <artifactId>microprofile-config</artifactId>
    </dependency>
    <dependency>
      <groupId>io.smallrye</groupId>
      <artifactId>smallrye-fault-tolerance</artifactId>
    </dependency>
  </dependencies>

</project>


text:
package rr.org.objectweb.asm.tree;

import java.util.Map;

import rr.org.objectweb.asm.MethodVisitor;
import rr.org.objectweb.asm.Opcodes;
import rr.org.objectweb.asm.tree.AbstractInsnNode;
import rr.org.objectweb.asm.tree.LabelNode;
import rr.org.objectweb.asm.tree.LdcInsnNode;

/**
 * A node that represents an LDC instruction.
 *
 * @author Eric Bruneton
 */
public class LdcInsnNode extends AbstractInsnNode {

    /**
     * The constant to be loaded on the stack. This parameter must be a non null
     * {@link Integer}, a {@link Float}, a {@link Long}, a {@link Double}, a
     * {@link String} or a {@link org.objectweb.asm.Type}.
     */
    public Object cst;

    /**
     * Constructs a new {@link LdcInsnNode}.
     *
     * @param cst
     *            the constant to be loaded on the stack. This parameter must be
     *            a non null {@link Integer}, a {@link Float}, a {@link Long}, a
     *            {@link Double} or a {@link String}.
     */
    public LdcInsnNode(final Object cst) {
        super(Opcodes.LDC);
        this.cst = cst;
    }

    @Override
    public int getType() {
        return LDC_INSN;
    }

    @Override
    public void accept(final MethodVisitor mv) {
        mv.visitLdcInsn(cst);
        acceptAnnotations(mv);
    }

    @Override
    public AbstractInsnNode clone(final Map<LabelNode, LabelNode> labels) {
        return new LdcInsnNode(cst).cloneAnnotations(this);
    }
}


text:
<?php

namespace Oro\Bundle\TranslationBundle;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\TranslationBundle\DependencyInjection\Compiler\TranslatorDependencyPass;

class OroTranslationBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new TranslatorDependencyPass());
    }
}


text:
using System;

#if __UNIFIED__
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using UIKit;
#else
using MonoTouch.CoreGraphics;
using MonoTouch.Foundation;
using MonoTouch.ObjCRuntime;
using MonoTouch.UIKit;
using CGRect = System.Drawing.RectangleF;
using nfloat = System.Single;
#endif

namespace ChameleonFramework
{
    // @interface ChameleonConstants : NSObject
    [BaseType(typeof(NSObject))]
    interface ChameleonConstants
    {
        // extern double ChameleonVersionNumber;
        //[Field("ChameleonVersionNumber", "__Internal")]
        //double ChameleonVersionNumber { get; }

        // extern const unsigned char [] ChameleonVersionString;
        //[Field("ChameleonVersionString", "__Internal")]
        //IntPtr ChameleonVersionString { get; }

        // extern const UIStatusBarStyle UIStatusBarStyleContrast;
        [Field("UIStatusBarStyleContrast", "__Internal")]
        UIStatusBarStyle UIStatusBarStyleContrast { get; }
    }

    // @interface Chameleon (UIColor)
    [Category]
    [BaseType(typeof(UIColor))]
    interface ChameleonColor
    {
        // @property (nonatomic, strong) UIImage * gradientImage;
        [Export("gradientImage", ArgumentSemantic.Strong)]
        UIImage GradientImage();

        // +(UIColor *)flatBlackColor;
        [Static]
        [Export("flatBlackColor")]

        UIColor FlatBlackColor { get; }

        // +(UIColor *)flatBlueColor;
        [Static]
        [Export("flatBlueColor")]

        UIColor FlatBlueColor { get; }

        // +(UIColor *)flatBrownColor;
        [Static]
        [Export("flatBrownColor")]

        UIColor FlatBrownColor { get; }

        // +(UIColor *)flatCoffeeColor;
        [Static]
        [Export("flatCoffeeColor")]

        UIColor FlatCoffeeColor { get; }

        // +(UIColor *)flatForestGreenColor;
        [Static]
        [Export("flatForestGreenColor")]

        UIColor FlatForestGreenColor { get; }

        // +(UIColor *)flatGrayColor;
        [Static]
        [Export("flatGrayColor")]

        UIColor FlatGrayColor { get; }

        // +(UIColor *)flatGreenColor;
        [Static]
        [Export("flatGreenColor")]

        UIColor FlatGreenColor { get; }

        // +(UIColor *)flatLimeColor;
        [Static]
        [Export("flatLimeColor")]

        UIColor FlatLimeColor { get; }

        // +(UIColor *)flatMagentaColor;
        [Static]
        [Export("flatMagentaColor")]

        UIColor FlatMagentaColor { get; }

        // +(UIColor *)flatMaroonColor;
        [Static]
        [Export("flatMaroonColor")]

        UIColor FlatMaroonColor { get; }

        // +(UIColor *)flatMintColor;
        [Static]
        [Export("flatMintColor")]

        UIColor FlatMintColor { get; }

        // +(UIColor *)flatNavyBlueColor;
        [Static]
        [Export("flatNavyBlueColor")]

        UIColor FlatNavyBlueColor { get; }

        // +(UIColor *)flatOrangeColor;
        [Static]
        [Export("flatOrangeColor")]

        UIColor FlatOrangeColor { get; }

        // +(UIColor *)flatPinkColor;
        [Static]
        [Export("flatPinkColor")]

        UIColor FlatPinkColor { get; }

        // +(UIColor *)flatPlumColor;
        [Static]
        [Export("flatPlumColor")]

        UIColor FlatPlumColor { get; }

        // +(UIColor *)flatPowderBlueColor;
        [Static]
        [Export("flatPowderBlueColor")]

        UIColor FlatPowderBlueColor { get; }

        // +(UIColor *)flatPurpleColor;
        [Static]
        [Export("flatPurpleColor")]

        UIColor FlatPurpleColor { get; }

        // +(UIColor *)flatRedColor;
        [Static]
        [Export("flatRedColor")]

        UIColor FlatRedColor { get; }

        // +(UIColor *)flatSandColor;
        [Static]
        [Export("flatSandColor")]

        UIColor FlatSandColor { get; }

        // +(UIColor *)flatSkyBlueColor;
        [Static]
        [Export("flatSkyBlueColor")]

        UIColor FlatSkyBlueColor { get; }

        // +(UIColor *)flatTealColor;
        [Static]
        [Export("flatTealColor")]

        UIColor FlatTealColor { get; }

        // +(UIColor *)flatWatermelonColor;
        [Static]
        [Export("flatWatermelonColor")]

        UIColor FlatWatermelonColor { get; }

        // +(UIColor *)flatWhiteColor;
        [Static]
        [Export("flatWhiteColor")]

        UIColor FlatWhiteColor { get; }

        // +(UIColor *)flatYellowColor;
        [Static]
        [Export("flatYellowColor")]

        UIColor FlatYellowColor { get; }

        // +(UIColor *)flatBlackColorDark;
        [Static]
        [Export("flatBlackColorDark")]

        UIColor FlatBlackColorDark { get; }

        // +(UIColor *)flatBlueColorDark;
        [Static]
        [Export("flatBlueColorDark")]

        UIColor FlatBlueColorDark { get; }

        // +(UIColor *)flatBrownColorDark;
        [Static]
        [Export("flatBrownColorDark")]

        UIColor FlatBrownColorDark { get; }

        // +(UIColor *)flatCoffeeColorDark;
        [Static]
        [Export("flatCoffeeColorDark")]

        UIColor FlatCoffeeColorDark { get; }

        // +(UIColor *)flatForestGreenColorDark;
        [Static]
        [Export("flatForestGreenColorDark")]

        UIColor FlatForestGreenColorDark { get; }

        // +(UIColor *)flatGrayColorDark;
        [Static]
        [Export("flatGrayColorDark")]

        UIColor FlatGrayColorDark { get; }

        // +(UIColor *)flatGreenColorDark;
        [Static]
        [Export("flatGreenColorDark")]

        UIColor FlatGreenColorDark { get; }

        // +(UIColor *)flatLimeColorDark;
        [Static]
        [Export("flatLimeColorDark")]

        UIColor FlatLimeColorDark { get; }

        // +(UIColor *)flatMagentaColorDark;
        [Static]
        [Export("flatMagentaColorDark")]

        UIColor FlatMagentaColorDark { get; }

        // +(UIColor *)flatMaroonColorDark;
        [Static]
        [Export("flatMaroonColorDark")]

        UIColor FlatMaroonColorDark { get; }

        // +(UIColor *)flatMintColorDark;
        [Static]
        [Export("flatMintColorDark")]

        UIColor FlatMintColorDark { get; }

        // +(UIColor *)flatNavyBlueColorDark;
        [Static]
        [Export("flatNavyBlueColorDark")]

        UIColor FlatNavyBlueColorDark { get; }

        // +(UIColor *)flatOrangeColorDark;
        [Static]
        [Export("flatOrangeColorDark")]

        UIColor FlatOrangeColorDark { get; }

        // +(UIColor *)flatPinkColorDark;
        [Static]
        [Export("flatPinkColorDark")]

        UIColor FlatPinkColorDark { get; }

        // +(UIColor *)flatPlumColorDark;
        [Static]
        [Export("flatPlumColorDark")]

        UIColor FlatPlumColorDark { get; }

        // +(UIColor *)flatPowderBlueColorDark;
        [Static]
        [Export("flatPowderBlueColorDark")]

        UIColor FlatPowderBlueColorDark { get; }

        // +(UIColor *)flatPurpleColorDark;
        [Static]
        [Export("flatPurpleColorDark")]

        UIColor FlatPurpleColorDark { get; }

        // +(UIColor *)flatRedColorDark;
        [Static]
        [Export("flatRedColorDark")]

        UIColor FlatRedColorDark { get; }

        // +(UIColor *)flatSandColorDark;
        [Static]
        [Export("flatSandColorDark")]

        UIColor FlatSandColorDark { get; }

        // +(UIColor *)flatSkyBlueColorDark;
        [Static]
        [Export("flatSkyBlueColorDark")]

        UIColor FlatSkyBlueColorDark { get; }

        // +(UIColor *)flatTealColorDark;
        [Static]
        [Export("flatTealColorDark")]

        UIColor FlatTealColorDark { get; }

        // +(UIColor *)flatWatermelonColorDark;
        [Static]
        [Export("flatWatermelonColorDark")]

        UIColor FlatWatermelonColorDark { get; }

        // +(UIColor *)flatWhiteColorDark;
        [Static]
        [Export("flatWhiteColorDark")]

        UIColor FlatWhiteColorDark { get; }

        // +(UIColor *)flatYellowColorDark;
        [Static]
        [Export("flatYellowColorDark")]

        UIColor FlatYellowColorDark { get; }

        // +(UIColor *)randomFlatColor;
        [Static]
        [Export("randomFlatColor")]

        UIColor RandomFlatColor { get; }

        // +(UIColor *)colorWithRandomFlatColorExcludingColorsInArray:(NSArray *)colors;
        [Static]
        [Export("colorWithRandomFlatColorExcludingColorsInArray:")]

        UIColor ColorWithRandomFlatColorExcludingColorsInArray(NSObject[] colors);

        // +(UIColor *)colorWithRandomColorInArray:(NSArray *)colors;
        [Static]
        [Export("colorWithRandomColorInArray:")]

        UIColor ColorWithRandomColorInArray(NSObject[] colors);

        // +(UIColor *)colorWithRandomFlatColorOfShadeStyle:(UIShadeStyle)shadeStyle;
        [Static]
        [Export("colorWithRandomFlatColorOfShadeStyle:")]
        UIColor ColorWithRandomFlatColorOfShadeStyle(UIShadeStyle shadeStyle);

        // +(UIColor *)colorWithRandomFlatColorOfShadeStyle:(UIShadeStyle)shadeStyle withAlpha:(CGFloat)alpha;
        [Static]
        [Export("colorWithRandomFlatColorOfShadeStyle:withAlpha:")]
        UIColor ColorWithRandomFlatColorOfShadeStyle(UIShadeStyle shadeStyle, nfloat alpha);

        // +(UIColor *)colorWithAverageColorFromImage:(UIImage *)image;
        [Static]
        [Export("colorWithAverageColorFromImage:")]
        UIColor GetImageAverageColor(UIImage image);

        // +(UIColor *)colorWithAverageColorFromImage:(UIImage *)image withAlpha:(CGFloat)alpha;
        [Static]
        [Export("colorWithAverageColorFromImage:withAlpha:")]
        UIColor GetImageAverageColor(UIImage image, nfloat alpha);

        // +(UIColor *)colorWithComplementaryFlatColorOf:(UIColor *)color;
        [Static]
        [Export("colorWithComplementaryFlatColorOf:")]
        UIColor ColorWithComplementaryFlatColorOf(UIColor color);

        // +(UIColor *)colorWithComplementaryFlatColorOf:(UIColor *)color withAlpha:(CGFloat)alpha;
        [Static]
        [Export("colorWithComplementaryFlatColorOf:withAlpha:")]
        UIColor ColorWithComplementaryFlatColorOf(UIColor color, nfloat alpha);

        // +(UIColor *)colorWithContrastingBlackOrWhiteColorOn:(UIColor *)backgroundColor isFlat:(BOOL)flat;
        [Static]
        [Export("colorWithContrastingBlackOrWhiteColorOn:isFlat:")]
        UIColor ColorWithContrastingBlackOrWhiteColorOn(UIColor backgroundColor, bool flat);

        // +(UIColor *)colorWithContrastingBlackOrWhiteColorOn:(UIColor *)backgroundColor isFlat:(BOOL)flat alpha:(CGFloat)alpha;
        [Static]
        [Export("colorWithContrastingBlackOrWhiteColorOn:isFlat:alpha:")]
        UIColor ColorWithContrastingBlackOrWhiteColorOn(UIColor backgroundColor, bool flat, nfloat alpha);

        // +(UIColor *)colorWithGradientStyle:(UIGradientStyle)gradientStyle withFrame:(CGRect)frame andColors:(NSArray *)colors;
        [Static]
        [Export("colorWithGradientStyle:withFrame:andColors:")]

        UIColor ColorWithGradientStyle(UIGradientStyle gradientStyle, CGRect frame, NSObject[] colors);

        // +(UIColor *)colorWithHexString:(NSString *)string;
        [Static]
        [Export("colorWithHexString:")]
        UIColor ColorWithHexString(string @string);

        // +(UIColor *)colorWithHexString:(NSString *)string withAlpha:(CGFloat)alpha;
        [Static]
        [Export("colorWithHexString:withAlpha:")]
        UIColor ColorWithHexString(string @string, nfloat alpha);

        // -(UIColor *)flatten;
        [Export("flatten")]

        UIColor Flatten();

        // -(UIColor *)darkenByPercentage:(CGFloat)percentage;
        [Export("darkenByPercentage:")]
        UIColor DarkenByPercentage(nfloat percentage);

        // -(NSString *)hexValue;
        [Export("hexValue")]

        string HexValue();

        // -(UIColor *)lightenByPercentage:(CGFloat)percentage;
        [Export("lightenByPercentage:")]
        UIColor LightenByPercentage(nfloat percentage);

        // +(UIColor *)colorWithFlatVersionOf:(UIColor *)color __attribute__((deprecated(" Use -flatten: instead (First deprecated in Chameleon 2.0).")));
        [Static]
        [Export("colorWithFlatVersionOf:")]
        UIColor ColorWithFlatVersionOf(UIColor color);
    }

    // @interface Chameleon (NSArray)
    [Static]
    [BaseType(typeof(NSObject), Name = "NSArray")]
    interface ChameleonColorArray
    {
        // +(NSArray *)arrayOfColorsWithColorScheme:(ColorScheme)colorScheme usingColor:(UIColor *)color withFlatScheme:(BOOL)isFlatScheme;
        [Static]
        [Export("arrayOfColorsWithColorScheme:usingColor:withFlatScheme:")]
        UIColor[] GetColors(ColorScheme colorScheme, UIColor color, bool isFlatScheme);

        // +(NSArray *)arrayOfColorsFromImage:(UIImage *)image withFlatScheme:(BOOL)isFlatScheme;
        [Static]
        [Export("arrayOfColorsFromImage:withFlatScheme:")]
        UIColor[] GetColors(UIImage image, bool isFlatScheme);

        // deprecated: "Use -arrayOfColorsWithColorScheme:usingColor:withFlatScheme: instead (First deprecated in Chameleon 2.0)."
        //      // +(NSArray *)arrayOfColorsWithColorScheme:(ColorScheme)colorScheme with:(UIColor *)color flatScheme:(BOOL)isFlatScheme __attribute__((deprecated(" Use -arrayOfColorsWithColorScheme:usingColor:withFlatScheme: instead (First deprecated in Chameleon 2.0).")));
        //      [Static]
        //      [Export ("arrayOfColorsWithColorScheme:with:flatScheme:")]
        //      [Verify (StronglyTypedNSArray)]
        //      NSObject[] ArrayOfColorsWithColorScheme (ColorScheme colorScheme, UIColor color, bool isFlatScheme);
    }

    // @interface Chameleon (UINavigationController)
    [Category]
    [BaseType(typeof(UINavigationController))]
    interface UINavigationController_Chameleon
    {
        // -(void)setStatusBarStyle:(UIStatusBarStyle)statusBarStyle;
        [Export("setStatusBarStyle:")]
        void SetStatusBarStyle(UIStatusBarStyle statusBarStyle);

        // @property (assign, nonatomic) BOOL hidesNavigationBarHairline;
        [Export("hidesNavigationBarHairline")]
        bool HidesNavigationBarHairline();
    }

    // @interface Chameleon (UIViewController)
    [Category]
    [BaseType(typeof(UIViewController))]
    interface UIViewController_Chameleon
    {
        // -(void)setThemeUsingPrimaryColor:(UIColor *)primaryColor withContentStyle:(UIContentStyle)contentStyle;
        [Export("setThemeUsingPrimaryColor:withContentStyle:")]
        void SetThemeUsingPrimaryColor(UIColor primaryColor, ContentStyle contentStyle);

        // -(void)setThemeUsingPrimaryColor:(UIColor *)primaryColor withSecondaryColor:(UIColor *)secondaryColor andContentStyle:(UIContentStyle)contentStyle;
        [Export("setThemeUsingPrimaryColor:withSecondaryColor:andContentStyle:")]
        void SetThemeUsingPrimaryColor(UIColor primaryColor, UIColor secondaryColor, ContentStyle contentStyle);

        // -(void)setThemeUsingPrimaryColor:(UIColor *)primaryColor withSecondaryColor:(UIColor *)secondaryColor usingFontName:(NSString *)fontName andContentStyle:(UIContentStyle)contentStyle;
        [Export("setThemeUsingPrimaryColor:withSecondaryColor:usingFontName:andContentStyle:")]
        void SetThemeUsingPrimaryColor(UIColor primaryColor, UIColor secondaryColor, string fontName, ContentStyle contentStyle);

        // -(void)setStatusBarStyle:(UIStatusBarStyle)statusBarStyle;
        [Export("setStatusBarStyle:")]
        void SetStatusBarStyle(UIStatusBarStyle statusBarStyle);
    }

    // @interface Chameleon : NSObject
    [BaseType(typeof(NSObject))]
    interface Chameleon
    {
        // +(void)setGlobalThemeUsingPrimaryColor:(UIColor *)primaryColor withContentStyle:(UIContentStyle)contentStyle;
        [Static]
        [Export("setGlobalThemeUsingPrimaryColor:withContentStyle:")]
        void SetGlobalTheme(UIColor primaryColor, UIContentStyle contentStyle);

        // +(void)setGlobalThemeUsingPrimaryColor:(UIColor *)primaryColor withSecondaryColor:(UIColor *)secondaryColor andContentStyle:(UIContentStyle)contentStyle;
        [Static]
        [Export("setGlobalThemeUsingPrimaryColor:withSecondaryColor:andContentStyle:")]
        void SetGlobalTheme(UIColor primaryColor, UIColor secondaryColor, UIContentStyle contentStyle);

        // +(void)setGlobalThemeUsingPrimaryColor:(UIColor *)primaryColor withSecondaryColor:(UIColor *)secondaryColor usingFontName:(NSString *)fontName andContentStyle:(UIContentStyle)contentStyle;
        [Static]
        [Export("setGlobalThemeUsingPrimaryColor:withSecondaryColor:usingFontName:andContentStyle:")]
        void SetGlobalTheme(UIColor primaryColor, UIColor secondaryColor, string fontName, UIContentStyle contentStyle);
    }

    // @interface Chameleon (UIButton)
    [Category]
    [BaseType(typeof(UIButton))]
    interface UIButton_Chameleon
    {
        // -(void)setSubstituteFontName:(NSString *)name __attribute__((annotate("ui_appearance_selector")));
        [Export("setSubstituteFontName:")]
        void SetSubstituteFontName(string name);
    }

    // @interface Chameleon (UILabel)
    [Category]
    [BaseType(typeof(UILabel))]
    interface UILabel_Chameleon
    {
        // -(void)setSubstituteFontName:(NSString *)name __attribute__((annotate("ui_appearance_selector")));
        [Export("setSubstituteFontName:")]
        void SetSubstituteFontName(string name);
    }

    // @interface ChameleonPrivate (UIColor)
    [Category]
    [BaseType(typeof(UIColor))]
    interface UIColor_ChameleonPrivate
    {
        // @property (readwrite, nonatomic) NSUInteger count;
        [Export("count")]
        nuint Count();

        // +(UIColor *)colorFromImage:(UIImage *)image atPoint:(CGPoint)point;
        [Static]
        [Export("colorFromImage:atPoint:")]
        UIColor ColorFromImage(UIImage image, CGPoint point);

        // -(UIColor *)colorWithMinimumSaturation:(CGFloat)saturation;
        [Export("colorWithMinimumSaturation:")]
        UIColor ColorWithMinimumSaturation(nfloat saturation);

        // -(BOOL)isDistinct:(UIColor *)color;
        [Export("isDistinct:")]
        bool IsDistinct(UIColor color);

        // -(BOOL)getValueForX:(CGFloat *)X valueForY:(CGFloat *)Y valueForZ:(CGFloat *)Z alpha:(CGFloat *)alpha;
        [Export("getValueForX:valueForY:valueForZ:alpha:")]
        unsafe bool GetValueForX(IntPtr X, IntPtr Y, IntPtr Z, IntPtr alpha);

        // -(BOOL)getLightness:(CGFloat *)L valueForA:(CGFloat *)A valueForB:(CGFloat *)B alpha:(CGFloat *)alpha;
        [Export("getLightness:valueForA:valueForB:alpha:")]
        unsafe bool GetLightness(IntPtr L, IntPtr A, IntPtr B, IntPtr alpha);
    }

    // @interface ChameleonPrivate (UIImage)
    [Category]
    [BaseType(typeof(UIImage))]
    interface UIImage_ChameleonPrivate
    {
        // +(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize;
        [Static]
        [Export("imageWithImage:scaledToSize:")]
        UIImage ImageWithImage(UIImage image, CGSize newSize);

        // -(UIImage *)imageScaledToSize:(CGSize)newSize;
        [Export("imageScaledToSize:")]
        UIImage ImageScaledToSize(CGSize newSize);
    }

    // @interface ChameleonPrivate (UIView)
    [Category]
    [BaseType(typeof(UIView))]
    interface UIView_ChameleonPrivate
    {
        // -(BOOL)isTopViewInWindow;
        [Export("isTopViewInWindow")]
        bool IsTopViewInWindow();

        // -(UIView *)findTopMostViewForPoint:(CGPoint)point;
        [Export("findTopMostViewForPoint:")]
        UIView FindTopMostViewForPoint(CGPoint point);
    }

    // @interface UIViewAppearance_Swift (UIView)
    [Category]
    [BaseType(typeof(UIView))]
    interface UIView_UIViewAppearance_Swift
    {
        // +(instancetype)appearanceWhenContainedWithin:(NSArray *)containers;
        [Static]
        [Export("appearanceWhenContainedWithin:")]

        UIView AppearanceWhenContainedWithin(NSObject[] containers);
    }
}


text:
import styled, { css } from "styled-components";
import { margin } from "styled-system";

import Icon from "../icon";
import StyledIcon from "../icon/icon.style";
import baseTheme from "../../style/themes/base";
import Help from "../help";
import Typography from "../typography";
import Hr from "../hr";
import Link from "../link";

const StyledHeading = styled.div`
  width: 100%;
  ${margin}
`;

StyledHeading.defaultProps = {
  theme: baseTheme,
};

const StyledHeaderContent = styled.div`
  display: inline-flex;
  align-items: flex-end;
`;

type StyledHeaderProps = {
  divider?: boolean;
  subheader?: boolean;
  hasBackLink?: boolean;
};

const StyledHeader = styled.div<StyledHeaderProps>`
  ${({ divider, subheader, hasBackLink }) => css`
    ${subheader &&
    css`
      margin-bottom: 16px;
    `}

    ${divider &&
    css`
      margin-bottom: 15px;
    `}

    ${divider &&
    !subheader &&
    css`
      margin-bottom: 20px;
    `}

    ${hasBackLink &&
    css`
      display: grid;
      grid-template-columns: min-content auto;
    `}
  `}
`;

const StyledHeadingBackButton = styled(Link)`
  margin-right: 5px;
  margin-top: 2px;

  a,
  button {
    margin: 0 1px 0 0;
    text-decoration: none;

    &:focus {
      background-color: transparent;
      outline: 3px solid var(--colorsSemanticFocus500);
    }

    &:hover {
      ${StyledIcon} {
        color: var(--colorsActionMinor600);
      }
    }

    ${StyledIcon} {
      margin-right: 0;
      display: inline-flex;
      color: var(--colorsActionMinor500);
    }
  }
`;

type StyledHeadingTitleProps = {
  withMargin?: boolean;
};

const StyledHeadingTitle = styled(Typography)<StyledHeadingTitleProps>`
  line-height: 32px;
  ${({ withMargin }) =>
    withMargin
      ? css`
          margin-right: 16px;
        `
      : null}
`;

const StyledHeadingPills = styled.span`
  line-height: 32px;
  display: inline-block;
  vertical-align: top;
`;

type StyledSubHeaderProps = {
  hasBackLink?: boolean;
  hasSeparator?: boolean;
};

const StyledSubHeader = styled.div<StyledSubHeaderProps>`
  margin-top: 5px;
  grid-row: 2;

  ${({ hasBackLink }) =>
    hasBackLink &&
    css`
      grid-column: 2;
    `}

  ${({ hasSeparator }) =>
    hasSeparator &&
    css`
      grid-row: 3;
      margin-top: 0px;
    `}
`;

const StyledHeadingIcon = styled(Icon)`
  height: 30px;

  &:before,
  &${StyledIcon}:before {
    font-size: 24px;
  }
`;

const StyledSeparator = styled.hr`
  border-top: 2px solid var(--colorsUtilityMajor100);
  margin: 10px 0 8px;
  text-align: left;
  width: 50px;
`;

const StyledDivider = styled(Hr)`
  margin: 15px 0 20px;
`;

const StyledHeaderHelp = styled(Help)`
  display: inline-block;
  margin-left: -6px;
  margin-right: 16px;
  position: relative;
  top: -4px;
  height: 22px;
`;

export {
  StyledHeadingIcon,
  StyledHeading,
  StyledSubHeader,
  StyledHeader,
  StyledSeparator,
  StyledHeaderHelp,
  StyledHeadingTitle,
  StyledDivider,
  StyledHeaderContent,
  StyledHeadingBackButton,
  StyledHeadingPills,
};


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Appendix F. Third Party Licenses</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Oracle NoSQL Database Administrator's Guide" />
    <link rel="up" href="index.html" title="Oracle NoSQL Database Administrator's Guide" />
    <link rel="prev" href="diag_stats.html" title="Key Distribution Statistics Utility" />

Library Version 12.1.3.5

          Appendix F. Third Party Licenses

          Prev

Appendix F. Third Party Licenses

        All of the third party licenses used by Oracle NoSQL Database are
        described in the LICENSE.txt file, which you can
        find in your KVHOME directory.

          Prev

          Key Distribution Statistics Utility

            Home


text:
package org.apache.felix.ipojo.test.compatibility;

import org.apache.felix.ipojo.test.compatibility.service.CheckService;
import org.junit.Test;
import org.ops4j.pax.exam.Option;

import static org.fest.assertions.Assertions.assertThat;
import static org.ops4j.pax.exam.CoreOptions.bundle;

/**
 * Check a configuration using Equinox SCR 1.4.100 (Declarative Services).
 * iPOJO provider is consumed by a component using SCR.
 *
 *
 * This test is intended to pass on Equinox only.
 */
public class TestBeingConsumedByEquinoxSCR1_4_100 extends Common {

    public static String DS_URL = "http://people.apache.org/~clement/ipojo/bundle4tests/org.eclipse.equinox.ds_1.4.101.v20130813-1853.jar";

    public static String UTILS_URL = "http://people.apache.org/~clement/ipojo/bundle4tests/org.eclipse.equinox.util_1.0.500.v20130404-1337.jar";

    @Override
    public Option[] bundles() {
        // We must not deploy the Equinox DS on Felix and KF
        if (! isEquinox()) {
            return new Option[0];
        }
        return new Option[] {
                bundle(DS_URL),
                bundle(UTILS_URL),
                iPOJOHelloProvider(),
                SCRHelloConsumer()
        };
    }

    @Test
    public void test() {
        if (! isEquinox()) {
            System.out.println("Test executed on Equinox only");
            return;
        }
        CheckService checker = osgiHelper.waitForService(CheckService.class, null, 1000);
        assertThat(checker).isNotNull();
        assertThat(checker.data().get("result")).isEqualTo("hello john doe");
    }
}


text:
var SerialPort = require("../serialport").SerialPort;
var sys = require("sys");

var serial_port = new SerialPort("/dev/master");
serial_port.write("It worked!\r");
serial_port.close();


text:
/**
* @fileoverview v1
* @name index.js
* @author Yoshiya Ito <myon53@gmail.com>
*/
import Express from 'express';
import Twitter from './twitter';
import Home from './home';

export default class V1 {
  constructor() {
    this.router = new Express.Router();
    this.router.get('/twitter', Twitter.index);
    this.router.get('/home', Home.index);
  }
}


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();

/**
 * Import database connection
 */

/* Database import (with open/close connection) */
require('./models/db');

/**
 * Import routes
 */

/* Server routes import */
var routes = require('./routes/index');
/* API routes import */
var routesAPI = require('./routes/api/locations');

/**
 * Default config
 */

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

/**
 * Routes instructions
 */

/* Tell app to use "routes" (not routesAPI) when "/" */
app.use('/', routes);
/* Tell app to use "routesAPI" (not routes) when "/api". And all routes in './routes/api/index' now has '/api' prefix of URL automatically */
app.use('/api', routesAPI);

/**
 * Default config
 */

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
import binascii

from ..ecdsa import generator_secp256k1, verify as ecdsa_verify
from ..encoding import public_pair_to_bitcoin_address, sec_to_public_pair
from ..networks import address_prefix_for_netcode
from ..serialize import b2h_rev

from pycoin.tx.pay_to import (
    script_obj_from_script, ScriptMultisig, ScriptPayToAddress, ScriptPayToPublicKey
)
from pycoin.tx.script.check_signature import parse_signature_blob
from pycoin.tx.script.der import UnexpectedDER
from pycoin.tx.script.tools import get_opcode

class NoAddressesForScriptTypeError(Exception):
    pass

def who_signed_tx(tx, tx_in_idx, netcode='BTC'):
    """
    Given a transaction (tx) an input index (tx_in_idx), attempt to figure
    out which addresses where used in signing (so far). This method
    depends on tx.unspents being properly configured. This should work on
    partially-signed MULTISIG transactions (it will return as many
    addresses as there are good signatures).
    Returns a list of ( address, sig_type ) pairs.
    Raises NoAddressesForScriptTypeError if addresses cannot be determined
    for the input's script.
    TODO: This does not yet support P2SH.
    """
    tx_in = tx.txs_in[tx_in_idx]
    parent_tx_out_idx = tx_in.previous_index
    parent_tx_out_script = tx.unspents[tx_in_idx].script
    script_obj = script_obj_from_script(parent_tx_out_script)
    signed_by = []

    if type(script_obj) not in (ScriptPayToAddress, ScriptPayToPublicKey, ScriptMultisig):
        raise NoAddressesForScriptTypeError(
            'unable to determine signing addresses for script type of parent tx {}[{}]'
            .format(b2h_rev(tx_in.previous_hash), parent_tx_out_idx))

    script = tx_in.script
    pc = 0
    while pc < len(script):
        opcode, data, pc = get_opcode(script, pc)
        if data is None:
            continue
        try:
            sig_pair, sig_type = parse_signature_blob(data)
        except (ValueError, TypeError, binascii.Error, UnexpectedDER):
            continue

        sig_hash = tx.signature_hash(parent_tx_out_script, parent_tx_out_idx, sig_type)

        for sec_key in script_obj.sec_keys:
            public_pair = sec_to_public_pair(sec_key)

            if ecdsa_verify(generator_secp256k1, public_pair, sig_hash, sig_pair):
                addr_pfx = address_prefix_for_netcode(netcode)
                addr = public_pair_to_bitcoin_address(public_pair, address_prefix=addr_pfx)
                signed_by.append((addr, sig_type))
    return signed_by


text:
@interface DMConfig()
@property (nonatomic, strong) NSDictionary* config;
@end

@implementation DMConfig

+ (DMConfig*)shared {
    static DMConfig* shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[self alloc] initWithName:@"Config"];
    });
    return shared;
}

- (instancetype)initWithName:(NSString*)name {
    if(self = [super init]) {
        NSString* path = [[NSBundle bundleForClass:self.class] pathForResource:name ofType:@"plist"];
        if(path) {
            self.config = [[NSDictionary alloc] initWithContentsOfFile:path];
        }
    }
    return self;
}

- (id)forKeys:(NSArray*)keys {
    return [keys inject:self.config into:^(NSDictionary* context, NSString* key) {
        return context[key];
    }];
}

- (id)objectForKeyedSubscript:(NSString*)key {
    if(!key) return nil;
    return [self forKeys:@[key]] ?: [self forKeys:[key componentsSeparatedByString:@"."]];
}

@end


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>gluon.messageboxhandler</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

web2py Web Framework

        Package gluon ::
        Module messageboxhandler

[hide private]

[frames] | no frames]

Module messageboxhandler

source code

        Classes
        [hide private]

        MessageBoxHandler

        NotifySendHandler

        Variables
        [hide private]

        __package__ = 'gluon'

         Home

         Trees

         Indices

         Help

web2py Web Framework

    Generated by Epydoc 3.0.1 on Sat Mar 29 21:55:15 2014

      http://epydoc.sourceforge.net


text:
namespace clang {
namespace tidy {
namespace performance {
namespace {

void recordFixes(const VarDecl &Var, ASTContext &Context,
                 DiagnosticBuilder &Diagnostic) {
  Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
  if (!Var.getType().isLocalConstQualified())
    Diagnostic << utils::fixit::changeVarDeclToConst(Var);
}

} // namespace

using namespace ::clang::ast_matchers;
using utils::decl_ref_expr::isOnlyUsedAsConst;

UnnecessaryCopyInitialization::UnnecessaryCopyInitialization(
    StringRef Name, ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      AllowedTypes(
          utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}

void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) {
  auto ConstReference = referenceType(pointee(qualType(isConstQualified())));

  // Match method call expressions where the `this` argument is only used as
  // const, this will be checked in `check()` part. This returned const
  // reference is highly likely to outlive the local const reference of the
  // variable being declared. The assumption is that the const reference being
  // returned either points to a global static variable or to a member of the
  // called object.
  auto ConstRefReturningMethodCall =
      cxxMemberCallExpr(callee(cxxMethodDecl(returns(ConstReference))),
                        on(declRefExpr(to(varDecl().bind("objectArg")))));
  auto ConstRefReturningFunctionCall =
      callExpr(callee(functionDecl(returns(ConstReference))),
               unless(callee(cxxMethodDecl())));

  auto localVarCopiedFrom = [this](const internal::Matcher<Expr> &CopyCtorArg) {
    return compoundStmt(
               forEachDescendant(
                   declStmt(
                       has(varDecl(hasLocalStorage(),
                                   hasType(qualType(
                                       hasCanonicalType(
                                           matchers::isExpensiveToCopy()),
                                       unless(hasDeclaration(namedDecl(
                                           matchers::matchesAnyListedName(
                                               AllowedTypes)))))),
                                   unless(isImplicit()),
                                   hasInitializer(
                                       cxxConstructExpr(
                                           hasDeclaration(cxxConstructorDecl(
                                               isCopyConstructor())),
                                           hasArgument(0, CopyCtorArg))
                                           .bind("ctorCall")))
                               .bind("newVarDecl")))
                       .bind("declStmt")))
        .bind("blockStmt");
  };

  Finder->addMatcher(localVarCopiedFrom(anyOf(ConstRefReturningFunctionCall,
                                              ConstRefReturningMethodCall)),
                     this);

  Finder->addMatcher(localVarCopiedFrom(declRefExpr(
                         to(varDecl(hasLocalStorage()).bind("oldVarDecl")))),
                     this);
}

void UnnecessaryCopyInitialization::check(
    const MatchFinder::MatchResult &Result) {
  const auto *NewVar = Result.Nodes.getNodeAs<VarDecl>("newVarDecl");
  const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>("oldVarDecl");
  const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>("objectArg");
  const auto *BlockStmt = Result.Nodes.getNodeAs<Stmt>("blockStmt");
  const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");

  // Do not propose fixes if the DeclStmt has multiple VarDecls or in macros
  // since we cannot place them correctly.
  bool IssueFix =
      Result.Nodes.getNodeAs<DeclStmt>("declStmt")->isSingleDecl() &&
      !NewVar->getLocation().isMacroID();

  // A constructor that looks like T(const T& t, bool arg = false) counts as a
  // copy only when it is called with default arguments for the arguments after
  // the first.
  for (unsigned int i = 1; i < CtorCall->getNumArgs(); ++i)
    if (!CtorCall->getArg(i)->isDefaultArgument())
      return;

  if (OldVar == nullptr) {
    handleCopyFromMethodReturn(*NewVar, *BlockStmt, IssueFix, ObjectArg,
                               *Result.Context);
  } else {
    handleCopyFromLocalVar(*NewVar, *OldVar, *BlockStmt, IssueFix,
                           *Result.Context);
  }
}

void UnnecessaryCopyInitialization::handleCopyFromMethodReturn(
    const VarDecl &Var, const Stmt &BlockStmt, bool IssueFix,
    const VarDecl *ObjectArg, ASTContext &Context) {
  bool IsConstQualified = Var.getType().isConstQualified();
  if (!IsConstQualified && !isOnlyUsedAsConst(Var, BlockStmt, Context))
    return;
  if (ObjectArg != nullptr &&
      !isOnlyUsedAsConst(*ObjectArg, BlockStmt, Context))
    return;

  auto Diagnostic =
      diag(Var.getLocation(),
           IsConstQualified ? "the const qualified variable %0 is "
                              "copy-constructed from a const reference; "
                              "consider making it a const reference"
                            : "the variable %0 is copy-constructed from a "
                              "const reference but is only used as const "
                              "reference; consider making it a const reference")
      << &Var;
  if (IssueFix)
    recordFixes(Var, Context, Diagnostic);
}

void UnnecessaryCopyInitialization::handleCopyFromLocalVar(
    const VarDecl &NewVar, const VarDecl &OldVar, const Stmt &BlockStmt,
    bool IssueFix, ASTContext &Context) {
  if (!isOnlyUsedAsConst(NewVar, BlockStmt, Context) ||
      !isOnlyUsedAsConst(OldVar, BlockStmt, Context))
    return;

  auto Diagnostic = diag(NewVar.getLocation(),
                         "local copy %0 of the variable %1 is never modified; "
                         "consider avoiding the copy")
                    << &NewVar << &OldVar;
  if (IssueFix)
    recordFixes(NewVar, Context, Diagnostic);
}

void UnnecessaryCopyInitialization::storeOptions(
    ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "AllowedTypes",
                utils::options::serializeStringList(AllowedTypes));
}

} // namespace performance
} // namespace tidy
} // namespace clang


text:
package io.github.azagniotov.stubby4j.utils;

import io.github.azagniotov.stubby4j.stubs.ReflectableStub;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public final class ReflectionUtils {

    // These fields are defined in various Stub* classes, e.g.: StubRequest or StubProxyConfig
    private static List<String> reflectionSkippableProperties =
            Collections.unmodifiableList(Arrays.asList("proxyConfigAsYAML", "webSocketConfigAsYAML", "regexGroups", "fileBytes"));

    private ReflectionUtils() {

    }

    @SuppressWarnings("deprecation")
    public static <T extends ReflectableStub> Map<String, String> getProperties(final T reflectable) throws IllegalAccessException, InvocationTargetException, UnsupportedEncodingException {
        final Map<String, String> properties = new HashMap<>();

        for (final Field field : reflectable.getClass().getDeclaredFields()) {

            AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                return true;
            });

            if (reflectionSkippableProperties.contains(field.getName())) {
                continue;
            }

            final Object fieldObject = ReflectionUtils.getPropertyValue(reflectable, field.getName());
            final String value = StringUtils.objectToString(fieldObject);

            if (!value.equals(StringUtils.NOT_PROVIDED) && !value.equals("{}")) {
                properties.put(StringUtils.toLower(field.getName()), value);
            }
        }

        return properties;
    }

    public static <T extends ReflectableStub> void injectObjectFields(final T reflectable, final String fieldName, final Object value) throws InvocationTargetException, IllegalAccessException {
        final Map<String, Object> fieldAndValue = new HashMap<>();
        fieldAndValue.put(fieldName.toLowerCase(Locale.US), value);
        injectObjectFields(reflectable, fieldAndValue);
    }

    @SuppressWarnings("deprecation")
    public static <T extends ReflectableStub> void injectObjectFields(final T reflectable, final Map<String, Object> fieldsAndValues) throws InvocationTargetException, IllegalAccessException {

        for (final Field field : reflectable.getClass().getDeclaredFields()) {
            final String fieldName = field.getName().toLowerCase(Locale.US);
            if (fieldsAndValues.containsKey(fieldName)) {
                AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    return true;
                });

                field.set(reflectable, fieldsAndValues.get(fieldName));
            }
        }
    }

    public static Object getPropertyValue(final Object object, final String fieldName) throws InvocationTargetException, IllegalAccessException {
        for (final Method method : object.getClass().getDeclaredMethods()) {
            // e.g.: "responseAsYAML" => StubHttpLifecycle.getResponseAsYAML
            if (method.getName().equalsIgnoreCase("get" + fieldName)) {
                return method.invoke(object);
            }
        }
        return null;
    }
}


text:
package org.hisp.dhis.analytics;

/**
 * Filter operators for measures.
 *
 * @author Lars Helge Overland
 */
public enum MeasureFilter
{
    EQ, GT, GE, LT, LE
}


text:
import mysql

from DBLayout.DBConnection import DBConnection
from EntitiesLayout.FacebookUser import FacebookUser

__author__ = 'David'

class FacebookUserDB:

    def __init__(self):
        self.db = DBConnection()
        print('Create object to access table user in DB.')

    def insertUser(self, user: FacebookUser):
        try:
            cnx = self.db.openConnection()
            cursor = cnx.cursor()
            addFBUserQuery = 'INSERT INTO user(idUser, facebookUserID, firstName, gender, lastName, link, locale, name, username)' \
                             'VALUES (NULL, %s, %s, %s, %s, %s, %s, %s, %s);'
            dataUser = (user.facebookUserId, user.firstName, user.gender, user.lastName, user.link, user.locale, user.name, user.userName)

            cursor.execute(addFBUserQuery, dataUser)
            cnx.commit()
            cursor.close()
            self.db.closeConnection()

        except mysql.connector.Error as err:
            print(err)
            print('Error writing a Facebook User in the DB.')
        except AttributeError as err:
            print('Register can\'t be stored.')

    def readUser(self, id: int):
        mp = {}
        try:
            cnx = self.db.openConnection()
            cursor = cnx.cursor()
            readFBUserQuery = ("SELECT idUser, facebookUserID, firstName, gender, lastName, link, locale, name, username "
                               "FROM user WHERE facebookUserID = %s;")

            dataUser = (id,)

            cursor.execute(readFBUserQuery, dataUser)

            for (idUser, facebookUserID, firstName, gender, lastName, link, locale, name, username) in cursor:
                mp['id'] = facebookUserID
                mp['first_name'] = firstName
                mp['gender'] = gender
                mp['last_name'] = lastName
                mp['link'] = link
                mp['locale'] = locale
                mp['name'] = name
                mp['username'] = username

                user = (FacebookUser(mp))

            cursor.close()
            self.db.closeConnection()

        except mysql.connector.Error as ex:
            print(ex)
            print('Error reading a Facebook User in the DB.')
        return user

    def readUsers(self):
        users = []
        mp = {}
        try:
            cnx = self.db.openConnection()
            cursor = cnx.cursor()
            readFBUserQuery = 'SELECT idUser, facebookUserID, firstName, gender, lastName, link, locale, name, username ' \
                              'FROM user;'

            cursor.execute(readFBUserQuery)

            for (idUser, facebookUserID, firstName, gender, lastName, link, locale, name, username) in cursor:
                mp['id'] = facebookUserID
                mp['first_name'] = firstName
                mp['gender'] = gender
                mp['last_name'] = lastName
                mp['link'] = link
                mp['locale'] = locale
                mp['name'] = name
                mp['username'] = username
                users.append(FacebookUser(mp))

            cursor.close()
            self.db.closeConnection()

        except mysql.connector.Error as ex:
            print(ex.fp.read())
            print('Error reading a Facebook User in the DB.')
        return users