text:
package roaring

import (
	"fmt"
	"github.com/RoaringBitmap/roaring"
	"math/bits"
	"runtime"
	"sync"
	"sync/atomic"
)

const (
	// Min64BitSigned - Minimum 64 bit value
	Min64BitSigned = -9223372036854775808
	// Max64BitSigned - Maximum 64 bit value
	Max64BitSigned = 9223372036854775807
)

// BSI is at its simplest is an array of bitmaps that represent an encoded
// binary value.  The advantage of a BSI is that comparisons can be made
// across ranges of values whereas a bitmap can only represent the existence
// of a single value for a given column ID.  Another usage scenario involves
// storage of high cardinality values.
//
// It depends upon the bitmap libraries.  It is not thread safe, so
// upstream concurrency guards must be provided.
type BSI struct {
	bA           []*roaring.Bitmap
	eBM          *roaring.Bitmap // Existence BitMap
	MaxValue     int64
	MinValue     int64
	runOptimized bool
}

// NewBSI constructs a new BSI.  Min/Max values are optional.  If set to 0
// then the underlying BSI will be automatically sized.
func NewBSI(maxValue int64, minValue int64) *BSI {

	bitsz := bits.Len64(uint64(minValue))
	if bits.Len64(uint64(maxValue)) > bitsz {
		bitsz = bits.Len64(uint64(maxValue))
	}
	ba := make([]*roaring.Bitmap, bitsz)
	for i := 0; i < len(ba); i++ {
		ba[i] = roaring.NewBitmap()
	}
	return &BSI{bA: ba, eBM: roaring.NewBitmap(), MaxValue: maxValue, MinValue: minValue}
}

// NewDefaultBSI constructs an auto-sized BSI
func NewDefaultBSI() *BSI {
	return NewBSI(int64(0), int64(0))
}

// RunOptimize attempts to further compress the runs of consecutive values found in the bitmap
func (b *BSI) RunOptimize() {
	b.eBM.RunOptimize()
	for i := 0; i < len(b.bA); i++ {
		b.bA[i].RunOptimize()
	}
	b.runOptimized = true
}

// HasRunCompression returns true if the bitmap benefits from run compression
func (b *BSI) HasRunCompression() bool {
	return b.runOptimized
}

// GetExistenceBitmap returns a pointer to the underlying existence bitmap of the BSI
func (b *BSI) GetExistenceBitmap() *roaring.Bitmap {
	return b.eBM
}

// ValueExists tests whether the value exists.
func (b *BSI) ValueExists(columnID uint64) bool {

	return b.eBM.Contains(uint32(columnID))
}

// GetCardinality returns a count of unique column IDs for which a value has been set.
func (b *BSI) GetCardinality() uint64 {
	return b.eBM.GetCardinality()
}

// BitCount returns the number of bits needed to represent values.
func (b *BSI) BitCount() int {

	return len(b.bA)
}

// SetValue sets a value for a given columnID.
func (b *BSI) SetValue(columnID uint64, value int64) {

	// If max/min values are set to zero then automatically determine bit array size
	if b.MaxValue == 0 && b.MinValue == 0 {
		ba := make([]*roaring.Bitmap, bits.Len64(uint64(value)))
		for i := len(ba) - b.BitCount(); i > 0; i-- {
			b.bA = append(b.bA, roaring.NewBitmap())
			if b.runOptimized {
				b.bA[i].RunOptimize()
			}
		}
	}

	var wg sync.WaitGroup

	for i := 0; i < b.BitCount(); i++ {
		wg.Add(1)
		go func(j int) {
			defer wg.Done()
			if uint64(value)&(1<<uint64(j)) > 0 {
				b.bA[j].Add(uint32(columnID))
			} else {
				b.bA[j].Remove(uint32(columnID))
			}
		}(i)
	}
	wg.Wait()
	b.eBM.Add(uint32(columnID))
}

// GetValue gets the value at the column ID.  Second param will be false for non-existant values.
func (b *BSI) GetValue(columnID uint64) (int64, bool) {
	value := int64(0)
	exists := b.eBM.Contains(uint32(columnID))
	if !exists {
		return value, exists
	}
	for i := 0; i < b.BitCount(); i++ {
		if b.bA[i].Contains(uint32(columnID)) {
			value |= (1 << uint64(i))
		}
	}
	return int64(value), exists
}

type action func(t *task, batch []uint32, resultsChan chan *roaring.Bitmap, wg *sync.WaitGroup)

func parallelExecutor(parallelism int, t *task, e action,
	foundSet *roaring.Bitmap) *roaring.Bitmap {

	var n int = parallelism
	if n == 0 {
		n = runtime.NumCPU()
	}

	resultsChan := make(chan *roaring.Bitmap, n)

	card := foundSet.GetCardinality()
	x := card / uint64(n)

	remainder := card - (x * uint64(n))
	var batch []uint32
	var wg sync.WaitGroup
	iter := foundSet.ManyIterator()
	for i := 0; i < n; i++ {
		if i == n-1 {
			batch = make([]uint32, x+remainder)
		} else {
			batch = make([]uint32, x)
		}
		iter.NextMany(batch)
		wg.Add(1)
		go e(t, batch, resultsChan, &wg)
	}

	wg.Wait()

	close(resultsChan)

	ba := make([]*roaring.Bitmap, 0)
	for bm := range resultsChan {
		ba = append(ba, bm)
	}

	return roaring.ParOr(0, ba...)

}

type bsiAction func(input *BSI, batch []uint32, resultsChan chan *BSI, wg *sync.WaitGroup)

func parallelExecutorBSIResults(parallelism int, input *BSI, e bsiAction, foundSet *roaring.Bitmap, sumResults bool) *BSI {

	var n int = parallelism
	if n == 0 {
		n = runtime.NumCPU()
	}

	resultsChan := make(chan *BSI, n)

	card := foundSet.GetCardinality()
	x := card / uint64(n)

	remainder := card - (x * uint64(n))
	var batch []uint32
	var wg sync.WaitGroup
	iter := foundSet.ManyIterator()
	for i := 0; i < n; i++ {
		if i == n-1 {
			batch = make([]uint32, x+remainder)
		} else {
			batch = make([]uint32, x)
		}
		iter.NextMany(batch)
		wg.Add(1)
		go e(input, batch, resultsChan, &wg)
	}

	wg.Wait()

	close(resultsChan)

	ba := make([]*BSI, 0)
	for bm := range resultsChan {
		ba = append(ba, bm)
	}

	results := NewDefaultBSI()
	if sumResults {
		for _, v := range ba {
			results.Add(v)
		}
	} else {
		results.ParOr(0, ba...)
	}
	return results

}

// Operation identifier
type Operation int

const (
	// LT less than
	LT Operation = 1 + iota
	// LE less than or equal
	LE
	// EQ equal
	EQ
	// GE greater than or equal
	GE
	// GT greater than
	GT
	// RANGE range
	RANGE
	// MIN find minimum
	MIN
	// MAX find maximum
	MAX
)

type task struct {
	bsi          *BSI
	op           Operation
	valueOrStart int64
	end          int64
	values       map[int64]struct{}
	bits         *roaring.Bitmap
}

// CompareValue compares value.
// For all operations with the exception of RANGE, the value to be compared is specified by valueOrStart.
// For the RANGE parameter the comparison criteria is >= valueOrStart and <= end.
// The parallelism parameter indicates the number of CPU threads to be applied for processing.  A value
// of zero indicates that all available CPU resources will be potentially utilized.
//
func (b *BSI) CompareValue(parallelism int, op Operation, valueOrStart, end int64,
	foundSet *roaring.Bitmap) *roaring.Bitmap {

	comp := &task{bsi: b, op: op, valueOrStart: valueOrStart, end: end}
	if foundSet == nil {
		return parallelExecutor(parallelism, comp, compareValue, b.eBM)
	}
	return parallelExecutor(parallelism, comp, compareValue, foundSet)
}

func compareValue(e *task, batch []uint32, resultsChan chan *roaring.Bitmap, wg *sync.WaitGroup) {

	defer wg.Done()

	results := roaring.NewBitmap()
	if e.bsi.runOptimized {
		results.RunOptimize()
	}

	x := e.bsi.BitCount()
	startIsNegative := x == 64 && uint64(e.valueOrStart)&(1<<uint64(x-1)) > 0
	endIsNegative := x == 64 && uint64(e.end)&(1<<uint64(x-1)) > 0

	for i := 0; i < len(batch); i++ {
		cID := batch[i]
		eq1, eq2 := true, true
		lt1, lt2, gt1 := false, false, false
		j := e.bsi.BitCount() - 1
		isNegative := false
		if x == 64 {
			isNegative = e.bsi.bA[j].Contains(cID)
			j--
		}
		compStartValue := e.valueOrStart
		compEndValue := e.end
		if isNegative != startIsNegative {
			compStartValue = ^e.valueOrStart + 1
		}
		if isNegative != endIsNegative {
			compEndValue = ^e.end + 1
		}
		for ; j >= 0; j-- {
			sliceContainsBit := e.bsi.bA[j].Contains(cID)

			if uint64(compStartValue)&(1<<uint64(j)) > 0 {
				// BIT in value is SET
				if !sliceContainsBit {
					if eq1 {
						if (e.op == GT || e.op == GE || e.op == RANGE) && startIsNegative && !isNegative {
							gt1 = true
						}
						if e.op == LT || e.op == LE {
							if !startIsNegative || (startIsNegative == isNegative) {
								lt1 = true
							}
						}
						eq1 = false
						break
					}
				}
			} else {
				// BIT in value is CLEAR
				if sliceContainsBit {
					if eq1 {
						if (e.op == LT || e.op == LE) && isNegative && !startIsNegative {
							lt1 = true
						}
						if e.op == GT || e.op == GE || e.op == RANGE {
							if startIsNegative || (startIsNegative == isNegative) {
								gt1 = true
							}
						}
						eq1 = false
						if e.op != RANGE {
							break
						}
					}
				}
			}

			if e.op == RANGE && uint64(compEndValue)&(1<<uint64(j)) > 0 {
				// BIT in value is SET
				if !sliceContainsBit {
					if eq2 {
						if !endIsNegative || (endIsNegative == isNegative) {
							lt2 = true
						}
						eq2 = false
						if startIsNegative && !endIsNegative {
							break
						}
					}
				}
			} else if e.op == RANGE {
				// BIT in value is CLEAR
				if sliceContainsBit {
					if eq2 {
						if isNegative && !endIsNegative {
							lt2 = true
						}
						eq2 = false
						break
					}
				}
			}
		}

		switch e.op {
		case LT:
			if lt1 {
				results.Add(cID)
			}
		case LE:
			if lt1 || (eq1 && (!startIsNegative || (startIsNegative && isNegative))) {
				results.Add(cID)
			}
		case EQ:
			if eq1 {
				results.Add(cID)
			}
		case GE:
			if gt1 || (eq1 && (startIsNegative || (!startIsNegative && !isNegative))) {
				results.Add(cID)
			}
		case GT:
			if gt1 {
				results.Add(cID)
			}
		case RANGE:
			if (eq1 || gt1) && (eq2 || lt2) {
				results.Add(cID)
			}
		default:
			panic(fmt.Sprintf("Unknown operation [%v]", e.op))
		}
	}

	resultsChan <- results
}

// MinMax - Find minimum or maximum value.
func (b *BSI) MinMax(parallelism int, op Operation, foundSet *roaring.Bitmap) int64 {

	var n int = parallelism
	if n == 0 {
		n = runtime.NumCPU()
	}

	resultsChan := make(chan int64, n)

	card := foundSet.GetCardinality()
	x := card / uint64(n)

	remainder := card - (x * uint64(n))
	var batch []uint32
	var wg sync.WaitGroup
	iter := foundSet.ManyIterator()
	for i := 0; i < n; i++ {
		if i == n-1 {
			batch = make([]uint32, x+remainder)
		} else {
			batch = make([]uint32, x)
		}
		iter.NextMany(batch)
		wg.Add(1)
		go b.minOrMax(op, batch, resultsChan, &wg)
	}

	wg.Wait()

	close(resultsChan)
	var minMax int64
	if op == MAX {
		minMax = Min64BitSigned
	} else {
		minMax = Max64BitSigned
	}

	for val := range resultsChan {
		if (op == MAX && val > minMax) || (op == MIN && val < minMax) {
			minMax = val
		}
	}
	return minMax
}

func (b *BSI) minOrMax(op Operation, batch []uint32, resultsChan chan int64, wg *sync.WaitGroup) {

	defer wg.Done()

	x := b.BitCount()
	var value int64 = Max64BitSigned
	if op == MAX {
		value = Min64BitSigned
	}

	for i := 0; i < len(batch); i++ {
		cID := batch[i]
		eq := true
		lt, gt := false, false
		j := b.BitCount() - 1
		var cVal int64
		valueIsNegative := uint64(value)&(1<<uint64(x-1)) > 0 && bits.Len64(uint64(value)) == 64
		isNegative := false
		if x == 64 {
			isNegative = b.bA[j].Contains(cID)
			if isNegative {
				cVal |= 1 << uint64(j)
			}
			j--
		}
		compValue := value
		if isNegative != valueIsNegative {
			compValue = ^value + 1
		}
		for ; j >= 0; j-- {
			sliceContainsBit := b.bA[j].Contains(cID)
			if sliceContainsBit {
				cVal |= 1 << uint64(j)
			}
			if uint64(compValue)&(1<<uint64(j)) > 0 {
				// BIT in value is SET
				if !sliceContainsBit {
					if eq {
						eq = false
						if op == MAX && valueIsNegative && !isNegative {
							gt = true
							break
						}
						if op == MIN && (!valueIsNegative || (valueIsNegative == isNegative)) {
							lt = true
						}
					}
				}
			} else {
				// BIT in value is CLEAR
				if sliceContainsBit {
					if eq {
						eq = false
						if op == MIN && isNegative && !valueIsNegative {
							lt = true
						}
						if op == MAX && (valueIsNegative || (valueIsNegative == isNegative)) {
							gt = true
						}
					}
				}
			}
		}
		if lt || gt {
			value = cVal
		}
	}

	resultsChan <- value
}

// Sum all values contained within the foundSet.   As a convenience, the cardinality of the foundSet
// is also returned (for calculating the average).
//
func (b *BSI) Sum(foundSet *roaring.Bitmap) (sum int64, count uint64) {

	count = foundSet.GetCardinality()
	var wg sync.WaitGroup
	for i := 0; i < b.BitCount(); i++ {
		wg.Add(1)
		go func(j int) {
			defer wg.Done()
			atomic.AddInt64(&sum, int64(foundSet.AndCardinality(b.bA[j])<<uint(j)))
		}(i)
	}
	wg.Wait()
	return
}

// Transpose calls b.IntersectAndTranspose(0, b.eBM)
func (b *BSI) Transpose() *roaring.Bitmap {
	return b.IntersectAndTranspose(0, b.eBM)
}

// IntersectAndTranspose is a matrix transpose function.  Return a bitmap such that the values are represented as column IDs
// in the returned bitmap. This is accomplished by iterating over the foundSet and only including
// the column IDs in the source (foundSet) as compared with this BSI.  This can be useful for
// vectoring one set of integers to another.
func (b *BSI) IntersectAndTranspose(parallelism int, foundSet *roaring.Bitmap) *roaring.Bitmap {

	trans := &task{bsi: b}
	return parallelExecutor(parallelism, trans, transpose, foundSet)
}

func transpose(e *task, batch []uint32, resultsChan chan *roaring.Bitmap, wg *sync.WaitGroup) {

	defer wg.Done()

	results := roaring.NewBitmap()
	if e.bsi.runOptimized {
		results.RunOptimize()
	}
	for _, cID := range batch {
		if value, ok := e.bsi.GetValue(uint64(cID)); ok {
			results.Add(uint32(value))
		}
	}
	resultsChan <- results
}

// ParOr is intended primarily to be a concatenation function to be used during bulk load operations.
// Care should be taken to make sure that columnIDs do not overlap (unless overlapping values are
// identical).
func (b *BSI) ParOr(parallelism int, bsis ...*BSI) {

	// Consolidate sets
	bits := len(b.bA)
	for i := 0; i < len(bsis); i++ {
		if len(bsis[i].bA) > bits {
			bits = bsis[i].BitCount()
		}
	}

	// Make sure we have enough bit slices
	for bits > b.BitCount() {
		newBm := roaring.NewBitmap()
		if b.runOptimized {
			newBm.RunOptimize()
		}
		b.bA = append(b.bA, newBm)
	}

	a := make([][]*roaring.Bitmap, bits)
	for i := range a {
		a[i] = make([]*roaring.Bitmap, 0)
		for _, x := range bsis {
			if len(x.bA) > i {
				a[i] = append(a[i], x.bA[i])
			} else {
				a[i] = []*roaring.Bitmap{roaring.NewBitmap()}
				if b.runOptimized {
					a[i][0].RunOptimize()
				}
			}
		}
	}

	// Consolidate existence bit maps
	ebms := make([]*roaring.Bitmap, len(bsis))
	for i := range ebms {
		ebms[i] = bsis[i].eBM
	}

	// First merge all the bit slices from all bsi maps that exist in target
	var wg sync.WaitGroup
	for i := 0; i < bits; i++ {
		wg.Add(1)
		go func(j int) {
			defer wg.Done()
			x := []*roaring.Bitmap{b.bA[j]}
			x = append(x, a[j]...)
			b.bA[j] = roaring.ParOr(parallelism, x...)
		}(i)
	}
	wg.Wait()

	// merge all the EBM maps
	x := []*roaring.Bitmap{b.eBM}
	x = append(x, ebms...)
	b.eBM = roaring.ParOr(parallelism, x...)
}

// UnmarshalBinary de-serialize a BSI.  The value at bitData[0] is the EBM.  Other indices are in least to most
// significance order starting at bitData[1] (bit position 0).
func (b *BSI) UnmarshalBinary(bitData [][]byte) error {

	for i := 1; i < len(bitData); i++ {
		if bitData == nil || len(bitData[i]) == 0 {
			continue
		}
		if b.BitCount() < i {
			newBm := roaring.NewBitmap()
			if b.runOptimized {
				newBm.RunOptimize()
			}
			b.bA = append(b.bA, newBm)
		}
		if err := b.bA[i-1].UnmarshalBinary(bitData[i]); err != nil {
			return err
		}
		if b.runOptimized {
			b.bA[i-1].RunOptimize()
		}

	}
	// First element of bitData is the EBM
	if bitData[0] == nil {
		b.eBM = roaring.NewBitmap()
		if b.runOptimized {
			b.eBM.RunOptimize()
		}
		return nil
	}
	if err := b.eBM.UnmarshalBinary(bitData[0]); err != nil {
		return err
	}
	if b.runOptimized {
		b.eBM.RunOptimize()
	}
	return nil
}

// MarshalBinary serializes a BSI
func (b *BSI) MarshalBinary() ([][]byte, error) {

	var err error
	data := make([][]byte, b.BitCount()+1)
	// Add extra element for EBM (BitCount() + 1)
	for i := 1; i < b.BitCount()+1; i++ {
		data[i], err = b.bA[i-1].MarshalBinary()
		if err != nil {
			return nil, err
		}
	}
	// Marshal EBM
	data[0], err = b.eBM.MarshalBinary()
	if err != nil {
		return nil, err
	}
	return data, nil
}

// BatchEqual returns a bitmap containing the column IDs where the values are contained within the list of values provided.
func (b *BSI) BatchEqual(parallelism int, values []int64) *roaring.Bitmap {

	valMap := make(map[int64]struct{}, len(values))
	for i := 0; i < len(values); i++ {
		valMap[values[i]] = struct{}{}
	}
	comp := &task{bsi: b, values: valMap}
	return parallelExecutor(parallelism, comp, batchEqual, b.eBM)
}

func batchEqual(e *task, batch []uint32, resultsChan chan *roaring.Bitmap,
	wg *sync.WaitGroup) {

	defer wg.Done()

	results := roaring.NewBitmap()
	if e.bsi.runOptimized {
		results.RunOptimize()
	}

	for i := 0; i < len(batch); i++ {
		cID := batch[i]
		if value, ok := e.bsi.GetValue(uint64(cID)); ok {
			if _, yes := e.values[int64(value)]; yes {
				results.Add(cID)
			}
		}
	}
	resultsChan <- results
}

// ClearBits cleared the bits that exist in the target if they are also in the found set.
func ClearBits(foundSet, target *roaring.Bitmap) {
	iter := foundSet.Iterator()
	for iter.HasNext() {
		cID := iter.Next()
		target.Remove(cID)
	}
}

// ClearValues removes the values found in foundSet
func (b *BSI) ClearValues(foundSet *roaring.Bitmap) {

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		ClearBits(foundSet, b.eBM)
	}()
	for i := 0; i < b.BitCount(); i++ {
		wg.Add(1)
		go func(j int) {
			defer wg.Done()
			ClearBits(foundSet, b.bA[j])
		}(i)
	}
	wg.Wait()
}

// NewBSIRetainSet - Construct a new BSI from a clone of existing BSI, retain only values contained in foundSet
func (b *BSI) NewBSIRetainSet(foundSet *roaring.Bitmap) *BSI {

	newBSI := NewBSI(b.MaxValue, b.MinValue)
	newBSI.bA = make([]*roaring.Bitmap, b.BitCount())
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		newBSI.eBM = b.eBM.Clone()
		newBSI.eBM.And(foundSet)
	}()
	for i := 0; i < b.BitCount(); i++ {
		wg.Add(1)
		go func(j int) {
			defer wg.Done()
			newBSI.bA[j] = b.bA[j].Clone()
			newBSI.bA[j].And(foundSet)
		}(i)
	}
	wg.Wait()
	return newBSI
}

// Clone performs a deep copy of BSI contents.
func (b *BSI) Clone() *BSI {
	return b.NewBSIRetainSet(b.eBM)
}

// Add - In-place sum the contents of another BSI with this BSI, column wise.
func (b *BSI) Add(other *BSI) {

	b.eBM.Or(other.eBM)
	for i := 0; i < len(other.bA); i++ {
		b.addDigit(other.bA[i], i)
	}
}

func (b *BSI) addDigit(foundSet *roaring.Bitmap, i int) {

	if i >= len(b.bA) {
		b.bA = append(b.bA, roaring.NewBitmap())
	}
	carry := roaring.And(b.bA[i], foundSet)
	b.bA[i].Xor(foundSet)
	if !carry.IsEmpty() {
		if i+1 >= len(b.bA) {
			b.bA = append(b.bA, roaring.NewBitmap())
		}
		b.addDigit(carry, i+1)
	}
}

// TransposeWithCounts is a matrix transpose function that returns a BSI that has a columnID system defined by the values
// contained within the input BSI.   Given that for BSIs, different columnIDs can have the same value.  TransposeWithCounts
// is useful for situations where there is a one-to-many relationship between the vectored integer sets.  The resulting BSI
// contains the number of times a particular value appeared in the input BSI as an integer count.
//
func (b *BSI) TransposeWithCounts(parallelism int, foundSet *roaring.Bitmap) *BSI {

	return parallelExecutorBSIResults(parallelism, b, transposeWithCounts, foundSet, true)
}

func transposeWithCounts(input *BSI, batch []uint32, resultsChan chan *BSI, wg *sync.WaitGroup) {

	defer wg.Done()

	results := NewDefaultBSI()
	if input.runOptimized {
		results.RunOptimize()
	}
	for _, cID := range batch {
		if value, ok := input.GetValue(uint64(cID)); ok {
			if val, ok2 := results.GetValue(uint64(value)); !ok2 {
				results.SetValue(uint64(value), 1)
			} else {
				val++
				results.SetValue(uint64(value), val)
			}
		}
	}
	resultsChan <- results
}

// Increment - In-place increment of values in a BSI.  Found set select columns for incrementing.
func (b *BSI) Increment(foundSet *roaring.Bitmap) {
	b.addDigit(foundSet, 0)
}

// IncrementAll - In-place increment of all values in a BSI.
func (b *BSI) IncrementAll() {
	b.Increment(b.GetExistenceBitmap())
}


text:
package org.deidentifier.arx.gui.view.impl.common.table;

import org.eclipse.nebula.widgets.nattable.data.IDataProvider;

/**
 *
 * @author Fabian Prasser
 *
 */
public interface CTDataProvider extends IDataProvider{

    /**
     *
     */
    public void clear();

    /**
     *
     *
     * @param data
     */
    public void setData(IDataProvider data);
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Linq;
using System.ComponentModel;
using System.Net;
using System.Runtime.CompilerServices;
using System.ServiceModel.Syndication;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace WPAppStudio.Entities.Base
{
    /// <summary>
    /// Representation of the results in a RSS search.
    /// </summary>
    public class RssSearchResult : BindableBase
    {
        private string _author;
        /// <summary>
        /// Gets/Sets the author of the RSS.
        /// </summary>
        public string Author
        {
            get
            {
                return _author;
            }
            set
            {
                SetProperty(ref _author, value);
            }
        }

        private DateTime _publishDate;
        /// <summary>
        /// Gets/Sets the publish date of the RSS.
        /// </summary>
        public DateTime PublishDate
        {
            get
            { return _publishDate; }
            set
            {
                SetProperty(ref _publishDate, value);
            }
        }

        private string _id;
        /// <summary>
        /// Gets/Sets the identifier of the RSS.
        /// </summary>
        public string Id
        {
            get { return _id; }
            set
            {
                SetProperty(ref _id, value);
            }
        }

        private string _title;
        /// <summary>
        /// Gets/Sets the title of the RSS.
        /// </summary>
        public string Title
        {
            get { return _title; }
            set
            {
                SetProperty(ref _title, value);
            }
        }

        private string _summary;
        /// <summary>
        /// Gets/Sets the summary of the RSS.
        /// </summary>
        public string Summary
        {
            get { return _summary; }
            set
            {
                SetProperty(ref _summary, value);
            }
        }

        private string _content;
        /// <summary>
        /// Gets/Sets the summary of the RSS.
        /// </summary>
        public string Content
        {
            get { return _content; }
            set
            {
                SetProperty(ref _content, value);
            }
        }

        private string _imageUrl;
        /// <summary>
        /// Gets/Sets the image URL of the RSS.
        /// </summary>
        public string ImageUrl
        {
            get { return _imageUrl; }
            set
            {
                SetProperty(ref _imageUrl, value);
            }
        }

        private string _extraImageUrl;
        /// <summary>
        /// Gets/Sets the extra image URL of the RSS.
        /// </summary>
        public string ExtraImageUrl
        {
            get { return _extraImageUrl; }
            set
            {
                SetProperty(ref _extraImageUrl, value);
            }
        }

        private string _mediaUrl;
        /// <summary>
        /// Gets/Sets the video URL of the RSS.
        /// </summary>
        public string MediaUrl
        {
            get { return _mediaUrl; }
            set
            {
                SetProperty(ref _mediaUrl, value);
            }
        }

        private string _feedUrl;
        /// <summary>
        /// Gets/Sets the RSS item feed URL.
        /// </summary>
        public string FeedUrl
        {
            get { return _feedUrl; }
            set
            {
                SetProperty(ref _feedUrl, value);
            }
        }

        /// <summary>
        /// Initializes a new instance of <see cref="RssSearchResult" /> class.
        /// </summary>
        public RssSearchResult() { }

		/// <summary>
        /// Initializes a new instance of <see cref="RssSearchResult" /> class.
        /// </summary>
        /// <param name="item">A valid SyndicationItem.</param>
        /// <param name="feedImage">Source feed image</param>
        public RssSearchResult(SyndicationItem item, string feedImage)
            : this()
        {
            Author = item.Authors.Count > 0 ? item.Authors[0].Name : string.Empty;

			if (string.IsNullOrEmpty(Author))
            {
                if (item.ElementExtensions.Count(p => p.OuterName == "creator") != 0)
                {
                    var creator = item.ElementExtensions.FirstOrDefault(p => p.OuterName == "creator");
                    if (creator != null)
                        Author = creator.GetObject<XElement>().Value;
                }
            }

            Id = item.Id;
            Title = item.Title != null ? HttpUtility.HtmlDecode(item.Title.Text) : string.Empty;
            Content = HttpUtility.HtmlDecode(RssUtil.SanitizeHtml(RssUtil.GetSummary(item)));
			Summary = RssUtil.SanitizeHtml(string.IsNullOrEmpty(Content) ? string.Empty : Content);
		    if (Summary.Length > 140)
		        Summary = HtmlUtil.TruncateHtml(Summary, 137, "...");
            PublishDate = item.PublishDate.DateTime;
            ImageUrl = RssUtil.GetImage(item, true);
			ExtraImageUrl = RssUtil.GetExtraImage(item);
            if (string.IsNullOrEmpty(ImageUrl) && !string.IsNullOrEmpty(ExtraImageUrl))
                ImageUrl = ExtraImageUrl;
		    if (string.IsNullOrEmpty(ImageUrl))
                ImageUrl = feedImage;

			if (String.IsNullOrEmpty(ImageUrl))
            {
                var encoded = item.ElementExtensions.FirstOrDefault(p => p.OuterName == "encoded");
                string encodedText = string.Empty;

                if (encoded != null)
                    encodedText = encoded.GetObject<XElement>().Value;

                var imageUrl =
                    Regex.Match(encodedText, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase).Groups[1].Value;
                ImageUrl = !string.IsNullOrEmpty(imageUrl) ? imageUrl : string.Empty;
            }

			MediaUrl = RssUtil.GetMediaVideoURL(item);
			FeedUrl = RssUtil.GetItemFeedLink(item);
        }

		public override bool Equals(object obj)
		{
			var cmp = obj as RssSearchResult;

			if(cmp == null) return false;

		    if (Title != null)
		        return Title.Equals(cmp.Title);
		    if (Id != null)
		        return Id.Equals(cmp.Id);
		    return this==obj;
		}

		public override int GetHashCode()
		{
            if (Title != null)
                return Title.GetHashCode();
            if (Id != null)
                return Id.GetHashCode();
		    return base.GetHashCode();
		}
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('globalsettings', '0006_globalsettings_javascript_codes'),
    ]

    operations = [
        migrations.AddField(
            model_name='globalsettings',
            name='javascript_codes_ignore_landing_pages',
            field=models.TextField(null=True, help_text="Same as above, except that the codes won't be put on landing pages (without HEADER and FOOTER)", blank=True),
        ),
        migrations.AlterField(
            model_name='globalsettings',
            name='javascript_codes',
            field=models.TextField(null=True, help_text='Embed JavaScript codes (privy, smartlook, etc) that will be available in EVERY page.', blank=True),
        ),
    ]


text:
package org.apache.flink.formats.parquet.row;

import org.apache.flink.table.dataformat.BaseRow;
import org.apache.flink.table.dataformat.Decimal;
import org.apache.flink.table.dataformat.SqlTimestamp;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.LocalZonedTimestampType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.logical.TimestampType;
import org.apache.flink.util.Preconditions;

import org.apache.parquet.io.api.Binary;
import org.apache.parquet.io.api.RecordConsumer;
import org.apache.parquet.schema.GroupType;
import org.apache.parquet.schema.Type;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.sql.Timestamp;
import java.util.Arrays;

import static org.apache.flink.formats.parquet.utils.ParquetSchemaConverter.computeMinBytesForDecimalPrecision;
import static org.apache.flink.formats.parquet.vector.reader.TimestampColumnReader.JULIAN_EPOCH_OFFSET_DAYS;
import static org.apache.flink.formats.parquet.vector.reader.TimestampColumnReader.MILLIS_IN_DAY;
import static org.apache.flink.formats.parquet.vector.reader.TimestampColumnReader.NANOS_PER_MILLISECOND;
import static org.apache.flink.formats.parquet.vector.reader.TimestampColumnReader.NANOS_PER_SECOND;

/**
 * Writes a record to the Parquet API with the expected schema in order to be written to a file.
 */
public class ParquetRowDataWriter {

	private final RecordConsumer recordConsumer;
	private final boolean utcTimestamp;

	private final FieldWriter[] filedWriters;
	private final String[] fieldNames;

	public ParquetRowDataWriter(
			RecordConsumer recordConsumer,
			RowType rowType,
			GroupType schema,
			boolean utcTimestamp) {
		this.recordConsumer = recordConsumer;
		this.utcTimestamp = utcTimestamp;

		this.filedWriters = new FieldWriter[rowType.getFieldCount()];
		this.fieldNames = rowType.getFieldNames().toArray(new String[0]);
		for (int i = 0; i < rowType.getFieldCount(); i++) {
			this.filedWriters[i] = createWriter(rowType.getTypeAt(i), schema.getType(i));
		}
	}

	/**
	 * It writes a record to Parquet.
	 *
	 * @param record Contains the record that is going to be written.
	 */
	public void write(final BaseRow record) {
		recordConsumer.startMessage();
		for (int i = 0; i < filedWriters.length; i++) {
			if (!record.isNullAt(i)) {
				String fieldName = fieldNames[i];
				FieldWriter writer = filedWriters[i];

				recordConsumer.startField(fieldName, i);
				writer.write(record, i);
				recordConsumer.endField(fieldName, i);
			}
		}
		recordConsumer.endMessage();
	}

	private FieldWriter createWriter(LogicalType t, Type type) {
		if (type.isPrimitive()) {
			switch (t.getTypeRoot()) {
				case CHAR:
				case VARCHAR:
					return new StringWriter();
				case BOOLEAN:
					return new BooleanWriter();
				case BINARY:
				case VARBINARY:
					return new BinaryWriter();
				case DECIMAL:
					DecimalType decimalType = (DecimalType) t;
					return createDecimalWriter(decimalType.getPrecision(), decimalType.getScale());
				case TINYINT:
					return new ByteWriter();
				case SMALLINT:
					return new ShortWriter();
				case DATE:
				case TIME_WITHOUT_TIME_ZONE:
				case INTEGER:
					return new IntWriter();
				case BIGINT:
					return new LongWriter();
				case FLOAT:
					return new FloatWriter();
				case DOUBLE:
					return new DoubleWriter();
				case TIMESTAMP_WITHOUT_TIME_ZONE:
					TimestampType timestampType = (TimestampType) t;
					return new TimestampWriter(timestampType.getPrecision());
				case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
					LocalZonedTimestampType localZonedTimestampType = (LocalZonedTimestampType) t;
					return new TimestampWriter(localZonedTimestampType.getPrecision());
				default:
					throw new UnsupportedOperationException("Unsupported type: " + type);
			}
		} else {
			throw new IllegalArgumentException("Unsupported  data type: " + t);
		}
	}

	private interface FieldWriter {

		void write(BaseRow row, int ordinal);
	}

	private class BooleanWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addBoolean(row.getBoolean(ordinal));
		}
	}

	private class ByteWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addInteger(row.getByte(ordinal));
		}
	}

	private class ShortWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addInteger(row.getShort(ordinal));
		}
	}

	private class LongWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addLong(row.getLong(ordinal));
		}
	}

	private class FloatWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addFloat(row.getFloat(ordinal));
		}
	}

	private class DoubleWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addDouble(row.getDouble(ordinal));
		}
	}

	private class StringWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addBinary(
				Binary.fromReusedByteArray(row.getString(ordinal).getBytes()));
		}
	}

	private class BinaryWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addBinary(
					Binary.fromReusedByteArray(row.getBinary(ordinal)));
		}
	}

	private class IntWriter implements FieldWriter {

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addInteger(row.getInt(ordinal));
		}
	}

	/**
	 * We only support INT96 bytes now, julianDay(4) + nanosOfDay(8).
	 * See https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#timestamp
	 * TIMESTAMP_MILLIS and TIMESTAMP_MICROS are the deprecated ConvertedType.
	 */
	private class TimestampWriter implements FieldWriter {

		private final int precision;

		private TimestampWriter(int precision) {
			this.precision = precision;
		}

		@Override
		public void write(BaseRow row, int ordinal) {
			recordConsumer.addBinary(timestampToInt96(row.getTimestamp(ordinal, precision)));
		}
	}

	private Binary timestampToInt96(SqlTimestamp sqlTimestamp) {
		int julianDay;
		long nanosOfDay;
		if (utcTimestamp) {
			long mills = sqlTimestamp.getMillisecond();
			julianDay = (int) ((mills / MILLIS_IN_DAY) + JULIAN_EPOCH_OFFSET_DAYS);
			nanosOfDay = (mills % MILLIS_IN_DAY) * NANOS_PER_MILLISECOND + sqlTimestamp.getNanoOfMillisecond();
		} else {
			Timestamp timestamp = sqlTimestamp.toTimestamp();
			long mills = timestamp.getTime();
			julianDay = (int) ((mills / MILLIS_IN_DAY) + JULIAN_EPOCH_OFFSET_DAYS);
			nanosOfDay = ((mills % MILLIS_IN_DAY) / 1000) * NANOS_PER_SECOND + timestamp.getNanos();
		}

		ByteBuffer buf = ByteBuffer.allocate(12);
		buf.order(ByteOrder.LITTLE_ENDIAN);
		buf.putLong(nanosOfDay);
		buf.putInt(julianDay);
		buf.flip();
		return Binary.fromConstantByteBuffer(buf);
	}

	private FieldWriter createDecimalWriter(int precision, int scale) {
		Preconditions.checkArgument(
			precision <= DecimalType.MAX_PRECISION,
			"Decimal precision %s exceeds max precision %s",
			precision, DecimalType.MAX_PRECISION);

		/*
		 * This is optimizer for UnscaledBytesWriter.
		 */
		class LongUnscaledBytesWriter implements FieldWriter {
			private final int numBytes;
			private final int initShift;
			private final byte[] decimalBuffer;

			private LongUnscaledBytesWriter() {
				this.numBytes = computeMinBytesForDecimalPrecision(precision);
				this.initShift = 8 * (numBytes - 1);
				this.decimalBuffer = new byte[numBytes];
			}

			@Override
			public void write(BaseRow row, int ordinal) {
				long unscaledLong = row.getDecimal(ordinal, precision, scale).toUnscaledLong();
				int i = 0;
				int shift = initShift;
				while (i < numBytes) {
					decimalBuffer[i] = (byte) (unscaledLong >> shift);
					i += 1;
					shift -= 8;
				}

				recordConsumer.addBinary(Binary.fromReusedByteArray(decimalBuffer, 0, numBytes));
			}
		}

		class UnscaledBytesWriter implements FieldWriter {
			private final int numBytes;
			private final byte[] decimalBuffer;

			private UnscaledBytesWriter() {
				this.numBytes = computeMinBytesForDecimalPrecision(precision);
				this.decimalBuffer = new byte[numBytes];
			}

			@Override
			public void write(BaseRow row, int ordinal) {
				byte[] bytes = row.getDecimal(ordinal, precision, scale).toUnscaledBytes();
				byte[] writtenBytes;
				if (bytes.length == numBytes) {
					// Avoid copy.
					writtenBytes = bytes;
				} else {
					byte signByte = bytes[0] < 0 ? (byte) -1 : (byte) 0;
					Arrays.fill(decimalBuffer, 0, numBytes - bytes.length, signByte);
					System.arraycopy(bytes, 0, decimalBuffer, numBytes - bytes.length, bytes.length);
					writtenBytes = decimalBuffer;
				}
				recordConsumer.addBinary(Binary.fromReusedByteArray(writtenBytes, 0, numBytes));
			}
		}

		// 1 <= precision <= 18, writes as FIXED_LEN_BYTE_ARRAY
		// optimizer for UnscaledBytesWriter
		if (Decimal.is32BitDecimal(precision) || Decimal.is64BitDecimal(precision)) {
			return new LongUnscaledBytesWriter();
		}

		// 19 <= precision <= 38, writes as FIXED_LEN_BYTE_ARRAY
		return new UnscaledBytesWriter();
	}
}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<title>Simple shapes</title>

		<canvas id="canvas" width="400" height="60"></canvas>

<button id="toDataURL">toDataURL</button>


text:
A research project to learn, index, and display all lexical information.

## Dependencies

You have to clone the following repositories as a pre-requisite:

```
 $ git clone git@github.com:stanfordnlp/phrasal.git
 $ git clone git@github.com:stanfordnlp/CoreNLP.git
 $ git clone git@github.com:oscii-lab/Word2VecJava.git
```

## Building

* Run `gradle test` to build and test `lex`.

## IDEA

* Run `gradle idea` to create project files.

## Getting started

The lexicon uses [PanLex](http://panlex.org/) data as a seed. To run the
system,
* [download](http://dev.panlex.org/db/) a `JSON`-formatted archive of PanLex data.
* To compile a lexicon as a `lex.json` file,  execute
  `gradle :run -Pargs="-p /path/to/panlex/directory -w /path/to/lex.json"`
* To serve the lexicon and a corpus over `http`, execute
  `gradle :run -Pargs="-r /path/to/lex.json -c /path/to/corpus/prefix -a"`

## API

The lexicon is currently served from: `http://104.197.10.176/translate/lexicon`

The structure of a request object is defined in `org.oscii.api.Protocol.Request`.

Responses are served in two ways:
* Over http in response to a JSON request body
* Over http in response to request parameters defining the fields of a request

For example, the following request returns translations, definitions, and
extensions for the word "drive".

    http://104.197.10.176/translate/lexicon?query=drive&source=en&target=es&translate=true&extend=true&define=true


text:
import unittest
from airflow.utils.weight_rule import WeightRule

class TestWeightRule(unittest.TestCase):

    def test_valid_weight_rules(self):
        self.assertTrue(WeightRule.is_valid(WeightRule.DOWNSTREAM))
        self.assertTrue(WeightRule.is_valid(WeightRule.UPSTREAM))
        self.assertTrue(WeightRule.is_valid(WeightRule.ABSOLUTE))
        self.assertEqual(len(WeightRule.all_weight_rules()), 3)


text:
[![Total Downloads](https://poser.pugx.org/jayzeng/virustotalapi/downloads.png)](https://packagist.org/packages/jayzeng/virustotalapi)
[![Latest Stable Version](https://poser.pugx.org/jayzeng/virustotalapi/v/stable.png)](https://packagist.org/packages/jayzeng/virustotalapi)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/jayzeng/virustotal_apiwrapper/badges/quality-score.png?s=46248d98379ddfeb153958114f71d5ea80a47cf9)](https://scrutinizer-ci.com/g/jayzeng/virustotal_apiwrapper/)
[![Build Status](https://travis-ci.org/jayzeng/virustotal_apiwrapper.png)](https://travis-ci.org/jayzeng/virustotal_apiwrapper)

Project website: (http://jayzeng.github.io/virustotal_apiwrapper/)

This is a PHP SDK to interact with Virus Total Public API v2.0, please see https://www.virustotal.com/en/documentation/public-api for details

## I want to show you my appreciation!
If you find the project useful and would love show your appreciation, awesome!

[![Support via Gittip](https://rawgithub.com/twolfson/gittip-badge/0.2.0/dist/gittip.png)](https://www.gittip.com/jayzeng/)

##Usage:
- You will need composer (http://getcomposer.org/)
- composer search virustotalapi or visit the package info on packagist (https://packagist.org/packages/jayzeng/virustotalapi)

Include the following in your composer.json:
```json
{
  "require": {
    "jayzeng/virustotalapi": "dev-master"
  }
}
```

```
composer update -v -o
```

## Quick start:
```
<?php
require_once 'Vendors/autoload.php';

$apiKey = 'your_api_key';

$file = new VirusTotal\File($apiKey);
$resp = $file->scan('foo.txt');

var_dump($resp);
?>
```

Sample output
```
[jayzeng] ~/Projects/virustotal_apiwrapper/Example] (master)>  php file.php |more
array(8) {
  ["scan_id"]=>
  string(75) "1afc739de16163a80380326ce05e1e69edfc99b7a931329ab127b5099377f076-1370244536"
  ["sha1"]=>
  string(40) "da9ed61e1bfa981c545acad4136e8a05f0602e45"
  ["resource"]=>
  string(64) "1afc739de16163a80380326ce05e1e69edfc99b7a931329ab127b5099377f076"
  ["response_code"]=>
  int(1)
  ["sha256"]=>
  string(64) "1afc739de16163a80380326ce05e1e69edfc99b7a931329ab127b5099377f076"
  ["permalink"]=>
  string(117) "https://www.virustotal.com/file/1afc739de16163a80380326ce05e1e69edfc99b7a931329ab127b5099377f076/analysis/1370244536/"
  ["md5"]=>
  string(32) "b2f301b40a5fb752b19ae0e5c7f679b4"
  ["verbose_msg"]=>
  string(64) "Scan request successfully queued, come back later for the report"
}
```

##Example:
Still feeling confusing? See Examples/ (https://github.com/jayzeng/virustotal_apiwrapper/tree/master/Examples)

I also hack up a demo application, source code is available at https://github.com/jayzeng/virustotal_demoapp

##How to run tests?
```bash
phpunit --configuration Tests/Conf/phpunit.xml Tests
```

Or
```
Vendors/bin/phpunit --configuration Tests/Conf/phpunit.xml Tests
```

##Issues & Development
- Source hosted [GitHub](https://github.com/jayzeng/virustotal_apiwrapper)
- Report issues, questions, feature requests on [GitHub Issues](https://github.com/jayzeng/virustotal_apiwrapper/issues)

##How to release new version?
- RELEASE_VERSION - version number
- RELEASE_MESSAGE - release message

```bash
make release RELEASE_VERSION="0.1" RELEASE_MESSAGE="v0.1 is released"
```

##How to contribute?
Awesome! Please follow these steps:
- Create an issue [GitHub Issues](https://github.com/jayzeng/virustotal_apiwrapper/issues) to explain what you will do
- Fork the repository into your GitHub account
- Create a new branch with a good name (e.g: feature/issue1_add_urlendpoint)
- Implement/Refactor tests
- Check in code
- Pass tests & travis build

##Author:
[Jay Zeng](https://github.com/jayzeng/), e-mail: [jayzeng@jay-zeng.com](mailto:jayzeng@jay-zeng.com)


text:
require 'spec_helper'

describe Sprint do
  before(:each) do
    @admin = User.create!(valid_user_attributes)
    @project = Project.create!(valid_project_attributes)
  end

  it "should create first sprint for the project" do
    sprint = Sprint.create!(project: @project)
    sprint.should_not be_new_record
    sprint.project.id.should eql(@project.id)
    @project.sprints.should include(sprint)
  end

  it "should require project to be associated with" do
    Sprint.create.should be_new_record
  end

  it "should initiate first sprint name to 'Sprint 1'" do
    Sprint.create(project: @project).name.should eql("Sprint 1")
  end

  it "should initiate sprint's start and end dates" do
    sprint = Sprint.create(project: @project)
    sprint.start_date.should < sprint.end_date
  end

  it "should create second sprint for the project" do
    Sprint.create(project: @project)
    s = Sprint.create(project: @project)
    s.should_not be_new_record
  end

  it "should initiate second sprint start date to 1 day after last sprint, and end date in 2 weeks from then" do
    sprint1 = Sprint.create(project: @project)
    sprint2 = Sprint.create(project: @project)
    sprint2.start_date.should > sprint1.end_date
    sprint2.end_date.should > sprint2.start_date
    sprint2.start_date.should > sprint1.end_date
  end

  it "should set default sprint dates to mondays and fridays" do
    sprint1= Sprint.create(project: @project)
    sprint2 = Sprint.create(project: @project)
    sprint1.start_date.should be_monday
    sprint1.end_date.should be_friday
    sprint2.start_date.should be_monday
    sprint2.end_date.should be_friday
  end

  it "should prevent nested sprint dates" do
    Sprint.create(project: @project, start_date: Time.zone.now, end_date: 11.days.from_now)
    Sprint.create(project: @project, start_date: 2.days.from_now, end_date: 13.days.from_now).should be_new_record
    Sprint.create(project: @project, start_date: Time.zone.now, end_date: 5.days.from_now).should be_new_record
    Sprint.create(project: @project, start_date: Time.zone.now, end_date: 11.days.from_now).should be_new_record
    Sprint.create(project: @project, start_date: 2.days.from_now, end_date: 11.days.from_now).should be_new_record
    Sprint.create(project: @project, start_date: Time.zone.now, end_date: 13.days.from_now).should be_new_record
    Sprint.create(project: @project, start_date: 2.days.ago, end_date: 5.days.from_now).should be_new_record
    Sprint.create(project: @project, start_date: 2.days.ago, end_date: 20.days.from_now).should be_new_record
    Sprint.create(project: @project, start_date: 12.days.from_now, end_date: 22.days.from_now).should_not be_new_record
  end

  it "should prevent start_date >= end_date" do
    Sprint.create(project: @project, start_date: 1.day.from_now, end_date: 1.day.from_now).should be_new_record
    Sprint.create(project: @project, start_date: 1.day.from_now, end_date: 1.day.ago).should be_new_record
  end

  it "should have unique name" do
    Sprint.create(project: @project)
    Sprint.create(project: @project, name: "Sprint 1").should_not be_valid
  end

  it "should be possible to assing formatted date" do
    s = Sprint.create(project: @project, formatted_start_date: "21/02/2010", formatted_end_date: "28/02/2010")
    s.start_date.should eql(Time.parse("21/02/2010"))
    s.end_date.to_i.should eql(Time.parse("28/02/2010").end_of_day.to_i)
    s.formatted_start_date.should eql("21/02/2010")
    s.formatted_end_date.should eql("28/02/2010")
  end
end


text:
package com.godmonth.status.test.sample.db2;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionOperations;
import org.springframework.transaction.support.TransactionTemplate;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})

@EnableJpaRepositories(entityManagerFactoryRef = "e2", transactionManagerRef = "tm2", basePackages = "com.godmonth.status.test.sample.repo")
//@EntityScan("com.godmonth.status.test.sample.domain")
public class RepoConfig2 {
    @Bean("d2")
    @ConfigurationProperties(prefix = "spring.db2")
    public DataSource userDataSource() {
        return DataSourceBuilder.create().build();
    }

    // userEntityManager bean
    @Bean("e2")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            @Qualifier("d2") DataSource userDataSource, JpaProperties jpaProperties) {
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder(vendorAdapter, jpaProperties.getProperties(), null);
        HibernateProperties hibernateProperties = new HibernateProperties();
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
        return builder.dataSource(userDataSource).properties(properties).packages("com.godmonth.status.test.sample.domain").build();
    }

    @Bean("tm2")
    public PlatformTransactionManager userTransactionManager(@Qualifier("e2") EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }

    @Bean("tt2")
    public TransactionOperations transactionTemplate(@Qualifier("tm2") PlatformTransactionManager platformTransactionManager) {
        return new TransactionTemplate(platformTransactionManager);
    }

}


text:
websafe/php-lib-hrd-pricelist
================================================================================

Draft library of PHP classes for handling HRD pricelists.

Installation
--------------------------------------------------------------------------------

~~~~ bash
git clone https://github.com/websafe/php-lib-hrd-pricelist.git
cd php-lib-hrd-pricelist
./install.sh
~~~~

Problems
--------------------------------------------------------------------------------

###  Class 'NumberFormatter' not found...

Install `libicu-devel` and the `intl` extension for PHP:

~~~~ bash
yum install libicu-devel
pecl install intl
~~~~

in `php.ini`:

~~~~ plain
extension=intl.so
~~~~


text:
<?php

declare(strict_types=1);

namespace Jose\Bundle\JoseFramework\Event;

use Symfony\Contracts\EventDispatcher\Event;
use Throwable;

final class JWSBuiltFailureEvent extends Event
{
    public function __construct(
        protected ?string $payload,
        protected array $signatures,
        protected bool $isPayloadDetached,
        protected ?bool $isPayloadEncoded,
        private readonly Throwable $throwable
    ) {
    }

    public function getPayload(): ?string
    {
        return $this->payload;
    }

    public function isPayloadDetached(): bool
    {
        return $this->isPayloadDetached;
    }

    public function getSignatures(): array
    {
        return $this->signatures;
    }

    public function getisPayloadEncoded(): ?bool
    {
        return $this->isPayloadEncoded;
    }

    public function getThrowable(): Throwable
    {
        return $this->throwable;
    }
}


text:
warn "Jdbc-H2 is only for use with JRuby" if (JRUBY_VERSION.nil? rescue true)
require 'jdbc/h2/version'

module Jdbc
  module H2

    def self.driver_jar
      "h2-#{DRIVER_VERSION}.jar"
    end

    def self.load_driver(method = :load)
      send method, driver_jar
    end

    def self.driver_name
      'org.h2.Driver'
    end

    if defined?(JRUBY_VERSION) && # enable backwards-compat behavior :
      ( Java::JavaLang::Boolean.get_boolean("jdbc.driver.autoload") ||
        Java::JavaLang::Boolean.get_boolean("jdbc.h2.autoload") )
      warn "autoloading JDBC driver on require 'jdbc/h2'" if $VERBOSE
      load_driver :require
    end
  end
end


text:
--
-- Copyright 2010-2017 Boxfuse GmbH
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--         http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--

/*
Test script to simulate the addition of Microsoft database tools assets.
 */
CREATE TABLE db_tools_test_table (
  id NVARCHAR(25) NOT NULL PRIMARY KEY
)
GO

EXEC sp_addextendedproperty 'microsoft_database_tools_support', 1, 'SCHEMA', 'dbo', 'TABLE', 'db_tools_test_table', NULL, NULL
GO

CREATE FUNCTION db_tools_test_function()
RETURNS NVARCHAR(25)
BEGIN
	RETURN 'test'
END
GO

EXEC sp_addextendedproperty 'microsoft_database_tools_support', 1, 'SCHEMA', 'dbo', 'FUNCTION', 'db_tools_test_function', NULL, NULL
GO

CREATE PROCEDURE db_tools_test_procedure AS SELECT * FROM dual
GO

EXEC sp_addextendedproperty 'microsoft_database_tools_support', 1, 'SCHEMA', 'dbo', 'PROCEDURE', 'db_tools_test_procedure', NULL, NULL
GO

CREATE VIEW db_tools_test_view AS SELECT * FROM db_tools_test_table
GO

EXEC sp_addextendedproperty 'microsoft_database_tools_support', 1, 'SCHEMA', 'dbo', 'VIEW', 'db_tools_test_view', NULL, NULL
GO


text:
/* Basic code - don't modify */

 .droppy { display: block; margin: 0; padding: 0; position: relative; }
  .droppy li { display: block; list-style: none; margin: 0; padding: 0; float: left; position: relative; }
  .droppy a { display: block; text-decoration: none; background-color: #E0EAEF; color: #fff;}
  .droppy ul { display: none; position: absolute; left: 0; margin: 0; padding: 0; }
  * html .droppy ul { line-height: 0; } /* IE6 "fix" */
  	.droppy ul a { zoom: 1; } /* IE6/7 fix */
    .droppy ul li { float: none; }
    .droppy ul ul { top: 0; }

/* Essentials - configure this */

.droppy ul { width: 200px; border-left: #7694A9 1px solid; border-right: #7694A9 1px solid; border-bottom: #7694A9 1px solid;}
.droppy ul ul { left: 201px; }

/* Everything else is theming */

.droppy { background-color: #ECF0F2; height: 24px; margin-bottom: 6px; color: #fff; border:1px solid #ACBDCD;}
.droppy *:hover { background-color: none; }
.droppy a { border-right: 1px solid #ACBDCD; color: #002E4F; font-size: 12px; padding: 6px 24px 6px 24px; line-height: 1; }
  .droppy li.hover a { background-color: #ECF0F2; }
  .droppy ul { top: 25px; }
    .droppy ul li a { background-color: #ECF0F2; }
      .droppy ul a.hover { background-color: #E5E8ED; }
   .droppy ul a { border-bottom: 1px solid white; border-right: none; opacity: 1; filter: alpha(opacity=90); }
/* .droppy ul a { border-bottom: none; } - I also needed this for IE6/7 */


text:
clang-format -i src/civetweb.c
clang-format -i src/main.c
clang-format -i src/CivetServer.cpp
clang-format -i src/civetweb_private_lua.h
clang-format -i src/md5.inl
clang-format -i src/sha1.inl
clang-format -i src/mod_lua.inl
clang-format -i src/mod_duktape.inl
clang-format -i src/timer.inl
clang-format -i src/handle_form.inl

clang-format -i src/third_party/civetweb_lua.h

clang-format -i include/civetweb.h
clang-format -i include/CivetServer.h

clang-format -i test/public_func.h
clang-format -i test/public_func.c
clang-format -i test/public_server.h
clang-format -i test/public_server.c
clang-format -i test/private.h
clang-format -i test/private.c
clang-format -i test/private_exe.h
clang-format -i test/private_exe.c
clang-format -i test/shared.h
clang-format -i test/shared.c
clang-format -i test/timertest.h
clang-format -i test/timertest.c
clang-format -i test/civetweb_check.h
clang-format -i test/main.c

clang-format -i examples/embedded_c/embedded_c.c


text:
package com.google.cloud.bigtable.hbase2_x;

import com.google.api.core.InternalApi;
import com.google.cloud.bigtable.hbase.util.FutureUtil;
import com.google.cloud.bigtable.hbase.util.ModifyTableBuilder;
import com.google.cloud.bigtable.hbase2_x.adapters.admin.TableAdapter2x;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Futures;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.InvocationHandlerAdapter;
import net.bytebuddy.implementation.MethodCall;
import net.bytebuddy.matcher.ElementMatchers;
import org.apache.hadoop.hbase.ClusterMetrics;
import org.apache.hadoop.hbase.ClusterMetrics.Option;
import org.apache.hadoop.hbase.ClusterStatus;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.AbstractBigtableAdmin;
import org.apache.hadoop.hbase.client.AbstractBigtableConnection;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.SnapshotDescription;
import org.apache.hadoop.hbase.client.SnapshotType;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * HBase 2.x specific implementation of {@link AbstractBigtableAdmin}.
 *
 *
For internal use only - public for technical reasons.
 */
@InternalApi("For internal usage only")
public abstract class BigtableAdmin extends AbstractBigtableAdmin {

  private final BigtableAsyncAdmin asyncAdmin;

  public BigtableAdmin(AbstractBigtableConnection connection) throws IOException {
    super(connection);
    asyncAdmin = BigtableAsyncAdmin.createInstance(connection);
  }

  /** {@inheritDoc} */
  @Override
  public void createTable(TableDescriptor desc) throws IOException {
    createTable(desc, null);
  }

  /** {@inheritDoc} */
  @Override
  public void createTable(TableDescriptor desc, byte[] startKey, byte[] endKey, int numRegions)
      throws IOException {
    createTable(desc, createSplitKeys(startKey, endKey, numRegions));
  }

  /** {@inheritDoc} */
  @Override
  public void createTable(TableDescriptor desc, byte[][] splitKeys) throws IOException {
    createTable(desc.getTableName(), TableAdapter2x.adapt(desc, splitKeys));
  }

  @Override
  public Future<Void> createTableAsync(TableDescriptor tableDescriptor) throws IOException {
    return asyncAdmin.createTable(tableDescriptor);
  }

  /** {@inheritDoc} */
  @Override
  public Future<Void> createTableAsync(TableDescriptor desc, byte[][] splitKeys)
      throws IOException {
    return asyncAdmin.createTable(desc, splitKeys);
  }

  /** {@inheritDoc} */
  @Override
  public List<SnapshotDescription> listSnapshots(String regex) throws IOException {
    return listSnapshots(Pattern.compile(regex));
  }

  /** {@inheritDoc} */
  @Override
  public List<SnapshotDescription> listSnapshots(Pattern pattern) throws IOException {
    if (pattern == null || pattern.matcher("").matches()) {
      return ImmutableList.of();
    }

    List<SnapshotDescription> response = new ArrayList<>();
    for (SnapshotDescription description : listSnapshots()) {
      if (pattern.matcher(description.getName()).matches()) {
        response.add(description);
      }
    }
    return response;
  }

  @Override
  public List<SnapshotDescription> listSnapshots() throws IOException {
    List<String> backups =
        Futures.getChecked(
            adminClientWrapper.listBackupsAsync(getBackupClusterId()), IOException.class);
    List<SnapshotDescription> response = new ArrayList<>();
    for (String backup : backups) {
      response.add(new SnapshotDescription(backup));
    }
    return response;
  }

  /**
   * {@inheritDoc}
   *
   *
Calling {@link #addColumn(TableName, ColumnFamilyDescriptor)} was causing stackoverflow.
   * Copying the same code here. //TODO - need to find a better way
   */
  @Override
  public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc)
      throws IOException {
    modifyColumns(
        tableName,
        columnFamilyDesc.getNameAsString(),
        "add",
        ModifyTableBuilder.newBuilder(tableName)
            .add(TableAdapter2x.toHColumnDescriptor(columnFamilyDesc)));
  }

  /**
   * {@inheritDoc}
   *
   *
Calling {@link #addColumn(TableName, ColumnFamilyDescriptor)} was causing stackoverflow.
   * Copying the same code here. //TODO - need to find a better way
   */
  @Override
  public void modifyColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc)
      throws IOException {
    modifyColumns(
        tableName,
        columnFamilyDesc.getNameAsString(),
        "modify",
        ModifyTableBuilder.newBuilder(tableName)
            .modify(TableAdapter2x.toHColumnDescriptor(columnFamilyDesc)));
  }

  /** {@inheritDoc} */
  @Override
  public Future<Void> deleteNamespaceAsync(String name) throws IOException {
    deleteNamespace(name);
    // TODO Consider better options after adding support for async hbase2
    return CompletableFuture.runAsync(() -> {});
  }

  /** {@inheritDoc} */
  @Override
  public Future<Void> disableTableAsync(TableName tableName) throws IOException {
    return asyncAdmin.disableTable(tableName);
  }

  /** {@inheritDoc} */
  @Override
  public Future<Void> enableTableAsync(TableName tableName) throws IOException {
    return asyncAdmin.enableTable(tableName);
  }

  /** {@inheritDoc} */
  @Override
  public TableDescriptor getDescriptor(TableName tableName) throws IOException {
    return getTableDescriptor(tableName);
  }

  /** {@inheritDoc} */
  @Override
  public void snapshot(SnapshotDescription snapshot)
      throws IOException, SnapshotCreationException, IllegalArgumentException {
    Objects.requireNonNull(snapshot);
    snapshot(snapshot.getName(), snapshot.getTableName());
  }

  /** {@inheritDoc} */
  @Override
  public void snapshot(String snapshotId, TableName tableName, SnapshotType ignored)
      throws IOException, SnapshotCreationException, IllegalArgumentException {
    snapshot(snapshotId, tableName);
  }

  @Override
  public Future<Void> addColumnFamilyAsync(
      TableName tableName, ColumnFamilyDescriptor columnFamily) {
    return asyncAdmin.addColumnFamily(tableName, columnFamily);
  }

  @Override
  public void deleteColumnFamily(TableName tableName, byte[] columnName) throws IOException {
    deleteColumn(tableName, columnName);
  }

  @Override
  public Future<Void> deleteColumnFamilyAsync(TableName tableName, byte[] columnName) {
    return asyncAdmin.deleteColumnFamily(tableName, columnName);
  }

  protected CompletableFuture<Void> deleteTableAsyncInternal(TableName tableName) {
    return ApiFutureUtils.toCompletableFuture(
        adminClientWrapper.deleteTableAsync(tableName.getNameAsString()));
  }

  @Override
  public Future<Void> deleteTableAsync(TableName tableName) throws IOException {
    return deleteTableAsyncInternal(tableName);
  }

  @Override
  public List<TableDescriptor> listTableDescriptors() throws IOException {
    return Arrays.asList(listTables());
  }

  @Override
  public List<TableDescriptor> listTableDescriptors(Pattern pattern) throws IOException {
    return Arrays.asList(listTables(pattern));
  }

  @Override
  public List<TableDescriptor> listTableDescriptors(List<TableName> tableNames) throws IOException {
    List<TableDescriptor> response = new ArrayList<TableDescriptor>();
    for (TableName tableName : tableNames) {
      TableDescriptor desc = getTableDescriptor(tableName);
      if (desc != null) {
        response.add(desc);
      }
    }
    return response;
  }

  @Override
  public List<TableDescriptor> listTableDescriptors(Pattern pattern, boolean includeSysTables)
      throws IOException {
    return Arrays.asList(listTables(pattern, includeSysTables));
  }

  @Override
  public List<TableDescriptor> listTableDescriptorsByNamespace(byte[] namespace)
      throws IOException {
    final String namespaceStr = Bytes.toString(namespace);
    return Arrays.asList(listTableDescriptorsByNamespace(namespaceStr));
  }

  @Override
  public Future<Void> modifyColumnFamilyAsync(
      TableName tableName, ColumnFamilyDescriptor columnFamily) throws IOException {
    return asyncAdmin.modifyColumnFamily(tableName, columnFamily);
  }

  @Override
  public void modifyTable(TableDescriptor tableDescriptor) throws IOException {
    modifyTable(tableDescriptor.getTableName(), tableDescriptor);
  }

  @Override
  public void modifyTable(TableName tableName, TableDescriptor tableDescriptor) throws IOException {
    FutureUtil.unwrap(modifyTableAsync(tableName, tableDescriptor));
  }

  @Override
  public Future<Void> modifyTableAsync(TableDescriptor tableDescriptor) throws IOException {
    return modifyTableAsync(tableDescriptor.getTableName(), tableDescriptor);
  }

  @Override
  public Future<Void> modifyTableAsync(TableName tableName, TableDescriptor newDescriptor) {
    return asyncAdmin
        .getDescriptor(tableName)
        .thenApply(
            descriptor ->
                ModifyTableBuilder.buildModifications(
                    new HTableDescriptor(newDescriptor), new HTableDescriptor(descriptor)))
        .thenApply(
            modifications -> {
              try {
                return modifyColumns(tableName, null, "modifyTableAsync", modifications);
              } catch (IOException e) {
                throw new CompletionException(e);
              }
            });
  }

  /* (non-Javadoc)
   * @see org.apache.hadoop.hbase.client.Admin#truncateTableAsync(org.apache.hadoop.hbase.TableName, boolean)
   */
  @Override
  public Future<Void> truncateTableAsync(TableName tableName, boolean preserveSplits)
      throws IOException {
    if (!preserveSplits) {
      LOG.info("truncate will preserveSplits. The passed in variable is ignored.");
    }
    return ApiFutureUtils.toCompletableFuture(
        adminClientWrapper.dropAllRowsAsync(tableName.getNameAsString()));
  }

  @Override
  public List<RegionInfo> getRegions(TableName tableName) throws IOException {
    List<RegionInfo> regionInfo = new ArrayList<>();
    for (HRegionInfo hRegionInfo : getTableRegions(tableName)) {
      regionInfo.add(hRegionInfo);
    }
    return regionInfo;
  }

  @Override
  public ClusterMetrics getClusterMetrics(EnumSet<Option> arg0) throws IOException {
    return getClusterStatus(); // TODO
  }

  @Override
  public ClusterStatus getClusterStatus() throws IOException {
    return new ClusterStatus(
        "hbaseVersion",
        "clusterid",
        new HashMap(),
        new ArrayList(),
        null,
        new ArrayList(),
        new ArrayList(),
        new String[0],
        false,
        -1);
  }

  /**
   * HBase 2.x has different return type for snapshotAsync method in different versions. {@link
   * #getSubclass} will generate the code to call the correct snapshotAsync method based on the
   * hbase version.
   */
  protected void snapshotAsyncVoid(SnapshotDescription snapshot)
      throws IOException, SnapshotCreationException {
    asyncAdmin.snapshot(snapshot);
    LOG.warn(
        "isSnapshotFinished() is not currently supported by BigtableAdmin.\n"
            + "You may poll for existence of the snapshot with listSnapshots(snapshotName)");
  }

  /**
   * HBase 2.x has different return type for snapshotAsync method in different versions. {@link
   * #getSubclass} will generate the code to call the correct snapshotAsync method based on the
   * hbase version.
   */
  protected Future<Void> snapshotAsyncFuture(SnapshotDescription snapshot)
      throws IOException, SnapshotCreationException {
    LOG.warn(
        "isSnapshotFinished() is not currently supported by BigtableAdmin.\n"
            + "You may poll for existence of the snapshot with listSnapshots(snapshotName)");
    return asyncAdmin.snapshot(snapshot);
  }

  private static Class<? extends BigtableAdmin> adminClass = null;

  /**
   * This is a workaround for incompatible changes in hbase minor versions. Dynamically generates a
   * class that extends BigtableAdmin so incompatible methods won't be accessed unless the methods
   * are called. If a method is implemented by BigtableAdmin, the generated class will invoke the
   * implementation in BigtableAdmin. Otherwise it'll throw {@link UnsupportedOperationException}.
   */
  private static synchronized Class<? extends BigtableAdmin> getSubclass()
      throws NoSuchMethodException {
    if (adminClass == null) {
      adminClass =
          new ByteBuddy()
              .subclass(BigtableAdmin.class)
              .method(ElementMatchers.isAbstract())
              .intercept(
                  InvocationHandlerAdapter.of(
                      new AbstractBigtableAdmin.UnsupportedOperationsHandler()))
              .method(
                  ElementMatchers.named("snapshotAsync")
                      .and(ElementMatchers.returns(TypeDescription.VOID)))
              .intercept(
                  MethodCall.invoke(
                          BigtableAdmin.class.getDeclaredMethod(
                              "snapshotAsyncVoid", SnapshotDescription.class))
                      .withAllArguments())
              .method(
                  ElementMatchers.named("snapshotAsync").and(ElementMatchers.returns(Future.class)))
              .intercept(
                  MethodCall.invoke(
                          BigtableAdmin.class.getDeclaredMethod(
                              "snapshotAsyncFuture", SnapshotDescription.class))
                      .withAllArguments())
              .make()
              .load(BigtableAdmin.class.getClassLoader())
              .getLoaded();
    }
    return adminClass;
  }

  public static BigtableAdmin createInstance(AbstractBigtableConnection connection)
      throws IOException {
    try {
      return getSubclass()
          .getDeclaredConstructor(AbstractBigtableConnection.class)
          .newInstance(connection);
    } catch (InvocationTargetException e) {
      // Unwrap and throw IOException or RuntimeException as is, and convert all other exceptions to
      // IOException because
      // org.apache.hadoop.hbase.client.Connection#getAdmin() only throws
      // IOException
      Throwables.throwIfInstanceOf(e.getTargetException(), IOException.class);
      Throwables.throwIfInstanceOf(e.getTargetException(), RuntimeException.class);
      throw new IOException(e);
    } catch (Exception e) {
      throw new IOException(e);
    }
  }
}


text:
// VexFlow - Music Engraving for HTML5
// Copyright Mohit Muthanna 2010
// Author Larry Kuhns 2011
// This class implements Accents.

/**
 * @constructor
 */
Vex.Flow.Articulation = function(type) {
  if (arguments.length > 0) this.init(type);
}
Vex.Flow.Articulation.prototype = new Vex.Flow.Modifier();
Vex.Flow.Articulation.prototype.constructor = Vex.Flow.Articulation;
Vex.Flow.Articulation.superclass = Vex.Flow.Modifier.prototype;

Vex.Flow.Articulation.prototype.init = function(type) {
  var superclass = Vex.Flow.Articulation.superclass;
  superclass.init.call(this);

  this.note = null;
  this.index = null;
  this.type = type;
  this.position = Vex.Flow.Modifier.Position.BELOW;

  this.render_options = {
    font_scale: 38,
    stroke_px: 3,
    stroke_spacing: 10
  };

  this.articulation = Vex.Flow.articulationCodes(this.type);
  this.setWidth(this.articulation.width);
}

Vex.Flow.Articulation.prototype.getCategory = function() {
  return "articulations";
}
Vex.Flow.Articulation.prototype.getPosition = function() {
  return this.position;
}
Vex.Flow.Articulation.prototype.setPosition = function(position) {
  if (position == Vex.Flow.Modifier.Position.ABOVE ||
      position == Vex.Flow.Modifier.Position.BELOW)
    this.position = position;
  return this;
}

Vex.Flow.Articulation.prototype.draw = function() {
  if (!this.context) throw new Vex.RERR("NoContext",
    "Can't draw Articulation without a context.");
  if (!(this.note && (this.index != null))) throw new Vex.RERR("NoAttachedNote",
    "Can't draw Articulation without a note and index.");
  // Articulations are centered over/under the note head

  var stave = this.note.stave;
  var start = this.note.getModifierStartXY(this.position, this.index);
  var glyph_y = start.y;
  var stem_ext = this.note.getStemExtents();
  if (this.position == Vex.Flow.Modifier.Position.ABOVE) {
    var shiftY = this.articulation.shift_up - 10;
    glyph_y = Vex.Min(glyph_y, stem_ext.topY);
    glyph_y = Vex.Min(glyph_y, this.note.stave.getYForLine(1) - 10);
  } else {
    var shiftY = this.articulation.shift_down + 10;
    glyph_y = Vex.Max(glyph_y, stem_ext.topY);
    glyph_y = Vex.Max(glyph_y,
                      stave.getYForLine(stave.options.num_lines - 1));
  }
  var glyph_x = (start.x) + this.articulation.shift_right;
  glyph_y += shiftY + this.y_shift;

 Vex.Flow.renderGlyph(this.context, glyph_x, glyph_y,
                       this.render_options.font_scale, this.articulation.code);
}


text:
package org.jgroups.tests;

import org.jgroups.*;
import org.jgroups.protocols.PingHeader;
import org.jgroups.protocols.TpHeader;
import org.jgroups.util.UUID;
import org.jgroups.util.Util;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Test(groups=Global.FUNCTIONAL)
public class StreamableTest {

    static final short PING_ID=100;
    static final short UDP_ID=101;

    public static void testStreamable() throws Exception {
        byte[] buf={'b', 'e', 'l', 'a', 'b', 'a', 'n'};
        byte[] tmp;
        Message m1=new BytesMessage(null, buf, 0, 4);
        Message m2=new BytesMessage(null, buf, 4, 3);

        ByteArrayOutputStream output=new ByteArrayOutputStream();
        DataOutputStream out=new DataOutputStream(output);
        m1.writeTo(out);
        out.close();
        tmp=output.toByteArray();
        output.close();

        ByteArrayInputStream input=new ByteArrayInputStream(tmp);
        DataInputStream in=new DataInputStream(input);
        Message m3, m4;

        m3=new BytesMessage();
        m3.readFrom(in);

        Assert.assertEquals(4, m3.getLength());
        Assert.assertEquals(4, m3.getArray().length);
        Assert.assertEquals(0, m3.getOffset());

        output=new ByteArrayOutputStream();
        out=new DataOutputStream(output);
        // out.writeObject(m2);
        m2.writeTo(out);
        out.close();
        tmp=output.toByteArray();
        output.close();

        System.out.println("-- serialized buffer is " + tmp.length + " bytes");

        input=new ByteArrayInputStream(tmp);
        in=new DataInputStream(input);

        m4=new BytesMessage();
        m4.readFrom(in);

        Assert.assertEquals(3, m4.getLength());
        Assert.assertEquals(3, m4.getArray().length);
        Assert.assertEquals(0, m4.getOffset());
    }

    public static void testStreamable2() throws Exception {
        byte[] buf={'b', 'e', 'l', 'a', 'b', 'a', 'n'};
        Message msg=new BytesMessage(null, buf, 0, 4);
        stream(msg);
    }

    public static void testStreamable3() throws Exception {
        byte[] buf={'b', 'e', 'l', 'a', 'b', 'a', 'n'};
        Message msg=new BytesMessage(null, buf, 4, 3);
        stream(msg);
    }

    public static void testNullBuffer() throws Exception {
        Message msg=new BytesMessage();
        stream(msg);
    }

    public static void testNonNullBuffer() throws Exception {
        Message msg=new BytesMessage(null, "Hello world".getBytes());
        stream(msg);
    }

    public static void testNonNullAddress() throws Exception {
        stream(new BytesMessage(null, "Hello world".getBytes()).setSrc(UUID.randomUUID()));
    }

    public static void testHeaders() throws Exception {
        Address dest=UUID.randomUUID();
        Address src=UUID.randomUUID();
        Message msg=new BytesMessage(dest, "Hello world".getBytes()).setSrc(src);
        PingHeader hdr=new PingHeader(PingHeader.GET_MBRS_REQ);
        msg.putHeader(PING_ID, hdr);
        TpHeader udp_hdr=new TpHeader("bla");
        msg.putHeader(UDP_ID, udp_hdr);
        stream(msg);
    }

    public static void testMergeView() throws Exception {
        Address a=Util.createRandomAddress("A"), b=Util.createRandomAddress("B"), c=Util.createRandomAddress("C"),
          d=Util.createRandomAddress("D"), e=Util.createRandomAddress("E"), f=Util.createRandomAddress("F");

        View v1=View.create(a,1,a,b,c);
        View v2=new MergeView(d, 2, Collections.singletonList(d), new ArrayList<>());
        View v3=View.create(e, 3, e,f);
        View v4=new MergeView(e, 4, Collections.singletonList(d), null);
        View v5=new View(e, 5, Collections.singletonList(d));
        List<View> subgroups=Arrays.asList(v1,v2,v3,v4,v5);

        MergeView view_all=new MergeView(a,5,Arrays.asList(a,b,c,d,e,f),subgroups);
        System.out.println("MergeView: " + view_all);
        List<View> sub=view_all.getSubgroups();
        assert sub.get(0) instanceof View;
        assert sub.get(1) instanceof MergeView;
        assert sub.get(2) instanceof View;
        assert sub.get(3) instanceof MergeView;
        assert sub.get(4) instanceof View;

        byte[] buf=Util.streamableToByteBuffer(view_all);
        assert buf != null;
        assert buf.length > 0;

        MergeView merge_view=Util.streamableFromByteBuffer(MergeView::new, buf);
        assert merge_view != null;
        System.out.println("MergeView: " + merge_view);
        for(View v: merge_view.getSubgroups()) {
            assert !(v instanceof MergeView);
        }
    }

    private static void stream(Message msg) throws Exception {
        int length, bufLength;
        byte[] tmp;
        Message msg2;
        Address src, dest=msg.getDest();
        int num_headers=getNumHeaders(msg);

        length=msg.getLength();
        bufLength=getBufLength(msg);
        src=msg.getSrc();

        ByteArrayOutputStream output=new ByteArrayOutputStream();
        DataOutputStream out=new DataOutputStream(output);
        msg.writeTo(out);
        out.close();
        tmp=output.toByteArray();
        output.close();

        System.out.println("-- serialized buffer is " + tmp.length + " bytes");

        ByteArrayInputStream input=new ByteArrayInputStream(tmp);
        DataInputStream in=new DataInputStream(input);

        msg2=new BytesMessage();
        msg2.readFrom(in);

        Assert.assertEquals(length, msg2.getLength());
        Assert.assertEquals(bufLength, getBufLength(msg2));
        assert match(dest, msg2.getDest());
        assert match(src, msg2.getSrc());
        Assert.assertEquals(num_headers, getNumHeaders(msg2));
    }

    private static int getNumHeaders(Message msg) {
        return msg.getNumHeaders();
    }

    private static boolean match(Address a1, Address a2) {
        if(a1 == null && a2 == null)
            return true;
        if(a1 != null)
            return a1.equals(a2);
        else
            return a2.equals(a1);
    }

    private static int getBufLength(Message msg) {
        return msg.getLength();
    }

}


text:
package com.amazon.dtasdk.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;
import java.util.Locale;

// Complete https://tt.amazon.com/0026066375 before open release WHOLE CLASS
/**
 * Utilities for encoding and decoding binary data to and from different forms.
 */
public class BinaryUtils {

    /** Default encoding when extracting binary data from a String */
    private static final String DEFAULT_ENCODING = "UTF-8";

    private static final Log log = LogFactory.getLog(BinaryUtils.class);

    /**
     * Converts byte data to a Hex-encoded string.
     *
     * @param data
     *            data to hex encode.
     *
     * @return hex-encoded string.
     */
    public static String toHex(byte[] data) {
        StringBuilder sb = new StringBuilder(data.length * 2);
        for (int i = 0; i < data.length; i++) {
            String hex = Integer.toHexString(data[i]);
            if (hex.length() == 1) {
                // Append leading zero.
                sb.append("0");
            } else if (hex.length() == 8) {
                // Remove ff prefix from negative numbers.
                hex = hex.substring(6);
            }
            sb.append(hex);
        }
        return sb.toString().toLowerCase(Locale.getDefault());
    }

    /**
     * Converts a Hex-encoded data string to the original byte data.
     *
     * @param hexData
     *            hex-encoded data to decode.
     * @return decoded data from the hex string.
     */
    public static byte[] fromHex(String hexData) {
        byte[] result = new byte[(hexData.length() + 1) / 2];
        String hexNumber = null;
        int stringOffset = 0;
        int byteOffset = 0;
        while (stringOffset < hexData.length()) {
            hexNumber = hexData.substring(stringOffset, stringOffset + 2);
            stringOffset += 2;
            result[byteOffset++] = (byte) Integer.parseInt(hexNumber, 16);
        }
        return result;
    }

    /**
     * Converts byte data to a Base64-encoded string.
     *
     * @param data
     *            data to Base64 encode.
     * @return encoded Base64 string.
     */
    public static String toBase64(byte[] data) {
        byte[] b64 = Base64.encodeBase64(data);
        return new String(b64);
    }

    /**
     * Converts a Base64-encoded string to the original byte data.
     *
     * @param b64Data
     *            a Base64-encoded string to decode.
     *
     * @return bytes decoded from a Base64 string.
     */
    public static byte[] fromBase64(String b64Data) {
        byte[] decoded;
        try {
            decoded = Base64.decodeBase64(b64Data.getBytes(DEFAULT_ENCODING));
        } catch (UnsupportedEncodingException uee) {
            // Shouldn't happen if the string is truly Base64 encoded.
            log.warn("Tried to Base64-decode a String with the wrong encoding: ", uee);
            decoded = Base64.decodeBase64(b64Data.getBytes());
        }
        return decoded;
    }

}


text:
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;

namespace System.MemoryTests
{
    public class CustomMemoryForTest<T> : OwnedMemory<T>
    {
        private bool _disposed;
        private int _referenceCount;
        private int _noReferencesCalledCount;
        private T[] _array;

        public CustomMemoryForTest(T[] array)
        {
            _array = array;
        }

        public int OnNoRefencesCalledCount => _noReferencesCalledCount;

        public override int Length => _array.Length;

        public override bool IsDisposed => _disposed;

        protected override bool IsRetained => _referenceCount > 0;

        public override Span<T> Span
        {
            get
            {
                if (IsDisposed)
                    throw new ObjectDisposedException(nameof(CustomMemoryForTest<T>));
                return new Span<T>(_array, 0, _array.Length);
            }
        }

        public override MemoryHandle Pin(int byteOffset = 0)
        {
            unsafe
            {
                Retain();
                if (byteOffset < 0 || (byteOffset/Unsafe.SizeOf<T>()) > _array.Length) throw new ArgumentOutOfRangeException(nameof(byteOffset));
                var handle = GCHandle.Alloc(_array, GCHandleType.Pinned);
                return new MemoryHandle(this, Unsafe.Add<byte>((void*)handle.AddrOfPinnedObject(), byteOffset), handle);
            }
        }

        protected override bool TryGetArray(out ArraySegment<T> arraySegment)
        {
            if (IsDisposed)
                throw new ObjectDisposedException(nameof(CustomMemoryForTest<T>));
            arraySegment = new ArraySegment<T>(_array);
            return true;
        }

        protected override void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                _array = null;
            }

            _disposed = true;

        }

        public override void Retain()
        {
            if (IsDisposed)
                throw new ObjectDisposedException(nameof(CustomMemoryForTest<T>));
            Interlocked.Increment(ref _referenceCount);
        }

        public override bool Release()
        {
            int newRefCount = Interlocked.Decrement(ref _referenceCount);

            if (newRefCount < 0)
                throw new InvalidOperationException();

            if (newRefCount == 0)
            {
                _noReferencesCalledCount++;
                return false;
            }
            return true;
        }
    }
}


text:
<bill session="115" type="h" number="62" updated="2017-10-11T07:15:47Z">
  <state datetime="2017-01-03">REFERRED</state>
  <status>
    <introduced datetime="2017-01-03"/>
  </status>
  <introduced datetime="2017-01-03"/>
  <titles>
    <title type="short" as="introduced">Gun Violence Reduction Resources Act of 2017</title>
    <title type="short" as="introduced">Gun Violence Reduction Resources Act of 2017</title>
    <title type="official" as="introduced">To provide for the hiring of 200 additional Bureau of Alcohol, Tobacco, Firearms and Explosives agents and investigators to enforce gun laws.</title>
    <title type="display">Gun Violence Reduction Resources Act of 2017</title>
  </titles>
  <sponsor bioguide_id="J000032"/>
  <cosponsors>
    <cosponsor bioguide_id="B001303" joined="2017-10-10"/>
  </cosponsors>
  <actions>
    <action datetime="2017-01-03">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-01-03" state="REFERRED">
      <text>Referred to the House Committee on the Judiciary.</text>
    </action>
    <action datetime="2017-01-12">
      <text>Referred to the Subcommittee on Crime, Terrorism, Homeland Security, and Investigations.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSJU" name="House Judiciary" activity="Referral"/>
    <committee subcommittee="Crime, Terrorism, Homeland Security, and Investigations" code="HSJU08" name="House Judiciary" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Crime and law enforcement"/>
    <term name="Criminal investigation, prosecution, interrogation"/>
    <term name="Department of Justice"/>
    <term name="Firearms and explosives"/>
    <term name="Government employee pay, benefits, personnel management"/>
    <term name="Law enforcement officers"/>
  </subjects>
  <amendments/>
  <summary date="2017-01-03T05:00:00Z" status="Introduced in House">Gun Violence Reduction Resources Act of 2017

This bill authorizes the Department of Justice to hire 200 additional agents and investigators for the Bureau of Alcohol, Tobacco, Firearms and Explosives.</summary>
  <committee-reports/>
</bill>


text:
package com.google.appengine.tools.appstats;

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

import play.modules.profiler.ProfilerExtra;

import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.tools.appstats.StatsProtos.AggregateRpcStatsProto;
import com.google.appengine.tools.appstats.StatsProtos.IndividualRpcStatsProto;
import com.google.appengine.tools.appstats.StatsProtos.StackFrameProto;

public enum GaeProfilerExtra implements ProfilerExtra {
    INSTANCE;

    public Map<String, Object> getExtraData(String param) {
        return null; // getAppstatsDataFor(param, 2);
    }

    /**
     * Get the Appstats data for the specified id.
     *
     * @param appstatsId
     *            The id of the Appstats request.
     * @param maxStackFrames
     *            The maximum number of stack frames to include in each RPC
     *            stack trace.
     * @return The appstats data.
     */
    public static Map<String, Object> getAppstatsDataFor(String appstatsId, Integer maxStackFrames)
    {
        Map<String, Object> appstatsMap = null;
        MemcacheWriter writer = new MemcacheWriter(null, MemcacheServiceFactory.getMemcacheService("__appstats__"));
        StatsProtos.RequestStatProto appstats = writer.getFull(Long.parseLong(appstatsId));
        if (appstats != null)
        {
            appstatsMap = new HashMap<String, Object>();
            appstatsMap.put("totalTime", appstats.getDurationMilliseconds());

            Map<String, Map<String, Object>> rpcInfoMap = new LinkedHashMap<String, Map<String, Object>>();
            for (AggregateRpcStatsProto rpcStat : appstats.getRpcStatsList())
            {
                Map<String, Object> rpcInfo = rpcInfoMap.get(rpcStat.getServiceCallName());
                if (rpcInfo == null)
                {
                    rpcInfo = new LinkedHashMap<String, Object>();
                    rpcInfoMap.put(rpcStat.getServiceCallName(), rpcInfo);
                }

                rpcInfo.put("totalCalls", rpcStat.getTotalAmountOfCalls());
                rpcInfo.put("totalTime", Long.valueOf(0));
            }

            List<Map<String, Object>> callInfoMap = new ArrayList<Map<String, Object>>();
            for (IndividualRpcStatsProto rpcStat : appstats.getIndividualStatsList())
            {
                // Update the total time for the RPC method
                Map<String, Object> rpcInfo = rpcInfoMap.get(rpcStat.getServiceCallName());
                rpcInfo.put("totalTime", ((Long) rpcInfo.get("totalTime")) + rpcStat.getDurationMilliseconds());

                // Get info about this specific call
                Map<String, Object> callInfo = new LinkedHashMap<String, Object>();
                callInfoMap.add(callInfo);
                callInfo.put("serviceCallName", rpcStat.getServiceCallName());
                callInfo.put("totalTime", rpcStat.getDurationMilliseconds());
                callInfo.put("startOffset", rpcStat.getStartOffsetMilliseconds());
                callInfo.put("request", truncate(rpcStat.getRequestDataSummary(), 100));
                callInfo.put("response", truncate(rpcStat.getResponseDataSummary(), 100));
                // Get the stack trace
                List<String> callStack = new ArrayList<String>();
                int i = 0;
                for (StackFrameProto frame : rpcStat.getCallStackList())
                {
                    if (maxStackFrames != null && i == maxStackFrames)
                    {
                        break;
                    }
                    callStack.add(String.format("%s.%s:%d", frame.getClassOrFileName(), frame.getFunctionName(),
                            frame.getLineNumber()));
                    i++;
                }
                callInfo.put("callStack", callStack);
            }
            appstatsMap.put("rpcStats", !rpcInfoMap.isEmpty() ? rpcInfoMap : null);
            appstatsMap.put("rpcCalls", !callInfoMap.isEmpty() ? callInfoMap : null);
        }
        return appstatsMap;
    }

    private static String truncate(String s, int maxLength)
    {
        if (s.length() > maxLength)
        {
            return s.substring(0, maxLength);
        } else
        {
            return s;
        }
    }

}