text:
/*
 * Implementation of turnstiles used to hold queue of threads blocked on
 * non-sleepable locks.  Sleepable locks use condition variables to
 * implement their queues.  Turnstiles differ from a sleep queue in that
 * turnstile queue's are assigned to a lock held by an owning thread.  Thus,
 * when one thread is enqueued onto a turnstile, it can lend its priority
 * to the owning thread.
 *
 * We wish to avoid bloating locks with an embedded turnstile and we do not
 * want to use back-pointers in the locks for the same reason.  Thus, we
 * use a similar approach to that of Solaris 7 as described in Solaris
 * Internals by Jim Mauro and Richard McDougall.  Turnstiles are looked up
 * in a hash table based on the address of the lock.  Each entry in the
 * hash table is a linked-lists of turnstiles and is called a turnstile
 * chain.  Each chain contains a spin mutex that protects all of the
 * turnstiles in the chain.
 *
 * Each time a thread is created, a turnstile is malloc'd and attached to
 * that thread.  When a thread blocks on a lock, if it is the first thread
 * to block, it lends its turnstile to the lock.  If the lock already has
 * a turnstile, then it gives its turnstile to the lock's turnstile's free
 * list.  When a thread is woken up, it takes a turnstile from the free list
 * if there are any other waiters.  If it is the only thread blocked on the
 * lock, then it reclaims the turnstile associated with the lock and removes
 * it from the hash table.
 *
 * XXX: We should probably implement some sort of sleep queue that condition
 * variables and sleepqueue's share.  On Solaris condition variables are
 * implemented using a hash table of sleep queues similar to our current
 * sleep queues.  We might want to investigate doing that ourselves.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/sys/kern/subr_turnstile.c,v 1.134.2.1 2003/12/11 20:01:52 jhb Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/ktr.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/mutex.h>
#include <sys/proc.h>
#include <sys/queue.h>
#include <sys/resourcevar.h>
#include <sys/turnstile.h>
#include <sys/sched.h>

/*
 * Constants for the hash table of turnstile chains.  TC_SHIFT is a magic
 * number chosen because the sleep queue's use the same value for the
 * shift.  Basically, we ignore the lower 8 bits of the address.
 * TC_TABLESIZE must be a power of two for TC_MASK to work properly.
 */
#define	TC_TABLESIZE	128			/* Must be power of 2. */
#define	TC_MASK		(TC_TABLESIZE - 1)
#define	TC_SHIFT	8
#define	TC_HASH(lock)	(((uintptr_t)(lock) >> TC_SHIFT) & TC_MASK)
#define	TC_LOOKUP(lock)	&turnstile_chains[TC_HASH(lock)]

/*
 * There are three different lists of turnstiles as follows.  The list
 * connected by ts_link entries is a per-thread list of all the turnstiles
 * attached to locks that we own.  This is used to fixup our priority when
 * a lock is released.  The other two lists use the ts_hash entries.  The
 * first of these two is turnstile chain list that a turnstile is on when
 * it is attached to a lock.  The second list to use ts_hash is the free
 * list hung off a turnstile that is attached to a lock.
 *
 * Each turnstile contains two lists of threads.  The ts_blocked list is
 * a linked list of threads blocked on the turnstile's lock.  The
 * ts_pending list is a linked list of threads previously awoken by
 * turnstile_signal() or turnstile_wait() that are waiting to be put on
 * the run queue.
 *
 * Locking key:
 *  c - turnstile chain lock
 *  q - td_contested lock
 */
struct turnstile {
	TAILQ_HEAD(, thread) ts_blocked;	/* (c + q) Blocked threads. */
	TAILQ_HEAD(, thread) ts_pending;	/* (c) Pending threads. */
	LIST_ENTRY(turnstile) ts_hash;		/* (c) Chain and free list. */
	LIST_ENTRY(turnstile) ts_link;		/* (q) Contested locks. */
	LIST_HEAD(, turnstile) ts_free;		/* (c) Free turnstiles. */
	struct lock_object *ts_lockobj;		/* (c) Lock we reference. */
	struct thread *ts_owner;		/* (c + q) Who owns the lock. */
};

struct turnstile_chain {
	LIST_HEAD(, turnstile) tc_turnstiles;	/* List of turnstiles. */
	struct mtx tc_lock;			/* Spin lock for this chain. */
};

static struct mtx td_contested_lock;
static struct turnstile_chain turnstile_chains[TC_TABLESIZE];

MALLOC_DEFINE(M_TURNSTILE, "turnstiles", "turnstiles");

/*
 * Prototypes for non-exported routines.
 */
static void	init_turnstile0(void *dummy);
static void	propagate_priority(struct thread *);
static void	turnstile_setowner(struct turnstile *ts, struct thread *owner);

/*
 * Walks the chain of turnstiles and their owners to propagate the priority
 * of the thread being blocked to all the threads holding locks that have to
 * release their locks before this thread can run again.
 */
static void
propagate_priority(struct thread *td)
{
	struct turnstile_chain *tc;
	struct turnstile *ts;
	struct thread *td1;
	int pri;

	mtx_assert(&sched_lock, MA_OWNED);
	pri = td->td_priority;
	ts = td->td_blocked;
	for (;;) {
		td = ts->ts_owner;

		if (td == NULL) {
			/*
			 * This really isn't quite right. Really
			 * ought to bump priority of thread that
			 * next acquires the lock.
			 */
			return;
		}

		MPASS(td->td_proc != NULL);
		MPASS(td->td_proc->p_magic == P_MAGIC);

		/*
		 * XXX: The owner of a turnstile can be stale if it is the
		 * first thread to grab a slock of a sx lock.  In that case
		 * it is possible for us to be at SSLEEP or some other
		 * weird state.  We should probably just return if the state
		 * isn't SRUN or SLOCK.
		 */
		KASSERT(!TD_IS_SLEEPING(td),
		    ("sleeping thread (pid %d) owns a non-sleepable lock",
		    td->td_proc->p_pid));

		/*
		 * If this thread already has higher priority than the
		 * thread that is being blocked, we are finished.
		 */
		if (td->td_priority <= pri)
			return;

		/*
		 * If lock holder is actually running, just bump priority.
		 */
		if (TD_IS_RUNNING(td)) {
			td->td_priority = pri;
			return;
		}

#ifndef SMP
		/*
		 * For UP, we check to see if td is curthread (this shouldn't
		 * ever happen however as it would mean we are in a deadlock.)
		 */
		KASSERT(td != curthread, ("Deadlock detected"));
#endif

		/*
		 * If on run queue move to new run queue, and quit.
		 * XXXKSE this gets a lot more complicated under threads
		 * but try anyhow.
		 */
		if (TD_ON_RUNQ(td)) {
			MPASS(td->td_blocked == NULL);
			sched_prio(td, pri);
			return;
		}

		/*
		 * Bump this thread's priority.
		 */
		td->td_priority = pri;

		/*
		 * If we aren't blocked on a lock, we should be.
		 */
		KASSERT(TD_ON_LOCK(td), (
		    "process %d(%s):%d holds %s but isn't blocked on a lock\n",
		    td->td_proc->p_pid, td->td_proc->p_comm, td->td_state,
		    ts->ts_lockobj->lo_name));

		/*
		 * Pick up the lock that td is blocked on.
		 */
		ts = td->td_blocked;
		MPASS(ts != NULL);
		tc = TC_LOOKUP(ts->ts_lockobj);
		mtx_lock_spin(&tc->tc_lock);

		/*
		 * This thread may not be blocked on this turnstile anymore
		 * but instead might already be woken up on another CPU
		 * that is waiting on sched_lock in turnstile_unpend() to
		 * finish waking this thread up.  We can detect this case
		 * by checking to see if this thread has been given a
		 * turnstile by either turnstile_signal() or
		 * turnstile_wakeup().  In this case, treat the thread as
		 * if it was already running.
		 */
		if (td->td_turnstile != NULL) {
			mtx_unlock_spin(&tc->tc_lock);
			return;
		}

		/*
		 * Check if the thread needs to be moved up on
		 * the blocked chain.  It doesn't need to be moved
		 * if it is already at the head of the list or if
		 * the item in front of it still has a higher priority.
		 */
		if (td == TAILQ_FIRST(&ts->ts_blocked)) {
			mtx_unlock_spin(&tc->tc_lock);
			continue;
		}

		td1 = TAILQ_PREV(td, threadqueue, td_lockq);
		if (td1->td_priority <= pri) {
			mtx_unlock_spin(&tc->tc_lock);
			continue;
		}

		/*
		 * Remove thread from blocked chain and determine where
		 * it should be moved up to.  Since we know that td1 has
		 * a lower priority than td, we know that at least one
		 * thread in the chain has a lower priority and that
		 * td1 will thus not be NULL after the loop.
		 */
		mtx_lock_spin(&td_contested_lock);
		TAILQ_REMOVE(&ts->ts_blocked, td, td_lockq);
		TAILQ_FOREACH(td1, &ts->ts_blocked, td_lockq) {
			MPASS(td1->td_proc->p_magic == P_MAGIC);
			if (td1->td_priority > pri)
				break;
		}

		MPASS(td1 != NULL);
		TAILQ_INSERT_BEFORE(td1, td, td_lockq);
		mtx_unlock_spin(&td_contested_lock);
		CTR4(KTR_LOCK,
		    "propagate_priority: td %p moved before %p on [%p] %s",
		    td, td1, ts->ts_lockobj, ts->ts_lockobj->lo_name);
		mtx_unlock_spin(&tc->tc_lock);
	}
}

/*
 * Early initialization of turnstiles.  This is not done via a SYSINIT()
 * since this needs to be initialized very early when mutexes are first
 * initialized.
 */
void
init_turnstiles(void)
{
	int i;

	for (i = 0; i < TC_TABLESIZE; i++) {
		LIST_INIT(&turnstile_chains[i].tc_turnstiles);
		mtx_init(&turnstile_chains[i].tc_lock, "turnstile chain",
		    NULL, MTX_SPIN);
	}
	mtx_init(&td_contested_lock, "td_contested", NULL, MTX_SPIN);
	thread0.td_turnstile = NULL;
}

static void
init_turnstile0(void *dummy)
{

	thread0.td_turnstile = turnstile_alloc();
}
SYSINIT(turnstile0, SI_SUB_LOCK, SI_ORDER_ANY, init_turnstile0, NULL);

/*
 * Set the owner of the lock this turnstile is attached to.
 */
static void
turnstile_setowner(struct turnstile *ts, struct thread *owner)
{

	mtx_assert(&td_contested_lock, MA_OWNED);
	MPASS(owner->td_proc->p_magic == P_MAGIC);
	MPASS(ts->ts_owner == NULL);
	ts->ts_owner = owner;
	LIST_INSERT_HEAD(&owner->td_contested, ts, ts_link);
}

/*
 * Malloc a turnstile for a new thread, initialize it and return it.
 */
struct turnstile *
turnstile_alloc(void)
{
	struct turnstile *ts;

	ts = malloc(sizeof(struct turnstile), M_TURNSTILE, M_WAITOK | M_ZERO);
	TAILQ_INIT(&ts->ts_blocked);
	TAILQ_INIT(&ts->ts_pending);
	LIST_INIT(&ts->ts_free);
	return (ts);
}

/*
 * Free a turnstile when a thread is destroyed.
 */
void
turnstile_free(struct turnstile *ts)
{

	MPASS(ts != NULL);
	MPASS(TAILQ_EMPTY(&ts->ts_blocked));
	MPASS(TAILQ_EMPTY(&ts->ts_pending));
	free(ts, M_TURNSTILE);
}

/*
 * Look up the turnstile for a lock in the hash table locking the associated
 * turnstile chain along the way.  Return with the turnstile chain locked.
 * If no turnstile is found in the hash table, NULL is returned.
 */
struct turnstile *
turnstile_lookup(struct lock_object *lock)
{
	struct turnstile_chain *tc;
	struct turnstile *ts;

	tc = TC_LOOKUP(lock);
	mtx_lock_spin(&tc->tc_lock);
	LIST_FOREACH(ts, &tc->tc_turnstiles, ts_hash)
		if (ts->ts_lockobj == lock)
			return (ts);
	return (NULL);
}

/*
 * Unlock the turnstile chain associated with a given lock.
 */
void
turnstile_release(struct lock_object *lock)
{
	struct turnstile_chain *tc;

	tc = TC_LOOKUP(lock);
	mtx_unlock_spin(&tc->tc_lock);
}

/*
 * Take ownership of a turnstile and adjust the priority of the new
 * owner appropriately.
 */
void
turnstile_claim(struct turnstile *ts)
{
	struct turnstile_chain *tc;
	struct thread *td, *owner;

	tc = TC_LOOKUP(ts->ts_lockobj);
	mtx_assert(&tc->tc_lock, MA_OWNED);

	owner = curthread;
	mtx_lock_spin(&td_contested_lock);
	turnstile_setowner(ts, owner);
	mtx_unlock_spin(&td_contested_lock);

	td = TAILQ_FIRST(&ts->ts_blocked);
	MPASS(td != NULL);
	MPASS(td->td_proc->p_magic == P_MAGIC);
	mtx_unlock_spin(&tc->tc_lock);

	/*
	 * Update the priority of the new owner if needed.
	 */
	mtx_lock_spin(&sched_lock);
	if (td->td_priority < owner->td_priority)
		owner->td_priority = td->td_priority;
	mtx_unlock_spin(&sched_lock);
}

/*
 * Block the current thread on the turnstile ts.  This function will context
 * switch and not return until this thread has been woken back up.  This
 * function must be called with the appropriate turnstile chain locked and
 * will return with it unlocked.
 */
void
turnstile_wait(struct turnstile *ts, struct lock_object *lock,
    struct thread *owner)
{
	struct turnstile_chain *tc;
	struct thread *td, *td1;

	td = curthread;
	tc = TC_LOOKUP(lock);
	mtx_assert(&tc->tc_lock, MA_OWNED);
	MPASS(td->td_turnstile != NULL);
	MPASS(owner != NULL);
	MPASS(owner->td_proc->p_magic == P_MAGIC);

	/* If the passed in turnstile is NULL, use this thread's turnstile. */
	if (ts == NULL) {
		ts = td->td_turnstile;
		LIST_INSERT_HEAD(&tc->tc_turnstiles, ts, ts_hash);
		KASSERT(TAILQ_EMPTY(&ts->ts_pending),
		    ("thread's turnstile has pending threads"));
		KASSERT(TAILQ_EMPTY(&ts->ts_blocked),
		    ("thread's turnstile has a non-empty queue"));
		KASSERT(LIST_EMPTY(&ts->ts_free),
		    ("thread's turnstile has a non-empty free list"));
		KASSERT(ts->ts_lockobj == NULL, ("stale ts_lockobj pointer"));
		ts->ts_lockobj = lock;
		mtx_lock_spin(&td_contested_lock);
		TAILQ_INSERT_TAIL(&ts->ts_blocked, td, td_lockq);
		turnstile_setowner(ts, owner);
		mtx_unlock_spin(&td_contested_lock);
	} else {
		TAILQ_FOREACH(td1, &ts->ts_blocked, td_lockq)
			if (td1->td_priority > td->td_priority)
				break;
		mtx_lock_spin(&td_contested_lock);
		if (td1 != NULL)
			TAILQ_INSERT_BEFORE(td1, td, td_lockq);
		else
			TAILQ_INSERT_TAIL(&ts->ts_blocked, td, td_lockq);
		mtx_unlock_spin(&td_contested_lock);
		MPASS(td->td_turnstile != NULL);
		LIST_INSERT_HEAD(&ts->ts_free, td->td_turnstile, ts_hash);
		MPASS(owner == ts->ts_owner);
	}
	td->td_turnstile = NULL;
	mtx_unlock_spin(&tc->tc_lock);

	mtx_lock_spin(&sched_lock);
	/*
	 * Handle race condition where a thread on another CPU that owns
	 * lock 'lock' could have woken us in between us dropping the
	 * turnstile chain lock and acquiring the sched_lock.
	 */
	if (td->td_flags & TDF_TSNOBLOCK) {
		td->td_flags &= ~TDF_TSNOBLOCK;
		mtx_unlock_spin(&sched_lock);
		return;
	}

#ifdef notyet
	/*
	 * If we're borrowing an interrupted thread's VM context, we
	 * must clean up before going to sleep.
	 */
	if (td->td_ithd != NULL) {
		struct ithd *it = td->td_ithd;

		if (it->it_interrupted) {
			if (LOCK_LOG_TEST(lock, 0))
				CTR3(KTR_LOCK, "%s: %p interrupted %p",
				    __func__, it, it->it_interrupted);
			intr_thd_fixup(it);
		}
	}
#endif

	/* Save who we are blocked on and switch. */
	td->td_blocked = ts;
	td->td_lockname = lock->lo_name;
	TD_SET_LOCK(td);
	propagate_priority(td);

	if (LOCK_LOG_TEST(lock, 0))
		CTR4(KTR_LOCK, "%s: td %p blocked on [%p] %s", __func__, td,
		    lock, lock->lo_name);

	td->td_proc->p_stats->p_ru.ru_nvcsw++;
	mi_switch();

	if (LOCK_LOG_TEST(lock, 0))
		CTR4(KTR_LOCK, "%s: td %p free from blocked on [%p] %s",
		    __func__, td, lock, lock->lo_name);

	mtx_unlock_spin(&sched_lock);
}

/*
 * Pick the highest priority thread on this turnstile and put it on the
 * pending list.  This must be called with the turnstile chain locked.
 */
int
turnstile_signal(struct turnstile *ts)
{
	struct turnstile_chain *tc;
	struct thread *td;
	int empty;

	MPASS(ts != NULL);
	MPASS(curthread->td_proc->p_magic == P_MAGIC);
	MPASS(ts->ts_owner == curthread);
	tc = TC_LOOKUP(ts->ts_lockobj);
	mtx_assert(&tc->tc_lock, MA_OWNED);

	/*
	 * Pick the highest priority thread blocked on this lock and
	 * move it to the pending list.
	 */
	td = TAILQ_FIRST(&ts->ts_blocked);
	MPASS(td->td_proc->p_magic == P_MAGIC);
	mtx_lock_spin(&td_contested_lock);
	TAILQ_REMOVE(&ts->ts_blocked, td, td_lockq);
	mtx_unlock_spin(&td_contested_lock);
	TAILQ_INSERT_TAIL(&ts->ts_pending, td, td_lockq);

	/*
	 * If the turnstile is now empty, remove it from its chain and
	 * give it to the about-to-be-woken thread.  Otherwise take a
	 * turnstile from the free list and give it to the thread.
	 */
	empty = TAILQ_EMPTY(&ts->ts_blocked);
	if (empty)
		MPASS(LIST_EMPTY(&ts->ts_free));
	else
		ts = LIST_FIRST(&ts->ts_free);
	LIST_REMOVE(ts, ts_hash);
	td->td_turnstile = ts;

	return (empty);
}

/*
 * Put all blocked threads on the pending list.  This must be called with
 * the turnstile chain locked.
 */
void
turnstile_wakeup(struct turnstile *ts)
{
	struct turnstile_chain *tc;
	struct turnstile *ts1;
	struct thread *td;

	MPASS(ts != NULL);
	MPASS(curthread->td_proc->p_magic == P_MAGIC);
	MPASS(ts->ts_owner == curthread);
	tc = TC_LOOKUP(ts->ts_lockobj);
	mtx_assert(&tc->tc_lock, MA_OWNED);

	/*
	 * Transfer the blocked list to the pending list.
	 */
	mtx_lock_spin(&td_contested_lock);
	TAILQ_CONCAT(&ts->ts_pending, &ts->ts_blocked, td_lockq);
	mtx_unlock_spin(&td_contested_lock);

	/*
	 * Give a turnstile to each thread.  The last thread gets
	 * this turnstile.
	 */
	TAILQ_FOREACH(td, &ts->ts_pending, td_lockq) {
		if (LIST_EMPTY(&ts->ts_free)) {
			MPASS(TAILQ_NEXT(td, td_lockq) == NULL);
			ts1 = ts;
		} else
			ts1 = LIST_FIRST(&ts->ts_free);
		LIST_REMOVE(ts1, ts_hash);
		td->td_turnstile = ts1;
	}
}

/*
 * Wakeup all threads on the pending list and adjust the priority of the
 * current thread appropriately.  This must be called with the turnstile
 * chain locked.
 */
void
turnstile_unpend(struct turnstile *ts)
{
	TAILQ_HEAD( ,thread) pending_threads;
	struct turnstile_chain *tc;
	struct thread *td;
	int cp, pri;

	MPASS(ts != NULL);
	MPASS(ts->ts_owner == curthread);
	tc = TC_LOOKUP(ts->ts_lockobj);
	mtx_assert(&tc->tc_lock, MA_OWNED);
	MPASS(!TAILQ_EMPTY(&ts->ts_pending));

	/*
	 * Move the list of pending threads out of the turnstile and
	 * into a local variable.
	 */
	TAILQ_INIT(&pending_threads);
	TAILQ_CONCAT(&pending_threads, &ts->ts_pending, td_lockq);
#ifdef INVARIANTS
	if (TAILQ_EMPTY(&ts->ts_blocked))
		ts->ts_lockobj = NULL;
#endif

	/*
	 * Remove the turnstile from this thread's list of contested locks
	 * since this thread doesn't own it anymore.  New threads will
	 * not be blocking on the turnstile until it is claimed by a new
	 * owner.
	 */
	mtx_lock_spin(&td_contested_lock);
	ts->ts_owner = NULL;
	LIST_REMOVE(ts, ts_link);
	mtx_unlock_spin(&td_contested_lock);
	mtx_unlock_spin(&tc->tc_lock);

	/*
	 * Adjust the priority of curthread based on other contested
	 * locks it owns.  Don't lower the priority below the base
	 * priority however.
	 */
	td = curthread;
	pri = PRI_MAX;
	mtx_lock_spin(&sched_lock);
	mtx_lock_spin(&td_contested_lock);
	LIST_FOREACH(ts, &td->td_contested, ts_link) {
		cp = TAILQ_FIRST(&ts->ts_blocked)->td_priority;
		if (cp < pri)
			pri = cp;
	}
	mtx_unlock_spin(&td_contested_lock);
	if (pri > td->td_base_pri)
		pri = td->td_base_pri;
	td->td_priority = pri;

	/*
	 * Wake up all the pending threads.  If a thread is not blocked
	 * on a lock, then it is currently executing on another CPU in
	 * turnstile_wait() or sitting on a run queue waiting to resume
	 * in turnstile_wait().  Set a flag to force it to try to acquire
	 * the lock again instead of blocking.
	 */
	while (!TAILQ_EMPTY(&pending_threads)) {
		td = TAILQ_FIRST(&pending_threads);
		TAILQ_REMOVE(&pending_threads, td, td_lockq);
		MPASS(td->td_proc->p_magic == P_MAGIC);
		if (TD_ON_LOCK(td)) {
			td->td_blocked = NULL;
			td->td_lockname = NULL;
			TD_CLR_LOCK(td);
			MPASS(TD_CAN_RUN(td));
			setrunqueue(td);
		} else {
			td->td_flags |= TDF_TSNOBLOCK;
			MPASS(TD_IS_RUNNING(td) || TD_ON_RUNQ(td));
		}
	}
	mtx_unlock_spin(&sched_lock);
}

/*
 * Return the first thread in a turnstile.
 */
struct thread *
turnstile_head(struct turnstile *ts)
{
#ifdef INVARIANTS
	struct turnstile_chain *tc;

	MPASS(ts != NULL);
	tc = TC_LOOKUP(ts->ts_lockobj);
	mtx_assert(&tc->tc_lock, MA_OWNED);
#endif
	return (TAILQ_FIRST(&ts->ts_blocked));
}

/*
 * Returns true if a turnstile is empty.
 */
int
turnstile_empty(struct turnstile *ts)
{
#ifdef INVARIANTS
	struct turnstile_chain *tc;

	MPASS(ts != NULL);
	tc = TC_LOOKUP(ts->ts_lockobj);
	mtx_assert(&tc->tc_lock, MA_OWNED);
#endif
	return (TAILQ_EMPTY(&ts->ts_blocked));
}


text:
/**
 * Autogenerated by Thrift Compiler (0.10.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using System.Runtime.Serialization;
using Thrift.Protocol;
using Thrift.Transport;

namespace Worldpay.Innovation.WPWithin.Rpc.Types
{

  #if !SILVERLIGHT
  [Serializable]
  #endif
  public partial class ServiceDetails : TBase
  {

    public int? ServiceId { get; set; }

    public string ServiceDescription { get; set; }

    public ServiceDetails() {
    }

    public void Read (TProtocol iprot)
    {
      iprot.IncrementRecursionDepth();
      try
      {
        TField field;
        iprot.ReadStructBegin();
        while (true)
        {
          field = iprot.ReadFieldBegin();
          if (field.Type == TType.Stop) {
            break;
          }
          switch (field.ID)
          {
            case 1:
              if (field.Type == TType.I32) {
                ServiceId = iprot.ReadI32();
              } else {
                TProtocolUtil.Skip(iprot, field.Type);
              }
              break;
            case 2:
              if (field.Type == TType.String) {
                ServiceDescription = iprot.ReadString();
              } else {
                TProtocolUtil.Skip(iprot, field.Type);
              }
              break;
            default:
              TProtocolUtil.Skip(iprot, field.Type);
              break;
          }
          iprot.ReadFieldEnd();
        }
        iprot.ReadStructEnd();
      }
      finally
      {
        iprot.DecrementRecursionDepth();
      }
    }

    public void Write(TProtocol oprot) {
      oprot.IncrementRecursionDepth();
      try
      {
        TStruct struc = new TStruct("ServiceDetails");
        oprot.WriteStructBegin(struc);
        TField field = new TField();
        if (ServiceId != null) {
          field.Name = "serviceId";
          field.Type = TType.I32;
          field.ID = 1;
          oprot.WriteFieldBegin(field);
          oprot.WriteI32(ServiceId.Value);
          oprot.WriteFieldEnd();
        }
        if (ServiceDescription != null) {
          field.Name = "serviceDescription";
          field.Type = TType.String;
          field.ID = 2;
          oprot.WriteFieldBegin(field);
          oprot.WriteString(ServiceDescription);
          oprot.WriteFieldEnd();
        }
        oprot.WriteFieldStop();
        oprot.WriteStructEnd();
      }
      finally
      {
        oprot.DecrementRecursionDepth();
      }
    }

    public override string ToString() {
      StringBuilder __sb = new StringBuilder("ServiceDetails(");
      bool __first = true;
      if (ServiceId != null) {
        if(!__first) { __sb.Append(", "); }
        __first = false;
        __sb.Append("ServiceId: ");
        __sb.Append(ServiceId);
      }
      if (ServiceDescription != null) {
        if(!__first) { __sb.Append(", "); }
        __first = false;
        __sb.Append("ServiceDescription: ");
        __sb.Append(ServiceDescription);
      }
      __sb.Append(")");
      return __sb.ToString();
    }

  }

}

redpajama_set_name: RedPajamaGithub


text:
set -e
# Update the version for for all droolsjbpm repositories

initializeWorkingDirAndScriptDir() {
    # Set working directory and remove all symbolic links
    workingDir=`pwd -P`

    # Go the script directory
    cd `dirname $0`
    # If the file itself is a symbolic link (ignoring parent directory links), then follow that link recursively
    # Note that scriptDir=`pwd -P` does not do that and cannot cope with a link directly to the file
    scriptFileBasename=`basename $0`
    while [ -L "$scriptFileBasename" ] ; do
        scriptFileBasename=`readlink $scriptFileBasename` # Follow the link
        cd `dirname $scriptFileBasename`
        scriptFileBasename=`basename $scriptFileBasename`
    done
    # Set script directory and remove other symbolic links (parent directory links)
    scriptDir=`pwd -P`
}

updateParentVersion() {
    mvn -B -N -s $scriptDir/update-version-all-settings.xml versions:update-parent -Dfull\
     -DparentVersion=[$newVersion] -DallowSnapshots=true -DgenerateBackupPoms=false
}

updateChildModulesVersion() {
    mvn -B -s $scriptDir/update-version-all-settings.xml versions:update-child-modules -Dfull\
     -DallowSnapshots=true -DgenerateBackupPoms=false
}

# Updates parent version and child modules versions for Maven project in current working dir
updateParentAndChildVersions() {
    # install the current version first (usually SNAPSHOT) as it is then needed later on when updating child modules
    mvn -B clean install -N
    updateParentVersion
    updateChildModulesVersion
}

initializeWorkingDirAndScriptDir
droolsjbpmOrganizationDir="$scriptDir/../../.."

if [ $# != 1 ]; then
    echo
    echo "Usage:"
    echo "  $0 releaseNewVersion"
    echo "For example:"
    echo "  $0 6.3.0.Final"
    echo
    exit 1
fi

newVersion=$1
echo "New version is $newVersion"

startDateTime=`date +%s`

cd $droolsjbpmOrganizationDir

for repository in `cat ${scriptDir}/../repository-list.txt` ; do
    echo

    if [ ! -d $droolsjbpmOrganizationDir/$repository ]; then
        echo "==============================================================================="
        echo "Missing Repository: $repository. SKIPPING!"
        echo "==============================================================================="
    else
        echo "==============================================================================="
        echo "Repository: $repository"
        echo "==============================================================================="
        cd $repository
        if [ $repository == 'droolsjbpm-build-bootstrap' ]; then
            # first build&install the current version (usually SNAPSHOT) as it is needed later by other repos
            mvn -B -Dfull clean install
            mvn -B -Dfull versions:set -DnewVersion=$newVersion -DallowSnapshots=true -DgenerateBackupPoms=false
            sed -i "s/<version\.org\.kie>.*<\/version.org.kie>/<version.org.kie>$newVersion<\/version.org.kie>/" pom.xml
            sed -i "s/<latestReleasedVersionFromThisBranch>.*<\/latestReleasedVersionFromThisBranch>/<latestReleasedVersionFromThisBranch>$newVersion<\/latestReleasedVersionFromThisBranch>/" pom.xml
            # workaround for http://jira.codehaus.org/browse/MVERSIONS-161
            mvn -B clean install -DskipTests
            returnCode=$?

        elif [ $repository = 'jbpm' ]; then
            updateParentAndChildVersions
            returnCode=$?
            sed -i "s/release.version=.*$/release.version=$newVersion/" jbpm-installer/build.properties

        elif [ $repository = 'droolsjbpm-tools' ]; then
            cd drools-eclipse
            mvn -B -Dfull tycho-versions:set-version -DnewVersion=$newVersion
            returnCode=$?
            # replace the leftovers not covered by the tycho plugin (bug?)
            # SNAPSHOT and release versions need to be handled differently
            versionToUse=$newVersion
            if [[ $newVersion == *-SNAPSHOT ]]; then
                versionToUse=`sed "s/-SNAPSHOT/.qualifier/" <<< $newVersion`
            fi
            sed -i "s/source_[^\"]*/source_$versionToUse/" org.drools.updatesite/category.xml
            sed -i "s/version=\"[0-9\.]*qualifier\"/version=\"$versionToUse\"/" org.drools.updatesite/category.xml
            cd ..
            if [ $returnCode == 0 ]; then
                mvn -B clean install -N
                updateParentVersion
                # workaround for http://jira.codehaus.org/browse/MVERSIONS-161
                mvn -B clean install -N -DskipTests
                cd drools-eclipse
                updateParentVersion
                cd ..
                updateChildModulesVersion
                returnCode=$?
            fi

        else
            updateParentAndChildVersions
            returnCode=$?
        fi

        if [ $returnCode != 0 ] ; then
            exit $returnCode
        fi

        cd ..
    fi
done

endDateTime=`date +%s`
spentSeconds=`expr $endDateTime - $startDateTime`

echo
echo "Total time: ${spentSeconds}s"


text:
var SecretinNodeAdapter = (function (exports, crypto, forge) {
  'use strict';

  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

  var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
  var forge__default = /*#__PURE__*/_interopDefaultLegacy(forge);

  /* eslint-disable max-classes-per-file */
  class Error$1 {
    constructor(errorObject) {
      this.message = 'Unknown error';
      if (typeof errorObject !== 'undefined') {
        this.errorObject = errorObject;
      } else {
        this.errorObject = null;
      }
    }
  }
  class InvalidHexStringError extends Error$1 {
    constructor() {
      super();
      this.message = 'Invalid hexString';
    }
  }

  /* eslint-disable no-bitwise */

  function hexStringToUint8Array(hexString) {
    if (hexString.length % 2 !== 0) {
      throw new InvalidHexStringError();
    }
    const arrayBuffer = new Uint8Array(hexString.length / 2);

    for (let i = 0; i < hexString.length; i += 2) {
      const byteValue = parseInt(hexString.substr(i, 2), 16);
      if (Number.isNaN(byteValue)) {
        throw new InvalidHexStringError();
      }
      arrayBuffer[i / 2] = byteValue;
    }

    return arrayBuffer;
  }

  function bytesToHexString(givenBytes) {
    if (!givenBytes) {
      return null;
    }

    const bytes = new Uint8Array(givenBytes);
    const hexBytes = [];

    for (let i = 0; i < bytes.length; i += 1) {
      let byteString = bytes[i].toString(16);
      if (byteString.length < 2) {
        byteString = `0${byteString}`;
      }
      hexBytes.push(byteString);
    }
    return hexBytes.join('');
  }

  function asciiToUint8Array(str) {
    const chars = [];
    for (let i = 0; i < str.length; i += 1) {
      chars.push(str.charCodeAt(i));
    }
    return new Uint8Array(chars);
  }

  function asciiToHexString(str) {
    return str
      .split('')
      .map((c) => `0${c.charCodeAt(0).toString(16)}`.slice(-2))
      .join('');
  }

  function hexStringToAscii(hexx) {
    const hex = hexx.toString();
    let str = '';
    for (let i = 0; i < hex.length; i += 2) {
      str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    }
    return str;
  }

  function bytesToASCIIString(bytes) {
    // String.fromCharCode.apply(null, new Uint8Array(bytes)) trigger Maximum call stack size exceeded
    const array = new Uint8Array(bytes);
    return array.reduce(
      (str, charIndex) => str + String.fromCharCode(charIndex),
      ''
    );
  }

  class AESGCMDecryptionError extends Error {
    constructor() {
      super();
      this.message = 'AES-GCM decryption error';
    }
  }

  function getSHA256(str) {
    const hash = crypto__default["default"].createHash('sha256');
    const data = asciiToUint8Array(str);
    hash.update(data);
    return Promise.resolve(hash.digest('hex'));
  }

  function genRSAOAEP() {
    return new Promise((resolve, reject) => {
      forge__default["default"].pki.rsa.generateKeyPair(4096, 0x10001, (err, keypair) => {
        if (err) {
          reject(err);
        } else {
          resolve(keypair);
        }
      });
    });
  }

  function generateWrappingKey() {
    const key = forge__default["default"].random.getBytesSync(32);
    return Promise.resolve(key);
  }

  function encryptAESGCM256(secret, key) {
    const result = {};
    if (typeof key === 'undefined') {
      const newKey = forge__default["default"].random.getBytesSync(32);
      result.key = newKey;
    } else {
      result.key = key;
    }

    const iv = forge__default["default"].random.getBytesSync(12);
    result.iv = asciiToHexString(iv);

    const cipher = forge__default["default"].cipher.createCipher('AES-GCM', result.key);
    cipher.start({
      iv,
      tagLength: 128,
    });
    cipher.update(forge__default["default"].util.createBuffer(JSON.stringify(secret)));
    cipher.finish();

    const data = asciiToHexString(cipher.output.getBytes());
    const tag = asciiToHexString(cipher.mode.tag.getBytes());
    result.secret = data;
    result.secret += tag;
    return Promise.resolve(result);
  }

  function decryptAESGCM256(secretObject, key) {
    const decipher = forge__default["default"].cipher.createDecipher('AES-GCM', key);
    const secret = hexStringToAscii(secretObject.secret);
    const data = secret.substr(0, secret.length - 16);
    const tag = secret.substr(data.length, 16);
    decipher.start({
      iv: hexStringToAscii(secretObject.iv),
      tag,
    });
    decipher.update(forge__default["default"].util.createBuffer(data));
    const pass = decipher.finish();
    if (pass) {
      const jsonStr = decipher.output.getBytes();
      // eslint-disable-next-line no-control-regex
      const breakingPattern = /[\x01-\x09\x0B-\x0C\x0E-\x1F]+/gi;
      return Promise.resolve(JSON.parse(jsonStr.replace(breakingPattern, '')));
    }
    return Promise.reject(new AESGCMDecryptionError());
  }

  function encryptRSAOAEP(secret, publicKey) {
    const encrypted = publicKey.encrypt(JSON.stringify(secret), 'RSA-OAEP', {
      md: forge__default["default"].md.sha256.create(),
    });
    return Promise.resolve(asciiToHexString(encrypted));
  }

  function decryptRSAOAEP(secret, privateKey) {
    const decrypted = privateKey.decrypt(hexStringToAscii(secret), 'RSA-OAEP', {
      md: forge__default["default"].md.sha256.create(),
    });
    return Promise.resolve(JSON.parse(decrypted));
  }

  function wrapRSAOAEP(key, publicKey) {
    const encrypted = publicKey.encrypt(key, 'RSA-OAEP', {
      md: forge__default["default"].md.sha256.create(),
    });
    return Promise.resolve(asciiToHexString(encrypted));
  }

  function sign(datas, key) {
    const pss = forge__default["default"].pss.create({
      md: forge__default["default"].md.sha256.create(),
      mgf: forge__default["default"].mgf.mgf1.create(forge__default["default"].md.sha256.create()),
      saltLength: 32,
    });

    const md = forge__default["default"].md.sha256.create();
    md.update(datas, 'utf8');

    const signature = key.sign(md, pss);

    return Promise.resolve(asciiToHexString(signature));
  }

  function verify(datas, signature, key) {
    const pss = forge__default["default"].pss.create({
      md: forge__default["default"].md.sha256.create(),
      mgf: forge__default["default"].mgf.mgf1.create(forge__default["default"].md.sha256.create()),
      saltLength: 32,
    });

    const md = forge__default["default"].md.sha256.create();
    md.update(datas, 'utf8');

    const valid = key.verify(
      md.digest().getBytes(),
      hexStringToAscii(signature),
      pss
    );
    return Promise.resolve(valid);
  }

  function unwrapRSAOAEP(wrappedKeyHex, privateKey) {
    const decrypted = privateKey.decrypt(
      hexStringToAscii(wrappedKeyHex),
      'RSA-OAEP',
      {
        md: forge__default["default"].md.sha256.create(),
      }
    );
    return Promise.resolve(decrypted);
  }

  function bigIntToBase64Url(fbin) {
    let hex = fbin.toRadix(16);
    if (hex.length % 2) {
      hex = `0${hex}`;
    }
    const buf = Buffer.from(hex, 'hex');
    const b64 = buf.toString('base64');
    const b64Url = b64.replace(/[+]/g, '-').replace(/\//g, '_').replace(/=/g, '');
    return b64Url;
  }

  function exportClearKey(key) {
    const e = bigIntToBase64Url(key.e);
    const n = bigIntToBase64Url(key.n);
    const jwk = {
      alg: 'RSA-OAEP-256',
      e,
      ext: true,
      key_ops: ['encrypt', 'wrapKey'],
      kty: 'RSA',
      n,
    };
    return Promise.resolve(jwk);
  }

  function convertOAEPToPSS(key) {
    return Promise.resolve(key);
  }

  function importPublicKey(jwkPublicKey) {
    const n = Buffer.from(jwkPublicKey.n, 'base64');
    const e = Buffer.from(jwkPublicKey.e, 'base64');

    const publicKey = forge__default["default"].pki.setRsaPublicKey(
      new forge__default["default"].jsbn.BigInteger(n.toString('hex'), 16),
      new forge__default["default"].jsbn.BigInteger(e.toString('hex'), 16)
    );
    return Promise.resolve(publicKey);
  }

  function derivePassword(password, parameters) {
    const result = {};

    let saltBuf;
    let iterations;
    if (typeof parameters === 'undefined') {
      saltBuf = asciiToUint8Array(forge__default["default"].random.getBytesSync(32));
      const iterationsBuf = forge__default["default"].random.getBytesSync(1);
      iterations = 100000 + iterationsBuf.charCodeAt(0);
    } else {
      saltBuf = hexStringToUint8Array(parameters.salt);
      if (typeof parameters.iterations === 'undefined') {
        iterations = 10000; // retrocompatibility
      } else {
        iterations = parameters.iterations;
      }
    }

    result.salt = bytesToHexString(saltBuf);
    result.iterations = iterations;

    const derivedKey = crypto__default["default"].pbkdf2Sync(
      password,
      saltBuf,
      iterations,
      32,
      'sha256'
    );

    result.key = bytesToASCIIString(derivedKey);

    return getSHA256(result.key).then((hash) => {
      result.hash = hash;
      return result;
    });
  }

  function exportKey(wrappingKey, key) {
    const result = {};

    const iv = forge__default["default"].random.getBytesSync(16);
    result.iv = asciiToHexString(iv);

    let jwk;

    if (typeof key.d !== 'undefined') {
      const d = bigIntToBase64Url(key.d);
      const dp = bigIntToBase64Url(key.dP);
      const dq = bigIntToBase64Url(key.dQ);
      const e = bigIntToBase64Url(key.e);
      const n = bigIntToBase64Url(key.n);
      const p = bigIntToBase64Url(key.p);
      const q = bigIntToBase64Url(key.q);
      const qi = bigIntToBase64Url(key.qInv);

      jwk = {
        alg: 'RSA-OAEP-256',
        d,
        dp,
        dq,
        e,
        ext: true,
        key_ops: ['decrypt', 'unwrapKey'],
        kty: 'RSA',
        n,
        p,
        q,
        qi,
      };
    } else {
      const b64Key = Buffer.from(key, 'binary').toString('base64');
      const b64UrlKey = b64Key
        .replace(/[+]/g, '-')
        .replace(/\//g, '_')
        .replace(/=/g, '');
      jwk = {
        alg: 'A256CBC',
        ext: true,
        k: b64UrlKey,
        key_ops: ['wrapKey', 'unwrapKey'],
        kty: 'oct',
      };
    }
    const cipher = forge__default["default"].cipher.createCipher('AES-CBC', wrappingKey);
    cipher.start({
      iv,
    });

    cipher.update(forge__default["default"].util.createBuffer(JSON.stringify(jwk)));
    cipher.finish();

    result.key = asciiToHexString(cipher.output.getBytes());
    return Promise.resolve(result);
  }

  function importPrivateKey(key, privateKeyObject) {
    const wrappedPrivateKey = hexStringToAscii(privateKeyObject.privateKey);
    const iv = hexStringToAscii(privateKeyObject.iv);

    const decipher = forge__default["default"].cipher.createDecipher('AES-CBC', key);
    decipher.start({ iv });
    decipher.update(forge__default["default"].util.createBuffer(wrappedPrivateKey));
    decipher.finish();
    const jwkPrivateKeyString = decipher.output.getBytes();

    const jwkPrivateKey = JSON.parse(jwkPrivateKeyString);

    const n = Buffer.from(jwkPrivateKey.n, 'base64');
    const e = Buffer.from(jwkPrivateKey.e, 'base64');
    const d = Buffer.from(jwkPrivateKey.d, 'base64');
    const p = Buffer.from(jwkPrivateKey.p, 'base64');
    const q = Buffer.from(jwkPrivateKey.q, 'base64');
    const dP = Buffer.from(jwkPrivateKey.dp, 'base64');
    const dQ = Buffer.from(jwkPrivateKey.dq, 'base64');
    const qInv = Buffer.from(jwkPrivateKey.qi, 'base64');

    const privateKey = forge__default["default"].pki.setRsaPrivateKey(
      new forge__default["default"].jsbn.BigInteger(n.toString('hex'), 16),
      new forge__default["default"].jsbn.BigInteger(e.toString('hex'), 16),
      new forge__default["default"].jsbn.BigInteger(d.toString('hex'), 16),
      new forge__default["default"].jsbn.BigInteger(p.toString('hex'), 16),
      new forge__default["default"].jsbn.BigInteger(q.toString('hex'), 16),
      new forge__default["default"].jsbn.BigInteger(dP.toString('hex'), 16),
      new forge__default["default"].jsbn.BigInteger(dQ.toString('hex'), 16),
      new forge__default["default"].jsbn.BigInteger(qInv.toString('hex'), 16)
    );
    return Promise.resolve(privateKey);
  }

  function importKey(key, keyObject) {
    const wrappedKey = hexStringToUint8Array(keyObject.key);
    const iv = hexStringToAscii(keyObject.iv);

    const decipher = forge__default["default"].cipher.createDecipher('AES-CBC', key);
    decipher.start({ iv });
    decipher.update(forge__default["default"].util.createBuffer(wrappedKey));
    decipher.finish();

    const jwkKeyString = decipher.output.getBytes();

    const jwkKey = JSON.parse(jwkKeyString);

    const importedKey = Buffer.from(jwkKey.k, 'base64');

    return Promise.resolve(importedKey.toString('binary'));
  }

  const SecretinNodeAdapter = {
    importKey,
    importPrivateKey,
    exportKey,
    derivePassword,
    importPublicKey,
    convertOAEPToPSS,
    exportClearKey,
    unwrapRSAOAEP,
    verify,
    sign,
    wrapRSAOAEP,
    decryptRSAOAEP,
    encryptRSAOAEP,
    decryptAESGCM256,
    encryptAESGCM256,
    generateWrappingKey,
    genRSAOAEP,
    getSHA256,
  };

  exports.convertOAEPToPSS = convertOAEPToPSS;
  exports.decryptAESGCM256 = decryptAESGCM256;
  exports.decryptRSAOAEP = decryptRSAOAEP;
  exports["default"] = SecretinNodeAdapter;
  exports.derivePassword = derivePassword;
  exports.encryptAESGCM256 = encryptAESGCM256;
  exports.encryptRSAOAEP = encryptRSAOAEP;
  exports.exportClearKey = exportClearKey;
  exports.exportKey = exportKey;
  exports.genRSAOAEP = genRSAOAEP;
  exports.generateWrappingKey = generateWrappingKey;
  exports.getSHA256 = getSHA256;
  exports.importKey = importKey;
  exports.importPrivateKey = importPrivateKey;
  exports.importPublicKey = importPublicKey;
  exports.sign = sign;
  exports.unwrapRSAOAEP = unwrapRSAOAEP;
  exports.verify = verify;
  exports.wrapRSAOAEP = wrapRSAOAEP;

  Object.defineProperty(exports, '__esModule', { value: true });

  return exports;

})({}, crypto, forge);


text:
package sk.lazyman.gizmo.web.error;

import org.wicketstuff.annotation.mount.MountPath;

/**
 * @author lazyman
 */
@MountPath("/error/403")
public class PageError403 extends PageError {

    public PageError403() {
        super(403);
    }
}


text:
package store

import (
	"testing"
	"time"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	generator "k8s.io/kube-state-metrics/v2/pkg/metric_generator"
)

func TestEndpointStore(t *testing.T) {
	// Fixed metadata on type and help text. We prepend this to every expected
	// output so we only have to modify a single place when doing adjustments.
	const metadata = `
		# HELP kube_endpoint_annotations Kubernetes annotations converted to Prometheus labels.
		# TYPE kube_endpoint_annotations gauge
		# HELP kube_endpoint_address_available (Deprecated since v2.6.0) Number of addresses available in endpoint.
		# TYPE kube_endpoint_address_available gauge
		# HELP kube_endpoint_address_not_ready (Deprecated since v2.6.0) Number of addresses not ready in endpoint
		# TYPE kube_endpoint_address_not_ready gauge
		# HELP kube_endpoint_created [STABLE] Unix creation timestamp
		# TYPE kube_endpoint_created gauge
		# HELP kube_endpoint_info [STABLE] Information about endpoint.
		# TYPE kube_endpoint_info gauge
		# HELP kube_endpoint_labels [STABLE] Kubernetes labels converted to Prometheus labels.
		# TYPE kube_endpoint_labels gauge
		# HELP kube_endpoint_ports [STABLE] Information about the Endpoint ports.
		# TYPE kube_endpoint_ports gauge
		# HELP kube_endpoint_address [STABLE] Information about Endpoint available and non available addresses.
		# TYPE kube_endpoint_address gauge
	`
	cases := []generateMetricsTestCase{
		{
			Obj: &v1.Endpoints{
				ObjectMeta: metav1.ObjectMeta{
					Name:              "test-endpoint",
					CreationTimestamp: metav1.Time{Time: time.Unix(1500000000, 0)},
					Namespace:         "default",
					Labels: map[string]string{
						"app": "foobar",
					},
				},
				Subsets: []v1.EndpointSubset{
					{
						Addresses: []v1.EndpointAddress{
							{IP: "127.0.0.1"}, {IP: "10.0.0.1"},
						},
						NotReadyAddresses: []v1.EndpointAddress{
							{IP: "10.0.0.10"},
						},
						Ports: []v1.EndpointPort{
							{Port: 8080, Name: "http", Protocol: v1.ProtocolTCP}, {Port: 8081, Name: "app", Protocol: v1.ProtocolTCP},
						},
					},
					{
						Addresses: []v1.EndpointAddress{
							{IP: "172.22.23.202"},
						},
						Ports: []v1.EndpointPort{
							{Port: 8443, Name: "https", Protocol: v1.ProtocolTCP}, {Port: 9090, Name: "prometheus", Protocol: v1.ProtocolTCP},
						},
					},
					{
						NotReadyAddresses: []v1.EndpointAddress{
							{IP: "192.168.1.3"}, {IP: "192.168.2.2"},
						},
						Ports: []v1.EndpointPort{
							{Port: 1234, Name: "syslog", Protocol: v1.ProtocolUDP}, {Port: 5678, Name: "syslog-tcp", Protocol: v1.ProtocolTCP},
						},
					},
				},
			},
			Want: metadata + `
				kube_endpoint_annotations{endpoint="test-endpoint",namespace="default"} 1
				kube_endpoint_address_available{endpoint="test-endpoint",namespace="default"} 6
				kube_endpoint_address_not_ready{endpoint="test-endpoint",namespace="default"} 6
				kube_endpoint_created{endpoint="test-endpoint",namespace="default"} 1.5e+09
				kube_endpoint_info{endpoint="test-endpoint",namespace="default"} 1
				kube_endpoint_labels{endpoint="test-endpoint",namespace="default"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="http",port_protocol="TCP",port_number="8080"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="app",port_protocol="TCP",port_number="8081"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="https",port_protocol="TCP",port_number="8443"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="prometheus",port_protocol="TCP",port_number="9090"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="syslog",port_protocol="UDP",port_number="1234"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="syslog-tcp",port_protocol="TCP",port_number="5678"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="127.0.0.1",ready="true"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="10.0.0.1",ready="true"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="172.22.23.202",ready="true"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="192.168.1.3",ready="false"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="192.168.2.2",ready="false"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="10.0.0.10",ready="false"} 1
			`,
		},
		{
			Obj: &v1.Endpoints{
				ObjectMeta: metav1.ObjectMeta{
					Name:              "single-port-endpoint",
					CreationTimestamp: metav1.Time{Time: time.Unix(1500000000, 0)},
					Namespace:         "default",
					Labels: map[string]string{
						"app": "single-foobar",
					},
				},
				Subsets: []v1.EndpointSubset{
					{
						Addresses: []v1.EndpointAddress{
							{IP: "127.0.0.1"}, {IP: "10.0.0.1"},
						},
						NotReadyAddresses: []v1.EndpointAddress{
							{IP: "10.0.0.10"},
						},
						Ports: []v1.EndpointPort{
							{Port: 8080, Protocol: v1.ProtocolTCP},
						},
					},
				},
			},
			Want: metadata + `
				kube_endpoint_annotations{endpoint="single-port-endpoint",namespace="default"} 1
				kube_endpoint_address_available{endpoint="single-port-endpoint",namespace="default"} 2
				kube_endpoint_address_not_ready{endpoint="single-port-endpoint",namespace="default"} 1
				kube_endpoint_created{endpoint="single-port-endpoint",namespace="default"} 1.5e+09
				kube_endpoint_info{endpoint="single-port-endpoint",namespace="default"} 1
				kube_endpoint_labels{endpoint="single-port-endpoint",namespace="default"} 1
				kube_endpoint_ports{endpoint="single-port-endpoint",namespace="default",port_name="",port_number="8080",port_protocol="TCP"} 1
				kube_endpoint_address{endpoint="single-port-endpoint",namespace="default",ip="127.0.0.1",ready="true"} 1
				kube_endpoint_address{endpoint="single-port-endpoint",namespace="default",ip="10.0.0.1",ready="true"} 1
				kube_endpoint_address{endpoint="single-port-endpoint",namespace="default",ip="10.0.0.10",ready="false"} 1
			`,
		},
	}
	for i, c := range cases {
		c.Func = generator.ComposeMetricGenFuncs(endpointMetricFamilies(nil, nil))
		c.Headers = generator.ExtractMetricFamilyHeaders(endpointMetricFamilies(nil, nil))
		if err := c.run(); err != nil {
			t.Errorf("unexpected collecting result in %vth run:\n%s", i, err)
		}
	}
}

func TestEndpointStoreWithLabels(t *testing.T) {
	// Fixed metadata on type and help text. We prepend this to every expected
	// output so we only have to modify a single place when doing adjustments.
	const metadata = `
		# HELP kube_endpoint_address_available (Deprecated since v2.6.0) Number of addresses available in endpoint.
		# TYPE kube_endpoint_address_available gauge
		# HELP kube_endpoint_address_not_ready (Deprecated since v2.6.0) Number of addresses not ready in endpoint
		# TYPE kube_endpoint_address_not_ready gauge
		# HELP kube_endpoint_annotations Kubernetes annotations converted to Prometheus labels.
		# TYPE kube_endpoint_annotations gauge
		# HELP kube_endpoint_created [STABLE] Unix creation timestamp
		# TYPE kube_endpoint_created gauge
		# HELP kube_endpoint_info [STABLE] Information about endpoint.
		# TYPE kube_endpoint_info gauge
		# HELP kube_endpoint_labels [STABLE] Kubernetes labels converted to Prometheus labels.
		# TYPE kube_endpoint_labels gauge
		# HELP kube_endpoint_ports [STABLE] Information about the Endpoint ports.
		# TYPE kube_endpoint_ports gauge
		# HELP kube_endpoint_address [STABLE] Information about Endpoint available and non available addresses.
		# TYPE kube_endpoint_address gauge
	`
	cases := []generateMetricsTestCase{
		{
			Obj: &v1.Endpoints{
				ObjectMeta: metav1.ObjectMeta{
					Name:              "test-endpoint",
					CreationTimestamp: metav1.Time{Time: time.Unix(1500000000, 0)},
					Namespace:         "default",
					Annotations: map[string]string{
						"app": "foobar",
					},
					Labels: map[string]string{
						"app": "foobar",
					},
				},
				Subsets: []v1.EndpointSubset{
					{
						Addresses: []v1.EndpointAddress{
							{IP: "127.0.0.1"}, {IP: "10.0.0.1"},
						},
						NotReadyAddresses: []v1.EndpointAddress{
							{IP: "10.0.0.10"},
						},
						Ports: []v1.EndpointPort{
							{Port: 8080, Name: "http", Protocol: v1.ProtocolTCP}, {Port: 8081, Name: "app", Protocol: v1.ProtocolTCP},
						},
					},
					{
						Addresses: []v1.EndpointAddress{
							{IP: "172.22.23.202"},
						},
						Ports: []v1.EndpointPort{
							{Port: 8443, Name: "https", Protocol: v1.ProtocolTCP}, {Port: 9090, Name: "prometheus", Protocol: v1.ProtocolTCP},
						},
					},
					{
						NotReadyAddresses: []v1.EndpointAddress{
							{IP: "192.168.1.3"}, {IP: "192.168.2.2"},
						},
						Ports: []v1.EndpointPort{
							{Port: 1234, Name: "syslog", Protocol: v1.ProtocolUDP}, {Port: 5678, Name: "syslog-tcp", Protocol: v1.ProtocolTCP},
						},
					},
				},
			},
			Want: metadata + `
				kube_endpoint_address_available{endpoint="test-endpoint",namespace="default"} 6
				kube_endpoint_address_not_ready{endpoint="test-endpoint",namespace="default"} 6
				kube_endpoint_annotations{endpoint="test-endpoint",annotation_app="foobar",namespace="default"} 1
				kube_endpoint_created{endpoint="test-endpoint",namespace="default"} 1.5e+09
				kube_endpoint_info{endpoint="test-endpoint",namespace="default"} 1
				kube_endpoint_labels{endpoint="test-endpoint",label_app="foobar",namespace="default"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="http",port_protocol="TCP",port_number="8080"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="app",port_protocol="TCP",port_number="8081"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="https",port_protocol="TCP",port_number="8443"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="prometheus",port_protocol="TCP",port_number="9090"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="syslog",port_protocol="UDP",port_number="1234"} 1
				kube_endpoint_ports{endpoint="test-endpoint",namespace="default",port_name="syslog-tcp",port_protocol="TCP",port_number="5678"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="127.0.0.1",ready="true"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="10.0.0.1",ready="true"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="172.22.23.202",ready="true"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="192.168.1.3",ready="false"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="192.168.2.2",ready="false"} 1
				kube_endpoint_address{endpoint="test-endpoint",namespace="default",ip="10.0.0.10",ready="false"} 1
			`,
		},
		{
			Obj: &v1.Endpoints{
				ObjectMeta: metav1.ObjectMeta{
					Name:              "single-port-endpoint",
					CreationTimestamp: metav1.Time{Time: time.Unix(1500000000, 0)},
					Namespace:         "default",
					Annotations: map[string]string{
						"app": "single-foobar",
					},
					Labels: map[string]string{
						"app": "single-foobar",
					},
				},
				Subsets: []v1.EndpointSubset{
					{
						Addresses: []v1.EndpointAddress{
							{IP: "127.0.0.1"}, {IP: "10.0.0.1"},
						},
						NotReadyAddresses: []v1.EndpointAddress{
							{IP: "10.0.0.10"},
						},
						Ports: []v1.EndpointPort{
							{Port: 8080, Protocol: v1.ProtocolTCP},
						},
					},
				},
			},
			Want: metadata + `
				kube_endpoint_annotations{endpoint="single-port-endpoint",annotation_app="single-foobar",namespace="default"} 1
				kube_endpoint_address_available{endpoint="single-port-endpoint",namespace="default"} 2
				kube_endpoint_address_not_ready{endpoint="single-port-endpoint",namespace="default"} 1
				kube_endpoint_created{endpoint="single-port-endpoint",namespace="default"} 1.5e+09
				kube_endpoint_info{endpoint="single-port-endpoint",namespace="default"} 1
				kube_endpoint_labels{endpoint="single-port-endpoint",label_app="single-foobar",namespace="default"} 1
				kube_endpoint_ports{endpoint="single-port-endpoint",namespace="default",port_name="",port_number="8080",port_protocol="TCP"} 1
				kube_endpoint_address{endpoint="single-port-endpoint",namespace="default",ip="127.0.0.1",ready="true"} 1
				kube_endpoint_address{endpoint="single-port-endpoint",namespace="default",ip="10.0.0.1",ready="true"} 1
				kube_endpoint_address{endpoint="single-port-endpoint",namespace="default",ip="10.0.0.10",ready="false"} 1
			`,
		},
	}
	for i, c := range cases {
		allowAnnotations := []string{
			"app",
		}
		allowLabels := []string{
			"app",
		}
		c.Func = generator.ComposeMetricGenFuncs(endpointMetricFamilies(allowAnnotations, allowLabels))
		c.Headers = generator.ExtractMetricFamilyHeaders(endpointMetricFamilies(allowAnnotations, allowLabels))
		if err := c.run(); err != nil {
			t.Errorf("unexpected collecting result in %vth run:\n%s", i, err)
		}
	}
}


text:
describe :kernel_object_id, :shared => true do
  # #object_id and #__id__ are aliases, so we only need one function
  # that tests both methods
  it "returns an integer" do
    mock('fixnum').send(@method).should be_kind_of(Fixnum)
    nil.send(@method).should be_kind_of(Fixnum)
  end

  it "returns the same value on all calls to id for a given object" do
    o1 = mock('x')
    o1.send(@method).should == o1.send(@method)
  end

  it "returns different values for different objects" do
    o1 = mock('o1')
    o2 = mock('o2')
    o1.send(@method).should_not == o2.send(@method)
  end

  it "returns the same value for two Fixnums with the same value" do
    o1 = 1
    o2 = 1
    o1.send(@method).should == o2.send(@method)
  end

  it "returns the same value for two Symbol literals" do
    o1 = :hello
    o2 = :hello
    o1.send(@method).should == o2.send(@method)
  end

  it "returns the same value for two true literals" do
    o1 = true
    o2 = true
    o1.send(@method).should == o2.send(@method)
  end

  it "returns the same value for two false literals" do
    o1 = false
    o2 = false
    o1.send(@method).should == o2.send(@method)
  end

  it "returns the same value for two nil literals" do
    o1 = nil
    o2 = nil
    o1.send(@method).should == o2.send(@method)
  end

  it "returns a different value for two Bignum literals" do
    o1 = 2e100.to_i
    o2 = 2e100.to_i
    o1.send(@method).should_not == o2.send(@method)
  end

  not_compliant_on :macruby do
    it "returns a different value for two Float literals" do
      o1 = 1.0
      o2 = 1.0
      o1.send(@method).should_not == o2.send(@method)
    end
  end

  it "returns a different value for two String literals" do
    o1 = "hello"
    o2 = "hello"
    o1.send(@method).should_not == o2.send(@method)
  end

  it "returns a different value for an object and its dup" do
    o1 = mock("object")
    o2 = o1.dup
    o1.send(@method).should_not == o2.send(@method)
  end
end


text:
package org.wso2.siddhi.test.standard;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.util.EventPrinter;

public class KslackTestClass {

    static final Logger log = Logger.getLogger(KslackTestClass.class);
    private int count;
    private long value;
    private boolean eventArrived;
    long startingTime = 0;
    long endingTime = 0;
    InputHandler secondHandler;

    @Before
    public void init() {
        count = 0;
        value = 0;
        eventArrived = false;
        startingTime = 0;
        endingTime = 0;
    }

    @Test
    public void perfTest() throws InterruptedException {
        log.info("Window PerfTest");
        SiddhiManager siddhiManager = new SiddhiManager();

        siddhiManager.defineStream("define stream inputStream (eventtt long, price long, volume long); ");

        String queryReference = siddhiManager.addQuery("from inputStream#window.kslack(eventtt , 5000) select eventtt, price, volume " +
                " insert into outputStream; ");

        //secondHandler = sendEvent();

        siddhiManager.addCallback(queryReference, new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                for (org.wso2.siddhi.core.event.Event event : inEvents) {
                    count++;

                    if (count == 1) {
                        org.junit.Assert.assertEquals(1l, event.getData()[0]);
                    }

                    if (count == 2) {
                        org.junit.Assert.assertEquals(4l, event.getData()[0]);
                    }

                    if (count == 3) {
                        org.junit.Assert.assertEquals(3l, event.getData()[0]);
                    }

                    if (count == 4) {
                        org.junit.Assert.assertEquals(5l, event.getData()[0]);
                    }

                    if (count == 5) {
                        org.junit.Assert.assertEquals(6l, event.getData()[0]);
                    }

                    if (count == 6) {
                        org.junit.Assert.assertEquals(7l, event.getData()[0]);
                    }

                    if (count == 7) {
                        org.junit.Assert.assertEquals(8l, event.getData()[0]);
                    }

                    if (count == 8) {
                        org.junit.Assert.assertEquals(9l, event.getData()[0]);
                    }

                    if (count == 9) {
                        org.junit.Assert.assertEquals(10l, event.getData()[0]);
                    }

                    if (count == 10) {
                        org.junit.Assert.assertEquals(13l, event.getData()[0]);
                    }

//                    try {
//                        secondHandler.send(event);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//                    }
                }
            }
        });

        InputHandler inputHandler = siddhiManager.getInputHandler("inputStream");

        inputHandler.send(new Object[]{1l, 700f, 100l});
        inputHandler.send(new Object[]{4l, 60.5f, 200l});
        inputHandler.send(new Object[]{3l, 60.5f, 200l});
        inputHandler.send(new Object[]{5l, 700f, 100l});
        inputHandler.send(new Object[]{6l, 60.5f, 200l});
        inputHandler.send(new Object[]{9l, 60.5f, 200l});
        inputHandler.send(new Object[]{7l, 700f, 100l});
        inputHandler.send(new Object[]{8l, 60.5f, 200l});
        inputHandler.send(new Object[]{10l, 60.5f, 200l});
        inputHandler.send(new Object[]{13l, 60.5f, 200l});

        Thread.sleep(7000);
        org.junit.Assert.assertEquals("Event count", 9, count);
        siddhiManager.shutdown();
    }

    private InputHandler sendEvent(){

        SiddhiManager siddhiManager = new SiddhiManager();

        siddhiManager.defineStream("define stream inputStream (eventtt long, price long, volume long); ");

        String queryReference = siddhiManager.addQuery("from inputStream select eventtt, price, volume " +
                " insert into outputStream; ");

        siddhiManager.addCallback(queryReference, new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(inEvents);
            }
        });

        InputHandler inputHandler = siddhiManager.getInputHandler("inputStream");
        return inputHandler;

    }

}


text:
'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    fingerprint: {
      prepend: 'https://totally-sick-cdn.example.com/',
      exclude: ['vendor.js', 'custom-fastboot-app.js'],
      generateAssetMap: true,
      assetMapPath: 'totally-customized-asset-map.json'
    }
  });

  return app.toTree();
};


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="@color/bright_foreground_dark_inverse" />
    <item android:color="@color/bright_foreground_dark_inverse" android:state_activated="true" />
    <item android:state_focused="true" android:color="@color/bright_foreground_dark_inverse" />
    <item android:state_pressed="true" android:color="@color/bright_foreground_dark_inverse" />
    <item android:color="@color/bright_foreground_dark" />
</selector>