text:
#ifndef __CDS_INTRUSIVE_SKIP_LIST_BASE_H
#define __CDS_INTRUSIVE_SKIP_LIST_BASE_H

#include <cds/intrusive/base.h>
#include <cds/details/marked_ptr.h>
#include <cds/bitop.h>
#include <cds/os/timer.h>
#include <cds/urcu/options.h>

namespace cds { namespace intrusive {
    /// SkipListSet related definitions
    /** @ingroup cds_intrusive_helper
    */
    namespace skip_list {

        /// The maximum possible height of any skip-list
        static unsigned int const c_nHeightLimit = 32 ;

        /// Skip list node
        /**
            Template parameters:
            - GC - garbage collector
            - Tag - a tag used to distinguish between different implementation. An incomplete type may be used as a tag.
        */
        template <class GC, typename Tag = opt::none>
        class node {
        public:
            typedef GC      gc          ;   ///< Garbage collector
            typedef Tag     tag         ;   ///< tag

            typedef cds::details::marked_ptr<node, 1>                       marked_ptr          ;   ///< marked pointer
            typedef typename gc::template atomic_marked_ptr< marked_ptr>    atomic_marked_ptr   ;   ///< atomic marked pointer specific for GC
            //@cond
            typedef atomic_marked_ptr tower_item_type ;
            //@endcond

        protected:
            atomic_marked_ptr       m_pNext     ;   ///< Next item in bottom-list (list at level 0)
            unsigned int            m_nHeight   ;   ///< Node height (size of m_arrNext array). For node at level 0 the height is 1.
            atomic_marked_ptr *     m_arrNext   ;   ///< Array of next items for levels 1 .. m_nHeight - 1. For node at level 0 \p m_arrNext is \p NULL

        public:
            /// Constructs a node of height 1 (a bottom-list node)
            node()
                : m_pNext( null_ptr<node *>())
                , m_nHeight(1)
                , m_arrNext( null_ptr<atomic_marked_ptr *>())
            {}

            /// Constructs a node of height \p nHeight
            void make_tower( unsigned int nHeight, atomic_marked_ptr * nextTower )
            {
                assert( nHeight > 0 )   ;
                assert( ( nHeight == 1 && nextTower == null_ptr<atomic_marked_ptr *>() )  // bottom-list node
                     || ( nHeight > 1  && nextTower != null_ptr<atomic_marked_ptr *>() )   // node at level of more than 0
                ) ;

                m_arrNext = nextTower   ;
                m_nHeight = nHeight     ;
            }

            //@cond
            atomic_marked_ptr * release_tower()
            {
                atomic_marked_ptr * pTower = m_arrNext  ;
                m_arrNext = null_ptr<atomic_marked_ptr *>() ;
                m_nHeight = 1   ;
                return pTower   ;
            }

            atomic_marked_ptr * get_tower() const
            {
                return m_arrNext ;
            }
            //@endcond

            /// Access to element of next pointer array
            atomic_marked_ptr& next( unsigned int nLevel )
            {
                assert( nLevel < height() ) ;
                assert( nLevel == 0 || (nLevel > 0 && m_arrNext != null_ptr<atomic_marked_ptr *>() )) ;

                return nLevel ? m_arrNext[ nLevel - 1] : m_pNext ;
            }

            /// Access to element of next pointer array (const version)
            atomic_marked_ptr const& next( unsigned int nLevel ) const
            {
                assert( nLevel < height() ) ;
                assert( nLevel == 0 || nLevel > 0 && m_arrNext != null_ptr<atomic_marked_ptr *>() ) ;

                return nLevel ? m_arrNext[ nLevel - 1] : m_pNext ;
            }

            /// Access to element of next pointer array (same as \ref next function)
            atomic_marked_ptr& operator[]( unsigned int nLevel )
            {
                return next( nLevel ) ;
            }

            /// Access to element of next pointer array (same as \ref next function)
            atomic_marked_ptr const& operator[]( unsigned int nLevel ) const
            {
                return next( nLevel ) ;
            }

            /// Height of the node
            unsigned int height() const
            {
                return m_nHeight    ;
            }

            /// Clears internal links
            void clear()
            {
                assert( m_arrNext == null_ptr<atomic_marked_ptr *>()) ;
                m_pNext.store( marked_ptr(), CDS_ATOMIC::memory_order_release ) ;
            }

            //@cond
            bool is_cleared() const
            {
                return m_pNext == atomic_marked_ptr()
                    && m_arrNext == null_ptr<atomic_marked_ptr *>()
                    && m_nHeight <= 1
                    ;
            }
            //@endcond
        };

        //@cond
        struct undefined_gc ;
        struct default_hook {
            typedef undefined_gc    gc  ;
            typedef opt::none       tag ;
        };
        //@endcond

        //@cond
        template < typename HookType, CDS_DECL_OPTIONS2>
        struct hook
        {
            typedef typename opt::make_options< default_hook, CDS_OPTIONS2>::type  options ;
            typedef typename options::gc    gc  ;
            typedef typename options::tag   tag ;
            typedef node<gc, tag>           node_type   ;
            typedef HookType                hook_type   ;
        };
        //@endcond

        /// Base hook
        /**
            \p Options are:
            - opt::gc - garbage collector used.
            - opt::tag - tag
        */
        template < CDS_DECL_OPTIONS2 >
        struct base_hook: public hook< opt::base_hook_tag, CDS_OPTIONS2 >
        {};

        /// Member hook
        /**
            \p MemberOffset defines offset in bytes of \ref node member into your structure.
            Use \p offsetof macro to define \p MemberOffset

            \p Options are:
            - opt::gc - garbage collector used.
            - opt::tag - tag
        */
        template < size_t MemberOffset, CDS_DECL_OPTIONS2 >
        struct member_hook: public hook< opt::member_hook_tag, CDS_OPTIONS2 >
        {
            //@cond
            static const size_t c_nMemberOffset = MemberOffset ;
            //@endcond
        };

        /// Traits hook
        /**
            \p NodeTraits defines type traits for node.
            See \ref node_traits for \p NodeTraits interface description

            \p Options are:
            - opt::gc - garbage collector used.
            - opt::tag - tag
        */
        template <typename NodeTraits, CDS_DECL_OPTIONS2 >
        struct traits_hook: public hook< opt::traits_hook_tag, CDS_OPTIONS2 >
        {
            //@cond
            typedef NodeTraits node_traits ;
            //@endcond
        };

        /// Option specifying random level generator
        /**
            The random level generator is an important part of skip-list algorithm.
            The node height in the skip-list have a probabilistic distribution
            where half of the nodes that have level \p i pointers also have level <tt>i+1</tt> pointers
            (i = 0..30).
            The random level generator should provide such distribution.

            The \p Type functor interface is:
            \code
            struct random_generator {
                static unsigned int const c_nUpperBound = 32 ;
                random_generator() ;
                unsigned int operator()() ;
            };
            \endcode

            where
            - \p c_nUpperBound - constant that specifies the upper bound of random number generated.
                The generator produces a number from range <tt>[0 .. c_nUpperBound)</tt> (upper bound excluded).
                \p c_nUpperBound must be no more than 32.
            - <tt>random_generator()</tt> - the constructor of generator object initialises the generator instance (its internal state).
            - <tt>unsigned int operator()()</tt> - the main generating function. Returns random level from range 0..31.

            Stateful generators are supported.

            Available \p Type implementations:
            - \ref xorshift
            - \ref turbo_pascal
        */
        template <typename Type>
        struct random_level_generator {
            //@cond
            template <typename Base>
            struct pack: public Base
            {
                typedef Type random_level_generator ;
            };
            //@endcond
        };

        /// Xor-shift random level generator
        /**
            The simplest of the generators described in George
            Marsaglia's "Xorshift RNGs" paper.  This is not a high-quality
            generator but is acceptable for skip-list.

            The random generator should return numbers from range [0..31].

            From Doug Lea's ConcurrentSkipListMap.java.
        */
        class xorshift {
            //@cond
            CDS_ATOMIC::atomic<unsigned int>    m_nSeed ;
            //@endcond
        public:
            /// The upper bound of generator's return value. The generator produces random number in range <tt>[0..c_nUpperBound)</tt>
            static unsigned int const c_nUpperBound = c_nHeightLimit ;

            /// Initializes the generator instance
            xorshift()
            {
                m_nSeed.store( (unsigned int) cds::OS::Timer::random_seed(), CDS_ATOMIC::memory_order_relaxed ) ;
            }

            /// Main generator function
            unsigned int operator()()
            {
                /* ConcurrentSkipListMap.java
                private int randomLevel() {
                    int x = randomSeed;
                    x ^= x << 13;
                    x ^= x >>> 17;
                    randomSeed = x ^= x << 5;
                    if ((x & 0x80000001) != 0) // test highest and lowest bits
                        return 0;
                    int level = 1;
                    while (((x >>>= 1) & 1) != 0) ++level;
                    return level;
                }
                */
                unsigned int x = m_nSeed.load( CDS_ATOMIC::memory_order_relaxed ) ;
                x ^= x << 13;
                x ^= x >> 17;
                x ^= x << 5;
                m_nSeed.store( x, CDS_ATOMIC::memory_order_relaxed ) ;
                unsigned int nLevel = ((x & 0x00000001) != 0) ? 0 : cds::bitop::LSB( (~(x >> 1)) & 0x7FFFFFFF ) ;
                assert( nLevel < c_nUpperBound )  ;
                return nLevel ;
            }
        };

        /// Turbo-pascal random level generator
        /**
            This uses a cheap pseudo-random function that was used in Turbo Pascal.

            The random generator should return numbers from range [0..31].

            From Doug Lea's ConcurrentSkipListMap.java.
        */
        class turbo_pascal
        {
            //@cond
            CDS_ATOMIC::atomic<unsigned int>    m_nSeed ;
            //@endcond
        public:
            /// The upper bound of generator's return value. The generator produces random number in range <tt>[0..c_nUpperBound)</tt>
            static unsigned int const c_nUpperBound = c_nHeightLimit ;

            /// Initializes the generator instance
            turbo_pascal()
            {
                m_nSeed.store( (unsigned int) cds::OS::Timer::random_seed(), CDS_ATOMIC::memory_order_relaxed ) ;
            }

            /// Main generator function
            unsigned int operator()()
            {
                /*
                private int randomLevel() {
                    int level = 0;
                    int r = randomSeed;
                    randomSeed = r * 134775813 + 1;
                    if (r < 0) {
                        while ((r <<= 1) > 0)
                            ++level;
                    }
                return level;
                }
                */
                /*
                    The low bits are apparently not very random (the original used only
                    upper 16 bits) so we traverse from highest bit down (i.e., test
                    sign), thus hardly ever use lower bits.
                */
                unsigned int x = m_nSeed.load( CDS_ATOMIC::memory_order_relaxed ) * 134775813 + 1;
                m_nSeed.store( x, CDS_ATOMIC::memory_order_relaxed ) ;
                unsigned int nLevel = ( x & 0x80000000 ) ? (31 - cds::bitop::MSBnz( (x & 0x7FFFFFFF) | 1 )) : 0 ;
                assert( nLevel < c_nUpperBound )   ;
                return nLevel ;
            }
        };

        /// SkipListSet internal statistics
        struct stat {
            typedef cds::atomicity::event_counter   event_counter ; ///< Event counter type

            event_counter   m_nNodeHeightAdd[c_nHeightLimit] ; ///< Count of added node of each height
            event_counter   m_nNodeHeightDel[c_nHeightLimit] ; ///< Count of deleted node of each height
            event_counter   m_nInsertSuccess        ; ///< Count of success insertion
            event_counter   m_nInsertFailed         ; ///< Count of failed insertion
            event_counter   m_nInsertRetries        ; ///< Count of unsiccessful retries of insertion
            event_counter   m_nEnsureExist          ; ///< Count of \p ensure call for existed node
            event_counter   m_nEnsureNew            ; ///< Count of \p ensure call for new node
            event_counter   m_nUnlinkSuccess        ; ///< Count of successful call of \p unlink
            event_counter   m_nUnlinkFailed         ; ///< Count of failed call of \p unlink
            event_counter   m_nEraseSuccess         ; ///< Count of successful call of \p erase
            event_counter   m_nEraseFailed          ; ///< Count of failed call of \p erase
            event_counter   m_nFindFastSuccess      ; ///< Count of successful call of \p find and all derivatives (via fast-path)
            event_counter   m_nFindFastFailed       ; ///< Count of failed call of \p find and all derivatives (via fast-path)
            event_counter   m_nFindSlowSuccess      ; ///< Count of successful call of \p find and all derivatives (via slow-path)
            event_counter   m_nFindSlowFailed       ; ///< Count of failed call of \p find and all derivatives (via slow-path)

            //@cond
            void onAddNode( unsigned int nHeight )
            {
                assert( nHeight > 0 && nHeight <= sizeof(m_nNodeHeightAdd) / sizeof(m_nNodeHeightAdd[0])) ;
                ++m_nNodeHeightAdd[nHeight - 1] ;
            }
            void onRemoveNode( unsigned int nHeight )
            {
                assert( nHeight > 0 && nHeight <= sizeof(m_nNodeHeightDel) / sizeof(m_nNodeHeightDel[0])) ;
                ++m_nNodeHeightDel[nHeight - 1] ;
            }

            void onInsertSuccess()      { ++m_nInsertSuccess    ; }
            void onInsertFailed()       { ++m_nInsertFailed     ; }
            void onInsertRetry()        { ++m_nInsertRetries    ; }
            void onEnsureExist()        { ++m_nEnsureExist      ; }
            void onEnsureNew()          { ++m_nEnsureNew        ; }
            void onUnlinkSuccess()      { ++m_nUnlinkSuccess    ; }
            void onUnlinkFailed()       { ++m_nUnlinkFailed     ; }
            void onEraseSuccess()       { ++m_nEraseSuccess     ; }
            void onEraseFailed()        { ++m_nEraseFailed      ; }
            void onFindFastSuccess()    { ++m_nFindFastSuccess  ; }
            void onFindFastFailed()     { ++m_nFindFastFailed   ; }
            void onFindSlowSuccess()    { ++m_nFindSlowSuccess  ; }
            void onFindSlowFailed()     { ++m_nFindSlowFailed   ; }

            //@endcond
        };

        /// SkipListSet empty internal statistics
        struct empty_stat {
            //@cond
            void onAddNode( unsigned int nHeight ) const {}
            void onRemoveNode( unsigned int nHeight ) const {}
            void onInsertSuccess()  const {}
            void onInsertFailed()   const {}
            void onInsertRetry()    const {}
            void onEnsureExist()    const {}
            void onEnsureNew()      const {}
            void onUnlinkSuccess()  const {}
            void onUnlinkFailed()   const {}
            void onEraseSuccess()   const {}
            void onEraseFailed()    const {}
            void onFindFastSuccess() const {}
            void onFindFastFailed()  const {}
            void onFindSlowSuccess() const {}
            void onFindSlowFailed()  const {}
            //@endcond
        };

        //@cond
        // For internal use only!!!
        template <typename Type>
        struct internal_node_builder {
            template <typename Base>
            struct pack: public Base
            {
                typedef Type internal_node_builder ;
            };
        };
        //@endcond

        /// Type traits for SkipListSet class
        struct type_traits
        {
            /// Hook used
            /**
                Possible values are: skip_list::base_hook, skip_list::member_hook, skip_list::traits_hook.
            */
            typedef base_hook<>       hook        ;

            /// Key comparison functor
            /**
                No default functor is provided. If the option is not specified, the \p less is used.
            */
            typedef opt::none                       compare     ;

            /// specifies binary predicate used for key compare.
            /**
                Default is \p std::less<T>.
            */
            typedef opt::none                       less        ;

            /// Disposer
            /**
                The functor used for dispose removed items. Default is opt::v::empty_disposer.
            */
            typedef opt::v::empty_disposer          disposer    ;

            /// Item counter
            /**
                The type for item counting feature.
                Default is no item counter (\ref atomicity::empty_item_counter)
            */
            typedef atomicity::empty_item_counter     item_counter;

            /// C++ memory ordering model
            /**
                List of available memory ordering see opt::memory_model
            */
            typedef opt::v::relaxed_ordering        memory_model    ;

            /// Random level generator
            /**
                The random level generator is an important part of skip-list algorithm.
                The node height in the skip-list have a probabilistic distribution
                where half of the nodes that have level \p i pointers also have level <tt>i+1</tt> pointers
                (i = 0..30). So, the height of a node is in range [0..31].

                See skip_list::random_level_generator option setter.
            */
            typedef turbo_pascal                    random_level_generator  ;

            /// Allocator
            /**
                Although the skip-list is an intrusive container,
                an allocator should be provided to maintain variable randomly-calculated height of the node
                since the node can contain up to 32 next pointers.
                The allocator specified is used to allocate an array of next pointers
                for nodes which height is more than 1.
            */
            typedef CDS_DEFAULT_ALLOCATOR           allocator ;

            /// back-off strategy used
            /**
                If the option is not specified, the cds::backoff::Default is used.
            */
            typedef cds::backoff::Default           back_off    ;

            /// Internal statistics
            typedef empty_stat                      stat ;

            /// RCU deadlock checking policy (only for \ref cds_intrusive_SkipListSet_rcu "RCU-based SkipListSet")
            /**
                List of available options see opt::rcu_check_deadlock
            */
            typedef opt::v::rcu_throw_deadlock      rcu_check_deadlock ;

            //@cond
            // For internal use only!!!
            typedef opt::none                       internal_node_builder    ;
            //@endcond
        };

        /// Metafunction converting option list to SkipListSet traits
        /**
            This is a wrapper for <tt> cds::opt::make_options< type_traits, Options...> </tt>
            \p Options list see \ref SkipListSet.
        */
        template <CDS_DECL_OPTIONS13>
        struct make_traits {
#   ifdef CDS_DOXYGEN_INVOKED
            typedef implementation_defined type ;   ///< Metafunction result
#   else
            typedef typename cds::opt::make_options<
                typename cds::opt::find_type_traits< type_traits, CDS_OPTIONS13 >::type
                ,CDS_OPTIONS13
            >::type   type ;
#   endif
        };

        //@cond
        namespace details {
            template <typename Node>
            class head_node: public Node
            {
                typedef Node node_type ;

                typename node_type::atomic_marked_ptr   m_Tower[skip_list::c_nHeightLimit] ;

            public:
                head_node( unsigned int nHeight )
                {
                    for ( size_t i = 0; i < sizeof(m_Tower) / sizeof(m_Tower[0]); ++i )
                        m_Tower[i].store( typename node_type::marked_ptr(), CDS_ATOMIC::memory_order_relaxed )  ;

                    node_type::make_tower( nHeight, m_Tower ) ;
                }

                node_type * head() const
                {
                    return const_cast<node_type *>( static_cast<node_type const *>(this)) ;
                }
            };

            template <typename NodeType, typename AtomicNodePtr, typename Alloc>
            struct intrusive_node_builder
            {
                typedef NodeType        node_type       ;
                typedef AtomicNodePtr   atomic_node_ptr ;
                typedef Alloc           allocator_type  ;

                typedef cds::details::Allocator< atomic_node_ptr, allocator_type >  tower_allocator ;

                template <typename RandomGen>
                static node_type * make_tower( node_type * pNode, RandomGen& gen )
                {
                    return make_tower( pNode, gen() + 1 )  ;
                }

                static node_type * make_tower( node_type * pNode, unsigned int nHeight )
                {
                    if ( nHeight > 1 )
                        pNode->make_tower( nHeight, tower_allocator().NewArray( nHeight - 1, null_ptr<node_type *>() )) ;
                    return pNode ;
                }

                static void dispose_tower( node_type * pNode )
                {
                    unsigned int nHeight = pNode->height() ;
                    if ( nHeight > 1 )
                        tower_allocator().Delete( pNode->release_tower(), nHeight ) ;
                }

                struct node_disposer {
                    void operator()( node_type * pNode )
                    {
                        dispose_tower( pNode )  ;
                    }
                };
            };

            // Forward declaration
            template <class GC, typename NodeTraits, typename BackOff, bool IsConst>
            class iterator ;

        } // namespace details
        //@endcond

    }   // namespace skip_list

    // Forward declaration
    template <class GC, typename T, typename Traits = skip_list::type_traits >
    class SkipListSet  ;

}}   // namespace cds::intrusive

#endif // #ifndef __CDS_INTRUSIVE_SKIP_LIST_BASE_H


text:
Clone this project onto an Ubuntu server and run:

```bash
make
```

This will set up PHP-FPM with Nginx.

redpajama_set_name: RedPajamaGithub


text:
package app

import (
	"fmt"
	"sort"
	"strings"

	docker "github.com/fsouza/go-dockerclient"

	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	utilerrors "github.com/GoogleCloudPlatform/kubernetes/pkg/util/errors"
	"github.com/golang/glog"

	"github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/dockerregistry"
	imageapi "github.com/openshift/origin/pkg/image/api"
)

// DockerClient is the local interface for the docker client
type DockerClient interface {
	ListImages(opts docker.ListImagesOptions) ([]docker.APIImages, error)
	InspectImage(name string) (*docker.Image, error)
}

// DockerClientResolver finds local docker images locally that match a search value
type DockerClientResolver struct {
	Client DockerClient

	// Optional, will delegate resolution to the registry if no local
	// exact matches are found.
	RegistryResolver Resolver

	// Insecure, if true will add an annotation to generated ImageStream
	// so that the image can be pulled properly
	Insecure bool
}

// Resolve searches all images in local docker server for an image that matches the passed in value
func (r DockerClientResolver) Resolve(value string) (*ComponentMatch, error) {
	ref, err := imageapi.ParseDockerImageReference(value)
	if err != nil {
		return nil, err
	}

	glog.V(4).Infof("checking local Docker daemon for %q", ref.String())
	images, err := r.Client.ListImages(docker.ListImagesOptions{})
	if err != nil {
		return nil, err
	}
	matches := ScoredComponentMatches{}
	for _, image := range images {
		if tags := matchTag(image, value, ref.Registry, ref.Namespace, ref.Name, ref.Tag); len(tags) > 0 {
			matches = append(matches, tags...)
		}
	}
	sort.Sort(matches)
	if exact := matches.Exact(); len(exact) > 0 {
		matches = exact
	} else {
		if r.RegistryResolver != nil {
			match, err := r.RegistryResolver.Resolve(value)
			switch err.(type) {
			case nil:
				return match, nil
			case ErrNoMatch:
				// show our partial matches
			case ErrMultipleMatches:
				return nil, err
			default:
				return nil, err
			}
		}
	}

	errs := []error{}
	for i, match := range matches {
		if match.Image != nil {
			continue
		}
		updated, err := r.lookup(match.Value)
		if err != nil {
			errs = append(errs, err)
			continue
		}
		updated.Score = match.Score
		updated.ImageTag = ref.Tag
		updated.Insecure = r.Insecure
		matches[i] = updated
	}

	if len(errs) != 0 {
		if len(errs) == 1 {
			err := errs[0]
			if err == docker.ErrNoSuchImage {
				return nil, ErrNoMatch{value: value}
			}
			return nil, err
		}
		return nil, utilerrors.NewAggregate(errs)
	}

	switch len(matches) {
	case 0:
		return nil, ErrNoMatch{value: value}
	case 1:
		return matches[0], nil
	default:
		return nil, ErrMultipleMatches{Image: value, Matches: matches}
	}
}

func (r DockerClientResolver) lookup(value string) (*ComponentMatch, error) {
	image, err := r.Client.InspectImage(value)
	if err != nil {
		return nil, err
	}
	dockerImage := &imageapi.DockerImage{}
	if err := kapi.Scheme.Convert(image, dockerImage); err != nil {
		return nil, err
	}
	return &ComponentMatch{
		Value:       value,
		Argument:    fmt.Sprintf("--docker-image=%q", value),
		Name:        value,
		Description: descriptionFor(dockerImage, value, "local Docker"),
		Builder:     IsBuilderImage(dockerImage),
		Score:       0.0,
		Image:       dockerImage,
		Insecure:    r.Insecure,
	}, nil
}

// DockerRegistryResolver searches for images in a given docker registry
type DockerRegistryResolver struct {
	Client dockerregistry.Client

	AllowInsecure bool
}

// Resolve searches the docker registry for repositories matching the passed in value
func (r DockerRegistryResolver) Resolve(value string) (*ComponentMatch, error) {
	ref, err := imageapi.ParseDockerImageReference(value)
	if err != nil {
		return nil, err
	}
	glog.V(4).Infof("checking Docker registry for %q", ref.String())
	connection, err := r.Client.Connect(ref.Registry, r.AllowInsecure)
	if err != nil {
		if dockerregistry.IsRegistryNotFound(err) {
			return nil, ErrNoMatch{value: value}
		}
		return nil, ErrNoMatch{value: value, qualifier: fmt.Sprintf("can't connect to %q: %v", ref.Registry, err)}
	}
	image, err := connection.ImageByTag(ref.Namespace, ref.Name, ref.Tag)
	if err != nil {
		if dockerregistry.IsNotFound(err) {
			return nil, ErrNoMatch{value: value, qualifier: err.Error()}
		}
		return nil, ErrNoMatch{value: value, qualifier: fmt.Sprintf("can't connect to %q: %v", ref.Registry, err)}
	}
	if len(ref.Tag) == 0 {
		ref.Tag = imageapi.DefaultImageTag
	}
	glog.V(4).Infof("found image: %#v", image)
	dockerImage := &imageapi.DockerImage{}
	if err = kapi.Scheme.Convert(image, dockerImage); err != nil {
		return nil, err
	}

	if len(ref.Registry) == 0 {
		ref.Registry = "Docker Hub"
	}
	return &ComponentMatch{
		Value:       value,
		Argument:    fmt.Sprintf("--docker-image=%q", value),
		Name:        value,
		Description: descriptionFor(dockerImage, value, ref.Registry),
		Builder:     IsBuilderImage(dockerImage),
		Score:       0,
		Image:       dockerImage,
		ImageTag:    ref.Tag,
	}, nil
}

func descriptionFor(image *imageapi.DockerImage, value, from string) string {
	shortID := image.ID
	if len(shortID) > 7 {
		shortID = shortID[:7]
	}
	parts := []string{fmt.Sprintf("Docker image %q", value), shortID, fmt.Sprintf("from %s", from)}
	if image.Size > 0 {
		mb := float64(image.Size) / float64(1024*1024)
		parts = append(parts, fmt.Sprintf("%f", mb))
	}
	if len(image.Author) > 0 {
		parts = append(parts, fmt.Sprintf("author %s", image.Author))
	}
	if len(image.Comment) > 0 {
		parts = append(parts, image.Comment)
	}
	return strings.Join(parts, ", ")
}

func partialScorer(a, b string, prefix bool, partial, none float32) (bool, float32) {
	switch {
	case len(a) == 0 && len(b) != 0, len(a) != 0 && len(b) == 0:
		return true, partial
	case a != b:
		if prefix {
			if strings.HasPrefix(a, b) || strings.HasPrefix(b, a) {
				return true, partial
			}
		}
		return false, none
	default:
		return true, 0.0
	}
}

func matchTag(image docker.APIImages, value, registry, namespace, name, tag string) []*ComponentMatch {
	if len(tag) == 0 {
		tag = imageapi.DefaultImageTag
	}
	matches := []*ComponentMatch{}
	for _, s := range image.RepoTags {
		if value == s {
			matches = append(matches, &ComponentMatch{
				Value: s,
				Score: 0.0,
			})
			continue
		}
		iRef, err := imageapi.ParseDockerImageReference(s)
		if err != nil {
			continue
		}
		if len(iRef.Tag) == 0 {
			iRef.Tag = imageapi.DefaultImageTag
		}
		match := &ComponentMatch{}
		ok, score := partialScorer(name, iRef.Name, true, 0.5, 1.0)
		if !ok {
			continue
		}
		match.Score += score
		_, score = partialScorer(namespace, iRef.Namespace, false, 0.5, 1.0)
		match.Score += score
		_, score = partialScorer(registry, iRef.Registry, false, 0.5, 1.0)
		match.Score += score
		_, score = partialScorer(tag, iRef.Tag, false, 0.5, 1.0)
		match.Score += score

		if match.Score >= 4.0 {
			continue
		}
		match.Score = match.Score / 4.0
		glog.V(4).Infof("partial match on %q with %f", s, match.Score)
		match.Value = s
		matches = append(matches, match)
	}
	return matches
}

// ImageStreamResolver searches the openshift server image streams for images matching a particular name
type ImageStreamResolver struct {
	Client            client.ImageStreamsNamespacer
	ImageStreamImages client.ImageStreamImagesNamespacer
	Namespaces        []string
}

// Resolve will attempt to find an imagestream with a name that matches the passed in value
func (r ImageStreamResolver) Resolve(value string) (*ComponentMatch, error) {
	ref, err := imageapi.ParseDockerImageReference(value)
	if err != nil || len(ref.Registry) != 0 {
		return nil, fmt.Errorf("image repositories must be of the form [<namespace>/]<name>[:<tag>|@<digest>]")
	}
	namespaces := r.Namespaces
	if len(ref.Namespace) != 0 {
		namespaces = []string{ref.Namespace}
	}
	searchTag := ref.Tag
	if len(searchTag) == 0 {
		searchTag = imageapi.DefaultImageTag
	}
	for _, namespace := range namespaces {
		glog.V(4).Infof("checking ImageStream %s/%s with ref %q", namespace, ref.Name, searchTag)
		repo, err := r.Client.ImageStreams(namespace).Get(ref.Name)
		if err != nil {
			if errors.IsNotFound(err) || errors.IsForbidden(err) {
				continue
			}
			return nil, err
		}
		ref.Namespace = namespace
		latest := imageapi.LatestTaggedImage(repo, searchTag)
		if latest == nil {
			// continue searching in the next namespace
			glog.V(2).Infof("no image recorded for %s/%s:%s", repo.Namespace, repo.Name, searchTag)
			continue
		}
		imageStreamImage, err := r.ImageStreamImages.ImageStreamImages(namespace).Get(ref.Name, latest.Image)
		if err != nil {
			if errors.IsNotFound(err) {
				// continue searching in the next namespace
				glog.V(2).Infof("tag %q is set, but image %q has been removed", searchTag, latest.Image)
				continue
			}
			return nil, err
		}
		imageData := imageStreamImage.Image

		ref.Registry = ""
		return &ComponentMatch{
			Value:       ref.String(),
			Argument:    fmt.Sprintf("--image=%q", ref.String()),
			Name:        ref.Name,
			Description: fmt.Sprintf("Image repository %s (tag %q) in project %s, tracks %q", repo.Name, searchTag, repo.Namespace, repo.Status.DockerImageRepository),
			Builder:     IsBuilderImage(&imageData.DockerImageMetadata),
			Score:       0,

			ImageStream: repo,
			Image:       &imageData.DockerImageMetadata,
			ImageTag:    searchTag,
		}, nil
	}
	return nil, ErrNoMatch{value: value}
}

// Searcher will return potentially multiple matches for a set of search strings
type Searcher interface {
	Search(terms []string) ([]*ComponentMatch, error)
}

// InputImageFromMatch returns an image reference from a component match.
// The component match will either be an image stream or an image.
func InputImageFromMatch(match *ComponentMatch) (*ImageRef, error) {
	g := NewImageRefGenerator()

	switch {
	case match.ImageStream != nil:
		input, err := g.FromStream(match.ImageStream, match.ImageTag)
		if err != nil {
			return nil, err
		}
		input.AsImageStream = true
		input.Info = match.Image
		return input, nil

	case match.Image != nil:
		input, err := g.FromName(match.Value)
		if err != nil {
			return nil, err
		}
		input.AsImageStream = true
		input.Info = match.Image
		input.Insecure = match.Insecure
		return input, nil

	default:
		return nil, fmt.Errorf("no image or image stream, can't setup a build")
	}
}

// ImageStreamByAnnotationResolver resolves image streams based on 'supports' annotations
// found in tagged images belonging to the stream
type ImageStreamByAnnotationResolver struct {
	Client            client.ImageStreamsNamespacer
	ImageStreamImages client.ImageStreamImagesNamespacer
	Namespaces        []string

	imageStreams map[string]*imageapi.ImageStreamList
}

const supportsAnnotationKey = "supports"

// NewImageStreamByAnnotationResolver creates a new ImageStreamByAnnotationResolver
func NewImageStreamByAnnotationResolver(streamClient client.ImageStreamsNamespacer, imageClient client.ImageStreamImagesNamespacer, namespaces []string) Resolver {
	return &ImageStreamByAnnotationResolver{
		Client:            streamClient,
		ImageStreamImages: imageClient,
		Namespaces:        namespaces,
		imageStreams:      make(map[string]*imageapi.ImageStreamList),
	}
}

func (r *ImageStreamByAnnotationResolver) getImageStreams(namespace string) ([]imageapi.ImageStream, error) {
	imageStreamList, ok := r.imageStreams[namespace]
	if !ok {
		var err error
		imageStreamList, err = r.Client.ImageStreams(namespace).List(labels.Everything(), fields.Everything())
		if err != nil {
			return nil, err
		}
		r.imageStreams[namespace] = imageStreamList
	}
	return imageStreamList.Items, nil
}

func matchSupportsAnnotation(value, annotation string) (float32, bool) {
	valueBase := strings.Split(value, ":")[0]
	parts := strings.Split(annotation, ",")

	// attempt an exact match first
	for _, p := range parts {
		if value == p {
			return 0.0, true
		}
	}

	// attempt a partial match
	for _, p := range parts {
		partBase := strings.Split(p, ":")[0]
		if valueBase == partBase {
			return 0.5, true
		}
	}

	return 0, false
}

func (r *ImageStreamByAnnotationResolver) annotationMatches(stream *imageapi.ImageStream, value string) []*ComponentMatch {
	if stream.Spec.Tags == nil {
		glog.Infof("No tags found on image, returning nil")
		return nil
	}
	matches := []*ComponentMatch{}
	for tag, tagref := range stream.Spec.Tags {
		if tagref.Annotations == nil {
			continue
		}
		supports, ok := tagref.Annotations[supportsAnnotationKey]
		if !ok {
			continue
		}
		score, ok := matchSupportsAnnotation(value, supports)
		if !ok {
			continue
		}
		latest := imageapi.LatestTaggedImage(stream, tag)
		if latest == nil {
			continue
		}
		imageStream, err := r.ImageStreamImages.ImageStreamImages(stream.Namespace).Get(stream.Name, latest.Image)
		if err != nil {
			glog.V(2).Infof("Could not retrieve image stream image for stream %q, tag %q: %v", stream.Name, tag, err)
			continue
		}
		if imageStream == nil {
			continue
		}
		imageData := imageStream.Image
		match := &ComponentMatch{
			Value:       value,
			Name:        stream.Name,
			Argument:    fmt.Sprintf("--image=%q", value),
			Description: fmt.Sprintf("Image stream %s in project %s, tracks %q", stream.Name, stream.Namespace, stream.Status.DockerImageRepository),
			Builder:     IsBuilderImage(&imageData.DockerImageMetadata),
			Score:       score,

			ImageStream: stream,
			Image:       &imageData.DockerImageMetadata,
			ImageTag:    imageapi.DefaultImageTag,
		}
		matches = append(matches, match)
	}
	return matches
}

// Resolve finds image stream images using their 'supports' annotation
func (r *ImageStreamByAnnotationResolver) Resolve(value string) (*ComponentMatch, error) {
	matches := ScoredComponentMatches{}
	for _, namespace := range r.Namespaces {
		streams, err := r.getImageStreams(namespace)
		if err != nil {
			return nil, err
		}
		for i := range streams {
			matches = append(matches, r.annotationMatches(&streams[i], value)...)
		}
	}
	switch len(matches) {
	case 0:
		return nil, ErrNoMatch{value: value}
	case 1:
		return matches[0], nil
	default:
		exact := matches.Exact()
		if len(exact) == 1 {
			return exact[0], nil
		}
		sort.Sort(matches)
		return nil, ErrMultipleMatches{Image: value, Matches: matches}
	}
}


text:
function setStatementError (input, state) {

  console.log('setStatementError', setStatementError);
  var path = ['statements', input.ref];

  let statement = state.get(path);

  state.merge(path, {
    id: args.id,
    $isSaving: false,
    $error: input.error
  });

};

export default setStatementError;


text:
var Activity1 = function(context) {

	var view = "
Another World
";

	context.prepareView().then(function(ui) {
		ui.innerHTML  = view;
	});

	context.setResult("oooo");

	context.onShow(function() {

		if (!ctx.actions) {
			ctx.actions = [];
		}
		ctx.actions.push({
			order: 1,
			action: "azione X",
			iconClass: "fa-search",
			handler: function(e) {
				alert("azione X dell'activity "+ctx.getActivityInstanceId());
			}
		});

	});

};


text:
package routes

import (
	"github.com/ml-tv/tv-api/src/components/users/handlers"
	"github.com/ml-tv/tv-api/src/core/router"
)

// Contains the index of all Endpoints
const (
	EndpointAddUser = iota
	EndpointUpdateUser
	EndpointDeleteUser
	EndpointGetUser
)

// UserEndpoints is a list of endpoints for this components
var UserEndpoints = router.Endpoints{
	EndpointAddUser: {
		Verb:    "POST",
		Path:    "/users",
		Auth:    nil,
		Handler: handlers.AddUser,
		Params:  &handlers.AddUserParams{},
	},
	EndpointUpdateUser: {
		Verb:    "PATCH",
		Path:    "/users/{id}",
		Auth:    router.LoggedUserAccess,
		Handler: handlers.UpdateUser,
		Params:  &handlers.UpdateUserParams{},
	},
	EndpointDeleteUser: {
		Verb:    "DELETE",
		Path:    "/users/{id}",
		Auth:    router.LoggedUserAccess,
		Handler: handlers.DeleteUser,
		Params:  &handlers.DeleteUserParams{},
	},
	EndpointGetUser: {
		Verb:    "GET",
		Path:    "/users/{id}",
		Auth:    nil,
		Handler: handlers.GetUser,
		Params:  &handlers.GetUserParams{},
	},
}


text:
title: Ana Willem
---

@@include('../../templates/_head-team.tpl')

  @@include('../../templates/_homenav.tpl')

Ana Willem

Developer

CONNECT

                      <svg viewBox="0 0 20 20" class="ico-social">
                        <use xlink:href="/assets/img/ico-social.svg#ico-website"></use>
                      </svg>

Ana tried her best to become an artist, a writer, or something bohemian like that, but at some point had to accept that her true talents lie in a more linear realm. PHP, MySQL, etc just seemed easier to learn than, for example, how to paint a masterpiece.

So, she traded in her paints for a computer and is enjoying expressing both her linear and creative aspects through website development and cultural programming.

Ana has been building websites with Drupal since Drupal 4.7 (2004). Her passion for design and development is rooted in a desire to make things work better. She strives to achieve a lean effect in her work: lightweight, user-friendly, and maximally conservative of resources. She is a graduate of the Rhode Island School of Design (Industrial Design) where she specialized in sustainable systems design. She brings with her 10 years of experience with technology and information systems design and development, and 15 years of design experience.

  @@include('../../templates/_footer.tpl')

  @@include('../../templates/_tail.tpl')


text:
@section('title',  trans('gitscrum.welcome-to-gitScrum-step-1'))

@extends('layouts.master-fluid', ['hideNavbar' => true, 'bodyClass' => 'body-wizard-step2'])

@section('content')

                    @if($repositories->count())

{{trans('Congratulations')}}

{{trans('gitscrum.you-have-successfully-added-repositories-for')}} {{config('app.name')}}

                    @else

{{trans('gitscrum.choose-at-least-one-repository')}}

{{trans('gitscrum.you-can-click')}} {{trans('gitscrum.here')}}
                            {{trans('gitscrum.to-try-again')}}

                    @endif

                @if( count($repositories) )

                        @include('partials.boxes.repositories', ['list'=>$repositories, 'columns'=>$columns])

                @else

                @endif

                    @if(count($repositories))
                        {{trans('gitscrum.continue-using')}}
                            {{config('app.name')}}

                           {{trans('gitscrum.or')}}
                        {{trans('gitscrum.import-my')}}
                            {{Auth::user()->provider}} {{trans('gitscrum.issues')}}

                    @else

{{trans('gitscrum.create-your-first-repository')}}

                            @include('partials.forms.product-backlog', ['route' => 'product_backlogs.store'])

                    @endif

GitScrum

be faster

@endsection


text:
![SparkleFormation](img/sparkle-formation.png)

# SparkleFormation

Orchestration template building tools for Ruby.

## What's it do?

Provides a very loose DSL to describe orchestration API templates
programmatically in Ruby.

## Is that it?

Yes. Well, kinda. It also has some extra features, like defining
building blocks to facilitate code reuse in template creation,
helper functions for commonly generated data structures, builtin
logic for handling template nesting, and most importantly:
conjouring magic (to get unicorns).

## Using SparkleFormation

SparkleFormation is a library and not intended for "direct use". If
you are looking to build infrastructure stacks via orchestration APIs
using SparkleFormation templates, please see the reference application
implementation:

* [SparkleFormation CLI (sfn)](http://www.sparkleformation.io/docs/sfn)

## Documentation

* [SparkleFormation Library Documentation](http://www.sparkleformation.io/docs/sparkle_formation/)

# Info
* Documentation: http://www.sparkleformation.io/docs/sparkle_formation
* Repository: https://github.com/sparkleformation/sparkle_formation
* Mailing List: https://groups.google.com/forum/#!forum/sparkleformation
* IRC: [#sparkleformation @ Freenode](https://webchat.freenode.net/?channels=#sparkleformation)
* Gitter: [![Join at https://gitter.im/SparkleFormation/sparkleformation](https://badges.gitter.im/SparkleFormation/sparkleformation.svg)](https://gitter.im/SparkleFormation/sparkleformation?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)


text:
package net.webeggs.juzzle.board;

import static net.webeggs.juzzle.Alphabet.LOWERCASE;

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

import net.webeggs.juzzle.vocabulary.LowercaseTrieVocabulary;

public class AlphabetJuzzleBoard extends AbstractJuzzleBoard<LowercaseTrieVocabulary>{

	byte[][] alphabetBoard;

	/**
	 * Creates a default 4x4 board
	 *
	 * @param letters
	 */
	public AlphabetJuzzleBoard(char[] letters) {
		this(4, 4, letters);
	}

	public AlphabetJuzzleBoard(int r, int c, char[] letters) {
		super(r, c, letters);
		alphabetBoard = new byte[r][c];
		for (int i = 0; i < r; i++) {
			for (int j = 0; j < c; j++) {
				int k = i * c + j;
				alphabetBoard[i][j] = LOWERCASE.getIndex(letters[k]);
			}
		}
	}

	@Override
	protected int recurse(LowercaseTrieVocabulary vocabulary,
			LinkedList<JuzzleBoardCell> usedCells, ArrayList<List<JuzzleBoardCell>> words) {
		int r = 1;
		byte[] word = getInt(usedCells);
		if (vocabulary.contains(word, 0)) {
			// System.out.println(word);
			words.add(new ArrayList<>(usedCells));
		}
		if (vocabulary.isPrefix(word, 0)) {
			// Search for moves
			List<JuzzleBoardCell> moves = getPossibleMoves(usedCells);
			for (JuzzleBoardCell move : moves) {
				usedCells.add(move);
				r += recurse(vocabulary, usedCells, words);
				usedCells.pollLast();
			}
		}
		return r;
	}

	protected byte[] getInt(List<JuzzleBoardCell> list) {
		byte[] r = new byte[list.size()];
		for (int i = 0; i < list.size(); i++) {
			JuzzleBoardCell cell = list.get(i);
			r[i] = alphabetBoard[cell.row][cell.col];
		}
		return r;
	}

	@Override
	protected char getCharAt(int row, int col) {
		return LOWERCASE.alphabet.charAt(alphabetBoard[row][col]);
	}
}


text:
package org.jcoderz.commons.doclet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jcoderz.commons.ArgumentMalformedException;
import org.jcoderz.commons.util.ArraysUtil;
import org.jcoderz.commons.util.IoUtil;
import org.jcoderz.commons.util.StringUtil;
import org.jcoderz.commons.util.XmlUtil;

import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.ConstructorDoc;
import com.sun.javadoc.Doc;
import com.sun.javadoc.DocErrorReporter;
import com.sun.javadoc.Doclet;
import com.sun.javadoc.ExecutableMemberDoc;
import com.sun.javadoc.FieldDoc;
import com.sun.javadoc.MemberDoc;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.PackageDoc;
import com.sun.javadoc.ParamTag;
import com.sun.javadoc.Parameter;
import com.sun.javadoc.ProgramElementDoc;
import com.sun.javadoc.RootDoc;
import com.sun.javadoc.SeeTag;
import com.sun.javadoc.SourcePosition;
import com.sun.javadoc.Tag;
import com.sun.javadoc.ThrowsTag;

/**
 * A generic doclet that writes out all javadoc information as XML.
 *
 * @author Andreas Mandel
 */
public class XmlDoclet
      extends Doclet
{
   /** The full qualified name of this class. */
   private static final String CLASSNAME = XmlDoclet.class.getName();

   /** The logger to use. */
   private static final Logger logger = Logger.getLogger(CLASSNAME);

   /** Static collector for doclet configuration. */
   private static XmlDocletConfig sConfig = new XmlDocletConfig();

   /** Concrete configuration for this xml doclet instance. */
   private final XmlDocletConfig mConfig;

   /** Output writer for current doclet. */
   private Writer mOut = null;

   private RootDoc mRootDoc;

   /**
    * Creates a new XmlDoclet with the given (fix) configuration.
    * @param config the config to use.
    */
   public XmlDoclet (XmlDocletConfig config)
   {
      try
      {
         mConfig = (XmlDocletConfig) config.clone();
      }
      catch (CloneNotSupportedException e)
      {
         throw new RuntimeException("Clone must be supported by config.", e);
      }
   }

   /** {@inheritDoc} */
   public static boolean start (RootDoc root)
   {
      if (logger.isLoggable(Level.FINER))
      {
         logger.entering(CLASSNAME, "start(RootDoc)", root);
      }
      boolean result = true;
      try
      {
         final XmlDoclet handler = new XmlDoclet(sConfig);
         handler.handle(root);
      }
      catch (Exception ex)
      {
         // CHECKME:
         result = false;
         root.printError(ex.getMessage());
         throw new RuntimeException("Internal processing error.", ex);
      }
      if (logger.isLoggable(Level.FINER))
      {
         logger.exiting(CLASSNAME, "start(RootDoc)", Boolean.valueOf(result));
      }
      return result;
   }

   /** @see XmlDocletConfig#optionLength(String) */
   public static int optionLength (String option)
   {
      if (logger.isLoggable(Level.FINER))
      {
         logger.entering(CLASSNAME, "optionLength(String)", option);
      }
      final int result = sConfig.optionLength(option);
      if (logger.isLoggable(Level.FINER))
      {
         logger.exiting(CLASSNAME, "optionLength(String)",
               new Integer(result));
      }
      return result;
   }

   public static boolean validOptions (String[][] arguments,
         DocErrorReporter reporter)
   {
      if (logger.isLoggable(Level.FINER))
      {
         logger.entering(CLASSNAME,
               "validOptions(String[][], DocErrorReporter)",
               new Object[] {ArraysUtil.toString(arguments), reporter});
      }
      boolean result = true;
      final Iterator i = Arrays.asList(arguments).iterator();
      while (i.hasNext())
      {
         final String[] arg = (String[]) i.next();
         if (logger.isLoggable(Level.FINER))
         {
            logger.finest("About to parse argument: "
                  + ArraysUtil.toString(arg));
         }
         final String[] options = new String[arg.length - 1];
         System.arraycopy(arg, 1, options, 0, options.length);
         try
         {
            sConfig.parseOption(arg[0], options);
         }
         catch (ArgumentMalformedException ex)
         {
            reporter.printError(ex.getMessage());
            result = false;
         }
      }
      if (logger.isLoggable(Level.FINER))
      {
         logger.exiting(CLASSNAME,
               "validOptions(String[][], DocErrorReporter)",
               Boolean.valueOf(result));
      }
      return result;
   }

   private void handle (RootDoc root)
         throws IOException
   {
      // create XML file
      FileOutputStream streamOut = null;
      mRootDoc = root;
      try
      {
         streamOut = new FileOutputStream(
               new File(mConfig.getOutputDirectory(), "javadoc.xml"), false);

         mOut = new OutputStreamWriter(streamOut, "utf-8");

         mOut.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
         mOut.write("<javadoc>\n");

         final Set handledPackages = new HashSet();

         final PackageDoc[] packages = root.specifiedPackages();
         for (int i = 0; i < packages.length; ++i)
         {
            generatePackageElement(packages[i]);
            handledPackages.add(packages[i].name());
         }
         final ClassDoc[] classes = root.specifiedClasses();
         for (int i = 0; i < classes.length; ++i)
         {
            if (!handledPackages.contains(
                  classes[i].containingPackage().name()))
            {
               generatePackageElement(classes[i].containingPackage());
               handledPackages.add(classes[i].containingPackage().name());
            }
         }
         mOut.write("</javadoc>");

      }
      finally
      {
         IoUtil.close(mOut);
         IoUtil.close(streamOut);
         mOut = null;
      }
   }

   private void generatePackageElement (PackageDoc pkg)
         throws IOException
   {
      mOut.write("<package");
      generateDocHeader(pkg);
      mOut.write(">");
      generateDocBody(pkg);
      final ClassDoc[] classes = pkg.allClasses();
      for (int i = 0; i < classes.length; ++i)
      {
         generateClassElement(classes[i]);
      }
      mOut.write("</package>");
   }

   private void generateClassElement (ClassDoc cd)
         throws IOException
   {
      mOut.write("<class");
      generateClassHeader(cd);
      mOut.write(">\n");
      generateClassBody(cd);
      mOut.write("</class>\n");
   }

   private void generateClassBody (ClassDoc cd)
         throws IOException
   {
      generateProgramElementBody(cd);

      // Interfaces
      final ClassDoc[] interfaces = cd.interfaces();
      for (int i = 0; i < interfaces.length; ++i)
      {
         mOut.write("<interface");
         addAttribute("name", interfaces[i].qualifiedName());
         mOut.write("/>\n");
      }

      // InnerClasses
      final ClassDoc[] innerClass = cd.innerClasses();
      for (int i = 0; i < innerClass.length; ++i)
      {
         mOut.write("<inner");
         addAttribute("name", innerClass[i].qualifiedName());
         mOut.write("/>\n");
      }

      // Fields
      final FieldDoc[] fields = cd.fields();
      for (int i = 0; i < fields.length; ++i)
      {
         final FieldDoc field = fields[i];
         generateFieldHeader(field);
         generateFieldBody(field);
         mOut.write("</field>\n");
      }

      // Constructors
      final ConstructorDoc[] constructors = cd.constructors();
      for (int i = 0; i < constructors.length; ++i)
      {
         final ConstructorDoc constructor = constructors[i];
         generateConstructorHeader(constructor);
         generateConstructorBody(constructor);
         mOut.write("</constructor>\n");
      }

      // Methods.
      final MethodDoc[] methods = cd.methods();
      for (int i = 0; i < methods.length; ++i)
      {
         final MethodDoc method = methods[i];
         generateMethodHeader(method);
         generateMethodBody(method);
         mOut.write("</method>\n");
      }
   }

   private void generateMethodHeader (MethodDoc method)
         throws IOException
   {
      mOut.write("<method");

      addAttribute("abstract", method.isAbstract());
      if (method.overriddenClass() != null)
      {
         addAttribute("overridden-class",
               method.overriddenClass().qualifiedName());
      }

      if (method.overriddenMethod() != null)
      {
         addAttribute("overridden-method",
               method.overriddenMethod().qualifiedName());
      }

      generateExecutableMemberHeader(method);
      mOut.write(">\n");
   }

   private void generateMethodBody (MethodDoc method)
         throws IOException
   {
      if (method.returnType() != null
            && !method.returnType().qualifiedTypeName().equals("void"))
      {
         mOut.write("<return");
         addAttribute("type",
               method.returnType().qualifiedTypeName()
                  + method.returnType().dimension());
         mOut.write(">");
         final Tag[] returnTag = method.tags("return");
         if (returnTag != null && returnTag.length > 0)
         {
            generatedTagedTextElement(returnTag[0].inlineTags());
         }
         mOut.write("</return>\n");
      }
      generateExecutableMemberDocBody(method);
   }

   private void generatedTagedTextElement (final Tag[] tags)
         throws IOException
   {
      mOut.write("<doc>");
      generateTagedDoc(tags);
      mOut.write("</doc>\n");
   }

   private void generateConstructorBody (ConstructorDoc constructor)
         throws IOException
   {
      generateExecutableMemberDocBody(constructor);
   }

   private void generateExecutableMemberDocBody (
         ExecutableMemberDoc executableMemberDoc)
         throws IOException
   {
      generateMemberBody(executableMemberDoc);

      // Parameter
      final ParamTag[] tags = executableMemberDoc.paramTags();
      final Map parameterTags = new HashMap();
      for (int i = 0; i < tags.length; ++i)
      {
         if (parameterTags.containsKey(tags[i].parameterName()))
         {
            warn(tags[i].position(),
                  "Duplicate parameter ignored. " + tags[i],
                  executableMemberDoc);
         }
         else
         {
            // ONLY on tag per parametername
            parameterTags.put(tags[i].parameterName(), tags[i]);
         }
      }

      final Parameter[] parameters = executableMemberDoc.parameters();
      for (int i = 0; i < parameters.length; ++i)
      {
         final ParamTag parameterTag
               = (ParamTag) parameterTags.get(parameters[i].name());
//         if (parameterTag == null)
//         {
//            warn("No tag for parameter " + parameters[i].hashCode(),
//                  executableMemberDoc);
//         }
         generateParameterHeader(parameters[i], parameterTag);
         generateParameterBody(parameters[i], parameterTag);
         mOut.write("</parameter>\n");
         parameterTags.remove(parameters[i].name());
      }

      if (!parameterTags.isEmpty())
      {
         warn(executableMemberDoc.position(),
               "Unused parameter tags: " + parameterTags, executableMemberDoc);
      }

      // Exceptions
      final ThrowsTag[] tTags = executableMemberDoc.throwsTags();
      final Map throwsTags = new HashMap();
      for (int i = 0; i < tTags.length; ++i)
      {
         if (throwsTags.containsKey(tTags[i].exceptionName()))
         {
            warn(tTags[i].position(),
                  "Duplicate throws Tags ignored." + tTags[i].exceptionName(),
                  executableMemberDoc);
         }
         else
         {
            throwsTags.put(tTags[i].exceptionName(), tTags[i]);
         }
      }

      final ClassDoc[] exceptions = executableMemberDoc.thrownExceptions();
      for (int i = 0; i < exceptions.length; ++i)
      {
         ThrowsTag exceptionTag
               = (ThrowsTag) throwsTags.remove(exceptions[i].qualifiedName());
         if (exceptionTag == null)
         {
            exceptionTag = (ThrowsTag) throwsTags.remove(exceptions[i].name());
         }
         if (exceptionTag == null)
         {
//            warn(executableMemberDoc.position(),
//                  "No tag for exception " + exceptions[i].name(),
//                  executableMemberDoc);
         }
         generateThrowsHeader(exceptions[i], exceptionTag);
         generateThrowsBody(exceptions[i], exceptionTag);
         mOut.write("</throws>\n");
      }

      if (!throwsTags.isEmpty())
      {
         warn(executableMemberDoc.position(),
               "Unused throws tags: " + throwsTags, executableMemberDoc);
      }
   }

   private void generateMemberBody (MemberDoc member)
         throws IOException
   {
      generateProgramElementBody(member);
   }

   private void generateProgramElementBody (ProgramElementDoc programElement)
         throws IOException
   {
      generateDocBody(programElement);
   }

   private void generateThrowsHeader (ClassDoc parameter,
         ThrowsTag exceptionTag)
         throws IOException
   {
      mOut.write("<throws");
      addAttribute("type", parameter.qualifiedName());
      generateTagHeader(exceptionTag);
      mOut.write(">");
   }

   private void generateThrowsBody (ClassDoc parameter,
         ThrowsTag exceptionTag)
         throws IOException
   {
      if (exceptionTag != null)
      {
         generateTagBody(exceptionTag);
      }
   }

   private void generateParameterBody (Parameter parameter,
         ParamTag parameterTag)
         throws IOException
   {
      if (parameterTag != null)
      {
         generateTagBody(parameterTag);
      }
   }

   private void generateParameterHeader (Parameter parameter,
         ParamTag parameterTag)
         throws IOException
   {
      mOut.write("<parameter");
      addAttribute("name", parameter.name());
      addAttribute("type",
            parameter.type().qualifiedTypeName()
               + parameter.type().dimension());
      mOut.write(">");
   }

   private void generateConstructorHeader (ConstructorDoc cd)
         throws IOException
   {
      mOut.write("<constructor");
      generateExecutableMemberHeader(cd);
      mOut.write(">");
   }

   private void generateExecutableMemberHeader (ExecutableMemberDoc emd)
         throws IOException
   {
      addAttribute("flat-signature", emd.flatSignature());
      addAttribute("signature", emd.signature());
      addAttribute("native", emd.isNative());
      addAttribute("synchronized", emd.isSynchronized());
      generateMemberHeader(emd);
   }

   private void generateMemberHeader (MemberDoc md)
         throws IOException
   {
      addAttribute("synthetic", md.isSynthetic());
      generateProgramElementHeader(md);
   }

   private void generateFieldBody (FieldDoc fd)
         throws IOException
   {
      generateMemberBody(fd);
      // TODO: cd.serialFieldTags()
   }

   private void generateFieldHeader (FieldDoc cd)
         throws IOException
   {
      mOut.write("<field");
      addAttribute("type",
            cd.type().qualifiedTypeName() + cd.type().dimension());

      final String constant = cd.constantValueExpression();
      if (constant != null)
      {
         addAttribute("constant", true);
         addAttribute("value", constant);
      }
      addAttribute("volatile", cd.isVolatile());
      addAttribute("transient", cd.isTransient());
      generateMemberHeader(cd);
      mOut.write(">");
   }

   private void generateDocBody (Doc doc)
         throws IOException
   {
      mOut.write("<doc>");
      generateTagedDoc(doc.inlineTags());
      mOut.write("</doc>");

      final Tag[] tags = doc.tags();
      for (int i = 0; i < tags.length; i++)
      {
         final Tag tag = tags[i];
         // these tags are handled directly
         if (!tag.kind().equals("@param")
               && !tag.kind().equals("@return")
               && !tag.kind().equals("@throws"))
         {
            generateTagElement(tag);
         }
      }
   }

   private void generateTagHeader (Tag tag)
         throws IOException
   {
      if (tag != null)
      {
         if (tag.position() != null)
         {
            generateSourcePositionHeader(tag.position());
         }
         addAttribute("name", tag.name());

         if (tag instanceof SeeTag)
         {
            final SeeTag seeTag = (SeeTag) tag;
            addAttribute("label", seeTag.label());
            addAttribute("referenced-class", seeTag.referencedClassName());
            addAttribute("referenced-member", seeTag.referencedMemberName());
            if (seeTag.referencedPackage() != null)
            {
               addAttribute("referenced-package",
                     seeTag.referencedPackage().name());
            }
         }
         else
         {
            addAttribute("kind", tag.kind());
         }
      }
   }

   private void generateTagElement (Tag tag)
         throws IOException
   {
      if (tag instanceof SeeTag)
      {
         generateSeeElement((SeeTag) tag);
      }
      else if (tag != null)
      {
         mOut.write("<tag");
         generateTagHeader(tag);
         mOut.write(">");
         generateTagBody(tag);
         mOut.write("</tag>");
      }
   }

   private void generateTagBody (Tag tag)
         throws IOException
   {
      mOut.write("<doc>");
      generateTagedDoc(tag.inlineTags());
      mOut.write("</doc>");
   }

   private void generateTagedDoc (Tag[] tags)
         throws IOException
   {
      // build string to be tidied up
      final StringBuffer data = new StringBuffer();
      for (int i = 0; i < tags.length; i++)
      {
         final Tag inlineTag = tags[i];
         if (inlineTag instanceof SeeTag)
         {
            data.append("");
         }
         else
         {
            data.append(inlineTag.text());
         }
      }
      final String input = data.toString();
      final String clean;
      if (input.indexOf('<') != -1 || input.indexOf('&') != -1)
      {
         final HtmlCleaner cleaner = new HtmlCleaner();
         clean = cleaner.clean(data);
         final String warnings = cleaner.getWarnings();
         if (!StringUtil.isEmptyOrNull(warnings))
         {
            mRootDoc.printWarning("Input:" + input);
            mRootDoc.printWarning("Clean:" + clean);
            if (cleaner.hasErrors())
            {
               mRootDoc.printWarning(tags[0].position(), warnings);
               // mRootDoc.printError(tags[0].position(), warnings);
            }
            else
            {
               mRootDoc.printWarning(tags[0].position(), warnings);
            }
         }
      }
      else
      {
         clean = input;
      }
      data.setLength(0);
      data.append(clean);

      // now replace the a tag back...
      int pos;
      while ((pos = data.indexOf("<a id='SEE_TAG_")) != -1)
      {
         mOut.write(data.substring(0, pos));
         final int i = Integer.parseInt(data.substring(pos
               + "", pos)));
         generateSeeElement((SeeTag) tags[i]);
         data.delete(0, data.indexOf("'>", pos) + "'>".length());
      }
      mOut.write(data.toString());
   }

   private void generateSeeElement (SeeTag tag)
         throws IOException
   {
      mOut.write("<see ");
      generateTagHeader(tag);
      mOut.write(">");
      final String label;
      if (!StringUtil.isNullOrEmpty(tag.label()))
      {
         label = tag.label();
      }
      else if (tag.referencedClassName() != null
            && tag.referencedMemberName() != null)
      {
         label = tag.referencedClassName() + "#" + tag.referencedMemberName();
      }
      else if (tag.referencedClassName() != null)
      {
         label = tag.referencedClassName();
      }
      else if (tag.referencedPackage() != null)
      {
         label = tag.referencedPackage().name();
      }
      else if (tag.referencedMemberName() != null)
      {
         label = tag.referencedMemberName();
      }
      else
      {
         label = "";
      }
      mOut.write(XmlUtil.escape(label));
      mOut.write("</see>");
   }

   private void generateSourcePositionHeader (SourcePosition position)
         throws IOException
   {
      if (position.file() != null)
      {
         addAttribute("file", position.file().getPath());
      }
      addAttribute("line", position.line());
      addAttribute("column", position.column());
   }

   private void generateClassHeader (ClassDoc cd)
         throws IOException
   {
      generateProgramElementHeader(cd);
      addAttribute("abstract", cd.isAbstract());
      addAttribute("externalizable", cd.isExternalizable());
      addAttribute("serializable", cd.isSerializable());
      if (cd.superclass() != null)
      {
         addAttribute("superclass", cd.superclass().qualifiedName());
      }
   }

   private void generateProgramElementHeader (ProgramElementDoc pe)
         throws IOException
   {
      addAttribute("qualified-name", pe.qualifiedName());

      if (pe.containingClass() != null)
      {
         addAttribute("containing-class",
               pe.containingClass().qualifiedName());
      }

      final String visibility;
      if (pe.isPrivate())
      {
         visibility = "private";
      }
      else if (pe.isProtected())
      {
         visibility = "protected";
      }
      else if (pe.isPackagePrivate())
      {
         visibility = "package private";
      }
      else if (pe.isPublic())
      {
         visibility = "public";
      }
      else
      {
         throw new RuntimeException("Could not detect access right " + pe);
      }
      addAttribute("visibility", visibility);
      addAttribute("static", pe.isStatic());
      addAttribute("final", pe.isFinal());
      addAttribute("modifiers", pe.modifiers());
      addAttribute("modifier-specifier",
            String.valueOf(pe.modifierSpecifier()));

      generateDocHeader(pe);
   }

   private void generateDocHeader (Doc doc)
         throws IOException
   {
      addAttribute("name", doc.name());
      addAttribute("exception", doc.isException());
      addAttribute("error", doc.isError());
      addAttribute("ordinary-class", doc.isOrdinaryClass());
      if (doc.position() != null)
      {
         generateSourcePositionHeader(doc.position());
      }
      if (doc.isInterface())
      {
         addAttribute("type", "interface");
      }
      else if (doc.isClass())
      {
         addAttribute("type", "class");
      }
   }

   private void addAttribute (String name, boolean value)
         throws IOException
   {
      if (value)
      {
         mOut.write(" ");
         mOut.write(name);
         mOut.write("='");
         mOut.write(name);
         mOut.write("'");
      }
   }

   private void addAttribute (String name, int value)
         throws IOException
   {
      addAttribute(name, Integer.toString(value));
   }

   private void addAttribute (String name, String value)
         throws IOException
   {
      if (!StringUtil.isEmptyOrNull(value))
      {
         mOut.write(" ");
         mOut.write(name);
         mOut.write("='");
         mOut.write(XmlUtil.attributeEscape(value));
         mOut.write("'");
      }
   }

   private void warn (SourcePosition pos, String string, Object parameter)
   {
      mRootDoc.printWarning(pos, string + " at " + parameter);
   }

}


text:
package com.redhat.ceylon.cmr.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Pack200;
import java.util.jar.Pack200.Packer;
import java.util.jar.Pack200.Unpacker;
import java.util.zip.ZipEntry;

import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.common.log.Logger;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.impl.ShaSigner;
import com.redhat.ceylon.common.FileUtil;

public final class JarUtils {

    /** A simple filter to determine if an entry should be included in an archive. */
    public static interface JarEntryFilter {
        public boolean avoid(String entryFullName);
    }

    public static void finishUpdatingJar(File originalFile, File outputFile, ArtifactContext context,
            JarOutputStream jarOutputStream, JarEntryFilter filter,
            RepositoryManager repoManager, boolean verbose, Logger log,
            Set<String> folders) throws IOException {
        finishUpdatingJar(originalFile, outputFile, context, jarOutputStream, filter, repoManager, verbose, log, folders, false);
    }

    public static void finishUpdatingJar(File originalFile, File outputFile, ArtifactContext context,
            JarOutputStream jarOutputStream, JarEntryFilter filter,
            RepositoryManager repoManager, boolean verbose, Logger log,
            Set<String> folders, boolean pack200) throws IOException {
        // now copy all previous jar entries
        if (originalFile != null) {
            JarFile jarFile = new JarFile(originalFile);
            Enumeration<JarEntry> entries = jarFile.entries();
            while(entries.hasMoreElements()){
                JarEntry entry = entries.nextElement();
                // skip the old entry if we overwrote it
                if(filter.avoid(entry.getName()))
                    continue;
                // only preserve directories if we did not write to them
                if(entry.isDirectory() && folders.contains(entry.getName()))
                    continue;
                ZipEntry copiedEntry = new ZipEntry(entry.getName());
                // Preserve the modification time and comment
                copiedEntry.setTime(entry.getTime());
                copiedEntry.setComment(entry.getComment());
                jarOutputStream.putNextEntry(copiedEntry);
                if(!entry.isDirectory()){
                    InputStream inputStream = jarFile.getInputStream(entry);
                    copy(inputStream, jarOutputStream);
                    inputStream.close();
                }
                jarOutputStream.closeEntry();
            }
            jarFile.close();
        }
        // now write all the required directories
        for(String folder : folders){
            ZipEntry dir = new ZipEntry(folder);
            jarOutputStream.putNextEntry(dir);
            jarOutputStream.closeEntry();
        }
        jarOutputStream.flush();
        jarOutputStream.close();
        if(verbose){
            log.info("[done writing to jar: "+outputFile.getPath()+"]");
            //Log.printLines(log.noticeWriter, "[done writing to jar: "+outputFile.getPath()+"]");
        }

        if (pack200) {
            repack(outputFile, log);
        }

        File sha1File = ShaSigner.sign(outputFile, log, verbose);
        try {
            context.setForceOperation(true);
            repoManager.putArtifact(context, outputFile);
            ArtifactContext sha1Context = context.getSha1Context();
            sha1Context.setForceOperation(true);
            repoManager.putArtifact(sha1Context, sha1File);
        } catch(RuntimeException x) {
            log.error("Failed to write module to repository: "+x.getMessage());
            // fatal errors go all the way up but don't print anything if we logged an error
            throw x;
        } finally {
            // now cleanup
            outputFile.delete();
            sha1File.delete();
        }
    }

    /**
     * Takes the jar generated file and repacks it using pack200 in an attempt
     * to reduce the file size. This is only worth doing on jars containing class files.
     */
    private static void repack(File outputFile, Logger log) throws IOException,
            FileNotFoundException {
        Packer packer = Pack200.newPacker();
        packer.properties().put(Packer.EFFORT, "9");
        packer.properties().put(Packer.KEEP_FILE_ORDER, Packer.FALSE);
        packer.properties().put(Packer.DEFLATE_HINT, Packer.TRUE);
        packer.properties().put(Packer.SEGMENT_LIMIT, "-1");
        packer.properties().put(Packer.MODIFICATION_TIME, Packer.LATEST);
        File tmp = File.createTempFile("ceylon-jarutils-", ".pack200", outputFile.getParentFile());
        try {
            try (OutputStream out = new FileOutputStream(tmp)) {
                try (JarFile in = new JarFile(outputFile)) {
                    packer.pack(in, out);
                }
            }

            try (JarOutputStream outStream = new JarOutputStream(new FileOutputStream(outputFile))) {
                outStream.setLevel(9);
                Unpacker unpacker = Pack200.newUnpacker();
                unpacker.unpack(tmp, outStream);
            }
        } finally {
            tmp.delete();
        }
        log.debug("[repacked jar: "+outputFile.getPath()+"]");
    }

    public static String toPlatformIndependentPath(Iterable<? extends File> sourcePaths, String prefixedSourceFile) {
        String sourceFile = FileUtil.relativeFile(sourcePaths, prefixedSourceFile);
        // zips are UNIX-friendly
        sourceFile = sourceFile.replace(File.separatorChar, '/');
        return sourceFile;
    }

    public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[4096];
        int read;
        while((read = inputStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, read);
        }
        outputStream.flush();
    }

    public static long oldestFileTime(File file) {
        long mtime = Long.MAX_VALUE;
        JarFile jarFile = null;
        try {
            jarFile = new JarFile(file);
            Enumeration<JarEntry> entries = jarFile.entries();
            while(entries.hasMoreElements()){
                JarEntry entry = entries.nextElement();
                if (entry.getTime() < mtime) {
                    mtime = entry.getTime();
                }
            }
        } catch (Exception ex) {
            mtime = Long.MIN_VALUE;
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }
        return mtime;
    }

    public static String getFolder(String fileName) {
        int lastSep = fileName.lastIndexOf('/');
        // toplevel does not need a folder
        if(lastSep == -1)
            return null;
        // include the last slash to create a folder
        return fileName.substring(0, lastSep+1);
    }
}


text: A client for WAMPVOIP.


text:
require 'spec_helper'
require 'rollbar'
require 'socket'

Rollbar.plugins.load!

shared_examples 'unloadable' do
  it "doesn't load" do
    subject.load!
    expect(subject.loaded).to eq(false)
  end
end

describe 'basic_socket plugin' do
  subject { Rollbar.plugins.get('basic_socket') }

  before(:all) do
    Rollbar.plugins.get('basic_socket').unload!
  end

  after(:each) do
    subject.unload!
  end

  it 'is an on demand plugin' do
    expect(subject.on_demand).to eq(true)
  end

  it "doesn't load by default" do
    expect(subject.loaded).to eq(false)
  end

  describe '#load_scoped!' do
    context 'with core monkey patching enabled' do
      before { subject.configuration.disable_core_monkey_patch = false }

      if Gem::Version.new(ActiveSupport::VERSION::STRING) < Gem::Version.new('4.1.0')
        context 'using active_support < 4.1' do
          it 'changes implementation of ::BasicSocket#as_json temporarily' do
            original_implementation = BasicSocket
                                      .public_instance_method(:as_json)
                                      .source_location

            subject.load_scoped! do
              expect(subject.loaded).to eq(true)
              socket = TCPSocket.new 'example.com', 80
              expect(socket.as_json).to include(:value)
              expect(socket.as_json[:value]).to match(/TCPSocket/)
            end

            expect(subject.loaded).to eq(false)
            expect(BasicSocket.public_instance_method(:as_json).source_location)
              .to(eq(original_implementation))
          end
        end
      else
        context 'using active_support >= 4.1' do
          context 'when called as transparent' do
            it 'executes provided block even when dependencies are unmet' do
              result = false
              subject.load_scoped!(true) do
                result = true
                expect(subject.loaded).to eq(false) # Plugin should not load
              end
              expect(result).to eq(true)
              expect(subject.loaded).to eq(false)
            end
          end
        end
      end
    end
  end

  describe '#load!' do
    if Gem::Version.new(ActiveSupport::VERSION::STRING) < Gem::Version.new('4.1.0')
      context 'using active_support < 4.1' do
        context 'with core monkey patching enabled' do
          before { subject.configuration.disable_core_monkey_patch = false }

          it 'loads' do
            subject.load!
            expect(subject.loaded).to eq(true)

            subject.unload!
            expect(subject.loaded).to eq(false)
          end

          it 'changes implementation of ::BasicSocket#as_json' do
            subject.load!
            socket = TCPSocket.new 'example.com', 80
            expect(socket.as_json).to include(:value)
            expect(socket.as_json[:value]).to match(/TCPSocket/)

            subject.unload!
            expect(subject.loaded).to eq(false)
          end
        end

        context 'with core monkey patching disabled' do
          before { subject.configuration.disable_core_monkey_patch = true }

          it_should_behave_like 'unloadable'
        end
      end
    else
      context 'using active_support >= 4.1' do
        it_should_behave_like 'unloadable'
      end
    end
  end
end


text:
package com.tectonica.jonix.onix3;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.OnixElement;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Prize or award year

 *

 * The year in which a prize or award was given. Optional and non-repeating.
 *

 *

 *

 * Format
 * Four digits, YYYY
 *

 *

 * Reference name
 * <tt><PrizeYear></tt>
 *

 *

 * Short tag
 * <tt><g127></tt>
 *

 *

 * Cardinality
 * 0…1
 *

 *

 * Example
 * <tt><PrizeYear>1999</PrizeYear></tt>
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link Prize}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link CollateralDetail} ⯈ {@link Prize} ⯈ {@link PrizeYear}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link Contributor} ⯈ {@link Prize} ⯈
 * {@link PrizeYear}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ContentDetail} ⯈ {@link ContentItem} ⯈ {@link Contributor} ⯈
 * {@link Prize} ⯈ {@link PrizeYear}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link PromotionDetail} ⯈ {@link PromotionalEvent} ⯈ {@link Contributor}
 * ⯈ {@link Prize} ⯈ {@link PrizeYear}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link Collection} ⯈ {@link Contributor} ⯈
 * {@link Prize} ⯈ {@link PrizeYear}

 *

 */
public class PrizeYear implements OnixElement<String>, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "PrizeYear";
    public static final String shortname = "g127";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * (type: dt.DateOrDateTime)
     */
    public String datestamp;

    /**
     * (type: dt.NonEmptyString)
     */
    public String sourcename;

    public RecordSourceTypes sourcetype;

    /////////////////////////////////////////////////////////////////////////////////
    // VALUE MEMBER
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * This is the raw content of PrizeYear. Could be null if {@code exists() == false}. Use {@link #value()} instead if
     * you want to get this as an {@link java.util.Optional}.
     *

     * Raw Format: Four digits, YYYY
     *

     * (type: dt.Year)
     */
    public String value;

    /**
     * Internal API, use the {@link #value()} method or the {@link #value} field instead
     */
    @Override
    public String _value() {
        return value;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // SERVICES
    /////////////////////////////////////////////////////////////////////////////////

    private final boolean exists;
    public static final PrizeYear EMPTY = new PrizeYear();

    public PrizeYear() {
        exists = false;
    }

    public PrizeYear(org.w3c.dom.Element element) {
        exists = true;
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcename = JPU.getAttribute(element, "sourcename");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));

        value = JPU.getContentAsString(element);
    }

    /**
     * @return whether this tag (<PrizeYear> or <g127>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }
}


text:
package org.openmrs.projectbuendia.webservices.rest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openmrs.api.EncounterService;
import org.openmrs.api.LocationService;
import org.openmrs.api.OrderService;
import org.openmrs.api.PatientService;
import org.openmrs.api.ProviderService;
import org.openmrs.api.context.Context;
import org.openmrs.module.webservices.rest.web.v1_0.controller.MainResourceControllerTest;
import org.openmrs.test.BaseModuleContextSensitiveTest;
import org.openmrs.test.SkipBaseSetup;

import javax.servlet.http.HttpServletRequest;

import static org.junit.Assert.fail;

/** Base class for resource tests that issue simulated REST API requests. */
public abstract class BaseApiRequestTest extends MainResourceControllerTest {
    private static boolean VERBOSE = true;

    protected EncounterService encounterService;
    protected LocationService locationService;
    protected OrderService orderService;
    protected PatientService patientService;
    protected ProviderService providerService;

    @Override public String getNamespace() {
        return "buendia";
    }

    /** Returns the path of the resource, under the path "/buendia". */
    public abstract String getURI();

    /** The expected number of records returned by a GET request to the main resource path. */
    public abstract long getAllCount();

    /** Returns a UUID for testing basic GET queries (only to verify a non-error, non-null result). */
    public abstract String getUuid();

    /** A list of the data files to preload with executeDataSet() before every test. */
    public abstract String[] getInitialDataFiles();

    @Rule public TestRule watcher = new TestWatcher() {
        protected void starting(Description description) {
            if (VERBOSE) System.err.println("=== Starting " + description.getMethodName() + "()");
        }
        protected void succeeded(Description description) {
            if (VERBOSE) System.err.println("\u001b[32;1m=== PASSED: " + description.getMethodName() + "()\u001b[0m");
        }
        protected void failed(Description description) {
            if (VERBOSE) System.err.println("\u001b[31;1m=== FAILED: " + description.getMethodName() + "()\u001b[0m");
        }
    };

    /**
     * {@link BaseModuleContextSensitiveTest} does this initialization, but also pre-loads
     * the database with a bunch of records. We don't want to load those records, because
     * we'd then have to augment them with `buendia_[type]_sync_map` records, which would
     * couple our test integrity to the records in OpenMRS' test data. For this reason, we disable
     * {@link BaseModuleContextSensitiveTest}'s setup by putting the {@link SkipBaseSetup}
     * annotation on the class, but then we've got to explicitly init the database and
     * authenticate ourselves.
     */
    @Before public void setUp() throws Exception {
        Logger.SILENT = !VERBOSE;

        encounterService = Context.getEncounterService();
        locationService = Context.getLocationService();
        orderService = Context.getOrderService();
        patientService = Context.getPatientService();
        providerService = Context.getProviderService();

        if (useInMemoryDatabase()) {
            initializeInMemoryDatabase();
            authenticate();
        }
        for (String path : getInitialDataFiles()) {
            executeDataSet(path);
        }
    }

    protected void assertExceptionOnRequest(HttpServletRequest request, String reason) {
        try {
            handle(request);
            fail("Exception due to " + reason + " was not thrown as expected");
        } catch (Exception expected) {
            if (VERBOSE) System.err.println(expected.getClass().getName()
                + " due to " + reason + " was thrown as expected");
        }
    }
}


text:
---
id: redis-cache
title: "Druid Redis Cache"
---

<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you 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.
  -->

A cache implementation for Druid based on [Redis](https://github.com/redis/redis).

Below are guidance and configuration options known to this module.

## Installation

Use [pull-deps](../../operations/pull-deps.md) tool shipped with Druid to install this [extension](../../development/extensions.md#community-extensions) on broker, historical and middle manager nodes.

```bash
java -classpath "druid_dir/lib/*" org.apache.druid.cli.Main tools pull-deps -c org.apache.druid.extensions.contrib:druid-redis-cache:{VERSION}
```

## Enabling

To enable this extension after installation,

1. [include](../../development/extensions.md#loading-extensions) this `druid-redis-cache` extension
2. to enable cache on broker nodes, follow [broker caching docs](../../configuration/index.md#broker-caching) to set related properties
3. to enable cache on historical nodes, follow [historical caching docs](../../configuration/index.md#historical-caching) to set related properties
4. to enable cache on middle manager nodes, follow [peon caching docs](../../configuration/index.md#peon-caching) to set related properties
5. set `druid.cache.type` to `redis`
6. add the following properties

## Configuration

### Cluster mode

To utilize a redis cluster, following properties must be set.

Note: some redis cloud service providers provide redis cluster service via a redis proxy, for these clusters, please follow the [Standalone mode](#standalone-mode) configuration below.

| Properties |Description|Default|Required|
|--------------------|-----------|-------|--------|
|`druid.cache.cluster.nodes`| Redis nodes in a cluster, represented in comma separated string. See example below | None | yes |
|`druid.cache.cluster.maxRedirection`| Max retry count | 5 | no |

#### Example

```properties
# a typical redis cluster with 6 nodes
druid.cache.cluster.nodes=127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005,127.0.0.1:7006
```

### Standalone mode

To use a standalone redis, following properties must be set.

| Properties |Description|Default|Required|
|--------------------|-----------|-------|--------|
|`druid.cache.host`|Redis server host|None|yes|
|`druid.cache.port`|Redis server port|None|yes|
|`druid.cache.database`|Redis database index|0|no|

Note: if both `druid.cache.cluster.nodes` and `druid.cache.host` are provided, cluster mode is preferred.

### Shared Properties

Except for the properties above, there are some extra properties which can be customized to meet different needs.

| Properties |Description|Default|Required|
|--------------------|-----------|-------|--------|
|`druid.cache.password`| Password to access redis server/cluster | None |no|
|`druid.cache.expiration`|Expiration for cache entries | P1D |no|
|`druid.cache.timeout`|Timeout for connecting to Redis and reading entries from Redis|PT2S|no|
|`druid.cache.maxTotalConnections`|Max total connections to Redis|8|no|
|`druid.cache.maxIdleConnections`|Max idle connections to Redis|8|no|
|`druid.cache.minIdleConnections`|Min idle connections to Redis|0|no|

For `druid.cache.expiration` and `druid.cache.timeout` properties, values can be format of `Period` or a number in milliseconds.

```properties
# Period format(recomended)
# cache expires after 1 hour
druid.cache.expiration=PT1H

# or in number(milliseconds) format
# 1 hour = 3_600_000 milliseconds
druid.cache.expiration=3600000
```

## Metrics

In addition to the normal cache metrics, the redis cache implementation also reports the following in both `total` and `delta`

|Metric|Description|Normal value|
|------|-----------|------------|
|`query/cache/redis/*/requests`|Count of requests to redis cache|whatever request to redis will increase request count by 1|


text:
<?php

namespace Flarum\Install;

use Flarum\Foundation\AppInterface;
use Flarum\Http\Middleware\DispatchRoute;
use Flarum\Http\Middleware\HandleErrorsWithWhoops;
use Flarum\Http\Middleware\StartSession;
use Flarum\Install\Console\InstallCommand;
use Illuminate\Contracts\Container\Container;
use Zend\Stratigility\MiddlewarePipe;

class Installer implements AppInterface
{
    /**
     * @var Container
     */
    protected $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * @return \Psr\Http\Server\RequestHandlerInterface
     */
    public function getRequestHandler()
    {
        $pipe = new MiddlewarePipe;
        $pipe->pipe($this->container->make(HandleErrorsWithWhoops::class));
        $pipe->pipe($this->container->make(StartSession::class));
        $pipe->pipe(
            new DispatchRoute($this->container->make('flarum.install.routes'))
        );

        return $pipe;
    }

    /**
     * @return \Symfony\Component\Console\Command\Command[]
     */
    public function getConsoleCommands()
    {
        return [
            $this->container->make(InstallCommand::class),
        ];
    }
}


text:
<ion-view ng-controller="PlacesController as placesScope">
	<ion-side-menus enable-menu-with-back-views="false">
		<ion-side-menu-content>
			<ion-tabs class="tabs-striped tabs-background-positive tabs-color-light tabs-icon-top tabs-top">
				<ion-tab title="{{ 'menu.list' | translate }}" icon="ion-document-text">
					<ion-nav-view name="list"></ion-nav-view>
				</ion-tab>
				<ion-tab title="{{ 'menu.map' | translate }}" icon="ion-earth" on-select="placesScope.broadcastPlacesFiltersChanged(true)">
					<ion-nav-view name="map"></ion-nav-view>
				</ion-tab>
			</ion-tabs>
		</ion-side-menu-content>
		<ion-side-menu side="right">
			<ng-include src="'templates/PARTS/side-menus/places-filters.html'"></ng-include>
		</ion-side-menu>
	</ion-side-menus>
</ion-view>


text:
<?php use_helper('I18N', 'Date') ?>
<?php include_partial('sympal_content/assets') ?>

<?php echo $title = __('Manage '.$contentType->getLabel().' Content', array(), 'messages'); $sf_response->setTitle($title); ?>

  <?php echo get_sympal_breadcrumbs(array(
    'Dashboard' => '@sympal_dashboard',
    'Site Content' => '@sympal_content_types_index',
    $contentType->getLabel() => '@sympal_content_list_type?type='.$contentType->getSlug()
  )) ?>

    <?php include_partial('sympal_content/list_header', array('pager' => $pager)) ?>

    <?php include_partial('sympal_content/filters', array('form' => $filters, 'configuration' => $configuration)) ?>

    <form action="<?php echo url_for('sympal_content_collection', array('action' => 'batch')) ?>" method="post">
    <?php include_partial('sympal_content/list', array('pager' => $pager, 'sort' => $sort, 'helper' => $helper)) ?>

      <?php include_partial('sympal_content/list_batch_actions', array('helper' => $helper)) ?>
      <?php include_partial('sympal_content/list_actions', array('helper' => $helper, 'contentType' => $contentType)) ?>

    </form>

    <?php include_partial('sympal_content/list_footer', array('pager' => $pager)) ?>