text:
// Copyright 2014 The Cockroach Authors.
//
// 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.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)

package storage

import (
	"fmt"
	"time"

	"github.com/cockroachdb/cockroach/pkg/roachpb"
	"github.com/cockroachdb/cockroach/pkg/util/cache"
	"github.com/cockroachdb/cockroach/pkg/util/hlc"
	"github.com/cockroachdb/cockroach/pkg/util/interval"
	"github.com/cockroachdb/cockroach/pkg/util/uuid"
	"github.com/google/btree"
)

const (
	// MinTSCacheWindow specifies the minimum duration to hold entries in
	// the cache before allowing eviction. After this window expires,
	// transactions writing to this node with timestamps lagging by more
	// than minCacheWindow will necessarily have to advance their commit
	// timestamp.
	MinTSCacheWindow = 10 * time.Second

	defaultEvictionSizeThreshold = 512

	// Max entries in each btree node.
	// TODO(peter): Not yet tuned.
	btreeDegree = 64
)

// cacheRequest holds the timestamp cache data from a single batch request. The
// requests are stored in a btree keyed by the timestamp and are "expanded" to
// populate the read/write interval caches if a potential conflict is detected
// due to an earlier request (based on timestamp) arriving.
type cacheRequest struct {
	reads     []roachpb.Span
	writes    []roachpb.Span
	txn       roachpb.Span
	txnID     *uuid.UUID
	timestamp hlc.Timestamp
	// Used to distinguish requests with identical timestamps. For actual
	// requests, the uniqueID value is >0. When probing the btree for requests
	// later than a particular timestamp a value of 0 is used.
	uniqueID int64
}

// Less implements the btree.Item interface.
func (cr *cacheRequest) Less(other btree.Item) bool {
	otherReq := other.(*cacheRequest)
	if cr.timestamp.Less(otherReq.timestamp) {
		return true
	}
	if otherReq.timestamp.Less(cr.timestamp) {
		return false
	}
	// Fallback to comparison of the uniqueID as a tie-breaker. This allows
	// multiple requests with the same timestamp to exist in the requests btree.
	return cr.uniqueID < otherReq.uniqueID
}

// numSpans returns the number of spans the request will expand into.
func (cr *cacheRequest) numSpans() int {
	n := len(cr.reads) + len(cr.writes)
	if cr.txn.Key != nil {
		n++
	}
	return n
}

// A TimestampCache maintains an interval tree FIFO cache of keys or
// key ranges and the timestamps at which they were most recently read
// or written. If a timestamp was read or written by a transaction,
// the txn ID is stored with the timestamp to avoid advancing
// timestamps on successive requests from the same transaction.
//
// The cache also maintains a low-water mark which is the most
// recently evicted entry's timestamp. This value always ratchets
// with monotonic increases. The low water mark is initialized to
// the current system time plus the maximum clock offset.
type timestampCache struct {
	rCache, wCache   *cache.IntervalCache
	lowWater, latest hlc.Timestamp

	// The requests tree contains cacheRequest entries keyed by timestamp. A
	// request is "expanded" (i.e. the read/write spans are added to the
	// read/write interval caches) when the timestamp cache is accessed on behalf
	// of an earlier request.
	requests   *btree.BTree
	tmpReq     cacheRequest
	reqIDAlloc int64
	reqSpans   int

	// evictionSizeThreshold allows old entries to stay in the TimestampCache
	// indefinitely as long as the number of intervals in the cache doesn't
	// exceed this value. Once the cache grows beyond it, intervals are
	// evicted according to the time window. This threshold is intended to
	// permit transactions to take longer than the eviction window duration
	// if the size of the cache is not a concern, such as when a user
	// is using an interactive SQL shell.
	evictionSizeThreshold int
}

// A cacheValue combines the timestamp with an optional txn ID.
type cacheValue struct {
	timestamp hlc.Timestamp
	txnID     *uuid.UUID // Nil for no transaction
}

func makeCacheEntry(key cache.IntervalKey, value cacheValue) *cache.Entry {
	alloc := struct {
		key   cache.IntervalKey
		value cacheValue
		entry cache.Entry
	}{
		key:   key,
		value: value,
	}
	alloc.entry.Key = &alloc.key
	alloc.entry.Value = &alloc.value
	return &alloc.entry
}

// newTimestampCache returns a new timestamp cache with supplied
// hybrid clock.
func newTimestampCache(clock *hlc.Clock) *timestampCache {
	tc := &timestampCache{
		rCache:                cache.NewIntervalCache(cache.Config{Policy: cache.CacheFIFO}),
		wCache:                cache.NewIntervalCache(cache.Config{Policy: cache.CacheFIFO}),
		evictionSizeThreshold: defaultEvictionSizeThreshold,
	}
	tc.Clear(clock.Now())
	tc.rCache.Config.ShouldEvict = tc.shouldEvict
	tc.wCache.Config.ShouldEvict = tc.shouldEvict
	return tc
}

// Clear clears the cache and resets the low-water mark.
func (tc *timestampCache) Clear(lowWater hlc.Timestamp) {
	tc.requests = btree.New(btreeDegree)
	tc.rCache.Clear()
	tc.wCache.Clear()
	tc.lowWater = lowWater
	tc.latest = tc.lowWater
}

// len returns the total number of read and write intervals in the
// TimestampCache.
func (tc *timestampCache) len() int {
	return tc.rCache.Len() + tc.wCache.Len() + tc.reqSpans
}

// SetLowWater sets the cache's low water mark, which is the minimum
// value the cache will return from calls to GetMax().
func (tc *timestampCache) SetLowWater(lowWater hlc.Timestamp) {
	if tc.lowWater.Less(lowWater) {
		tc.lowWater = lowWater
	}
}

// add the specified timestamp to the cache as covering the range of
// keys from start to end. If end is nil, the range covers the start
// key only. txnID is nil for no transaction. readTSCache specifies
// whether the command adding this timestamp should update the read
// timestamp; false to update the write timestamp cache.
func (tc *timestampCache) add(
	start, end roachpb.Key, timestamp hlc.Timestamp, txnID *uuid.UUID, readTSCache bool,
) {
	// This gives us a memory-efficient end key if end is empty.
	if len(end) == 0 {
		end = start.Next()
		start = end[:len(start)]
	}
	tc.latest.Forward(timestamp)
	// Only add to the cache if the timestamp is more recent than the
	// low water mark.
	if tc.lowWater.Less(timestamp) {
		tcache := tc.wCache
		if readTSCache {
			tcache = tc.rCache
		}

		addRange := func(r interval.Range) {
			value := cacheValue{timestamp: timestamp, txnID: txnID}
			key := tcache.MakeKey(r.Start, r.End)
			entry := makeCacheEntry(key, value)
			tcache.AddEntry(entry)
		}
		r := interval.Range{
			Start: interval.Comparable(start),
			End:   interval.Comparable(end),
		}

		// Check existing, overlapping entries and truncate/split/remove if
		// superseded and in the past. If existing entries are in the future,
		// subtract from the range/ranges that need to be added to cache.
		for _, entry := range tcache.GetOverlaps(r.Start, r.End) {
			cv := entry.Value.(*cacheValue)
			key := entry.Key.(*cache.IntervalKey)
			sCmp := r.Start.Compare(key.Start)
			eCmp := r.End.Compare(key.End)
			if cv.timestamp.Less(timestamp) {
				// The existing interval has a timestamp less than the new
				// interval. Compare interval ranges to determine how to
				// modify existing interval.
				switch {
				case sCmp == 0 && eCmp == 0:
					// New and old are equal; replace old with new and avoid the need to insert new.
					//
					// New: ------------
					// Old: ------------
					//
					// New: ------------
					// Old:
					*cv = cacheValue{timestamp: timestamp, txnID: txnID}
					tcache.MoveToEnd(entry)
					return
				case sCmp <= 0 && eCmp >= 0:
					// New contains or is equal to old; delete old.
					//
					// New: ------------      ------------      ------------
					// Old:   --------    or    ----------  or  ----------
					//
					// New: ------------      ------------      ------------
					// Old:
					tcache.DelEntry(entry)
				case sCmp > 0 && eCmp < 0:
					// Old contains new; split up old into two.
					//
					// New:     ----
					// Old: ------------
					//
					// New:     ----
					// Old: ----    ----
					oldEnd := key.End
					key.End = r.Start

					newKey := tcache.MakeKey(r.End, oldEnd)
					newEntry := makeCacheEntry(newKey, *cv)
					tcache.AddEntryAfter(newEntry, entry)
				case eCmp >= 0:
					// Left partial overlap; truncate old end.
					//
					// New:     --------          --------
					// Old: --------      or  ------------
					//
					// New:     --------          --------
					// Old: ----              ----
					key.End = r.Start
				case sCmp <= 0:
					// Right partial overlap; truncate old start.
					//
					// New: --------          --------
					// Old:     --------  or  ------------
					//
					// New: --------          --------
					// Old:         ----              ----
					key.Start = r.End
				default:
					panic(fmt.Sprintf("no overlap between %v and %v", key.Range, r))
				}
			} else if timestamp.Less(cv.timestamp) {
				// The existing interval has a timestamp greater than the new interval.
				// Compare interval ranges to determine how to modify new interval before
				// adding it to the timestamp cache.
				switch {
				case sCmp >= 0 && eCmp <= 0:
					// Old contains or is equal to new; no need to add.
					//
					// Old: -----------      -----------      -----------      -----------
					// New:    -----     or  -----------  or  --------     or     --------
					//
					// Old: -----------      -----------      -----------      -----------
					// New:
					return
				case sCmp < 0 && eCmp > 0:
					// New contains old; split up old into two. We can add the left piece
					// immediately because it is guaranteed to be before the rest of the
					// overlaps.
					//
					// Old:    ------
					// New: ------------
					//
					// Old:    ------
					// New: ---      ---
					lr := interval.Range{Start: r.Start, End: key.Start}
					addRange(lr)

					r.Start = key.End
				case eCmp > 0:
					// Left partial overlap; truncate new start.
					//
					// Old: --------          --------
					// New:     --------  or  ------------
					//
					// Old: --------          --------
					// New:         ----              ----
					r.Start = key.End
				case sCmp < 0:
					// Right partial overlap; truncate new end.
					//
					// Old:     --------          --------
					// New: --------      or  ------------
					//
					// Old:     --------          --------
					// New: ----              ----
					r.End = key.Start
				default:
					panic(fmt.Sprintf("no overlap between %v and %v", key.Range, r))
				}
			} else if (cv.txnID == nil && txnID == nil) ||
				(cv.txnID != nil && txnID != nil && *cv.txnID == *txnID) {
				// The existing interval has a timestamp equal to the new
				// interval, and the same transaction ID.
				switch {
				case sCmp >= 0 && eCmp <= 0:
					// Old contains or is equal to new; no need to add.
					//
					// New:    -----     or  -----------  or  --------     or     --------
					// Old: -----------      -----------      -----------      -----------
					//
					// New:
					// Old: -----------      -----------      -----------      -----------
					return
				case sCmp <= 0 && eCmp >= 0:
					// New contains old; delete old.
					//
					// New: ------------      ------------      ------------
					// Old:   --------    or    ----------  or  ----------
					//
					// New: ------------      ------------      ------------
					// Old:
					tcache.DelEntry(entry)
				case eCmp >= 0:
					// Left partial overlap; truncate old end.
					//
					// New:     --------          --------
					// Old: --------      or  ------------
					//
					// New:     --------          --------
					// Old: ----              ----
					key.End = r.Start
				case sCmp <= 0:
					// Right partial overlap; truncate old start.
					//
					// New: --------          --------
					// Old:     --------  or  ------------
					//
					// New: --------          --------
					// Old:         ----              ----
					key.Start = r.End
				default:
					panic(fmt.Sprintf("no overlap between %v and %v", key.Range, r))
				}
			} else {
				// The existing interval has a timestamp equal to the new
				// interval and a different transaction ID.
				switch {
				case sCmp == 0 && eCmp == 0:
					// New and old are equal. Segment is no longer owned by any
					// transaction.
					//
					// New: ------------
					// Old: ------------
					//
					// New:
					// Nil: ============
					// Old:
					cv.txnID = nil
					return
				case sCmp == 0 && eCmp > 0:
					// New contains old, left-aligned. Clear ownership of the
					// existing segment and truncate new.
					//
					// New: ------------
					// Old: ----------
					//
					// New:           --
					// Nil: ==========
					// Old:
					cv.txnID = nil
					r.Start = key.End
				case sCmp < 0 && eCmp == 0:
					// New contains old, right-aligned. Clear ownership of the
					// existing segment and truncate new.
					//
					// New: ------------
					// Old:   ----------
					//
					// New: --
					// Nil:   ==========
					// Old:
					cv.txnID = nil
					r.End = key.Start
				case sCmp < 0 && eCmp > 0:
					// New contains old; split into three segments with the
					// overlap owned by no txn.
					//
					// New: ------------
					// Old:   --------
					//
					// New: --        --
					// Nil:   ========
					// Old:
					cv.txnID = nil
					newKey := tcache.MakeKey(r.Start, key.Start)
					newEntry := makeCacheEntry(newKey, cacheValue{timestamp: timestamp, txnID: txnID})
					tcache.AddEntryAfter(newEntry, entry)
					r.Start = key.End
				case sCmp > 0 && eCmp < 0:
					// Old contains new; split up old into two. New segment is
					// owned by no txn.
					//
					// New:     ----
					// Old: ------------
					//
					// New:
					// Nil:     ====
					// Old: ----    ----
					txnID = nil
					oldEnd := key.End
					key.End = r.Start

					newKey := tcache.MakeKey(r.End, oldEnd)
					newEntry := makeCacheEntry(newKey, *cv)
					tcache.AddEntryAfter(newEntry, entry)
				case eCmp == 0:
					// Old contains new, right-aligned; truncate old end and clear
					// ownership of new segment.
					//
					// New:     --------
					// Old: ------------
					//
					// New:
					// Nil:     ========
					// Old: ----
					txnID = nil
					key.End = r.Start
				case sCmp == 0:
					// Old contains new, left-aligned; truncate old start and
					// clear ownership of new segment.
					// New: --------
					// Old: ------------
					//
					// New:
					// Nil: ========
					// Old:         ----
					txnID = nil
					key.Start = r.End
				case eCmp > 0:
					// Left partial overlap; truncate old end and split new into
					// segments owned by no txn (the overlap) and the new txn.
					//
					// New:     --------
					// Old: --------
					//
					// New:         ----
					// Nil:     ====
					// Old: ----
					key.End, r.Start = r.Start, key.End
					newKey := tcache.MakeKey(key.End, r.Start)
					newCV := cacheValue{timestamp: cv.timestamp, txnID: nil}
					newEntry := makeCacheEntry(newKey, newCV)
					tcache.AddEntryAfter(newEntry, entry)
				case sCmp < 0:
					// Right partial overlap; truncate old start and split new into
					// segments owned by no txn (the overlap) and the new txn.
					//
					// New: --------
					// Old:     --------
					//
					// New: ----
					// Nil:     ====
					// Old:         ----
					key.Start, r.End = r.End, key.Start
					newKey := tcache.MakeKey(r.End, key.Start)
					newCV := cacheValue{timestamp: cv.timestamp, txnID: nil}
					newEntry := makeCacheEntry(newKey, newCV)
					tcache.AddEntryAfter(newEntry, entry)
				default:
					panic(fmt.Sprintf("no overlap between %v and %v", key.Range, r))
				}
			}
		}
		addRange(r)
	}
}

// AddRequest adds the specified request to the cache in an unexpanded state.
func (tc *timestampCache) AddRequest(req cacheRequest) {
	if len(req.reads) == 0 && len(req.writes) == 0 && req.txn.Key == nil {
		// The request didn't contain any spans for the timestamp cache.
		return
	}

	if !tc.lowWater.Less(req.timestamp) {
		// Request too old to be added.
		return
	}

	tc.reqIDAlloc++
	req.uniqueID = tc.reqIDAlloc
	tc.requests.ReplaceOrInsert(&req)
	tc.reqSpans += req.numSpans()

	// Bump the latest timestamp and evict any requests that are now too old.
	tc.latest.Forward(req.timestamp)
	edge := tc.latest
	edge.WallTime -= MinTSCacheWindow.Nanoseconds()

	// Evict requests as long as the number of cached spans (both in the requests
	// queue and the interval caches) is larger than the eviction threshold.
	for tc.len() > tc.evictionSizeThreshold {
		// TODO(peter): It might be more efficient to gather up the requests to
		// delete using BTree.AscendLessThan rather than calling Min
		// repeatedly. Maybe.
		minItem := tc.requests.Min()
		if minItem == nil {
			break
		}
		minReq := minItem.(*cacheRequest)
		if edge.Less(minReq.timestamp) {
			break
		}
		tc.lowWater = minReq.timestamp
		tc.requests.DeleteMin()
		if tc.reqSpans < minReq.numSpans() {
			panic(fmt.Sprintf("bad reqSpans: %d < %d", tc.reqSpans, minReq.numSpans()))
		}
		tc.reqSpans -= minReq.numSpans()
	}
}

// ExpandRequests expands any request that is newer than the specified
// timestamp.
func (tc *timestampCache) ExpandRequests(timestamp hlc.Timestamp) {
	// Find all of the requests that have a timestamp greater than or equal to
	// the specified timestamp. Note that we can't delete the requests during the
	// btree iteration.
	var reqs []*cacheRequest
	tc.tmpReq.timestamp = timestamp
	tc.requests.AscendGreaterOrEqual(&tc.tmpReq, func(i btree.Item) bool {
		// TODO(peter): We could be more intelligent about not expanding a request
		// if there is no possibility of overlap. For example, in workloads where
		// there are concurrent bulk inserts for completely distinct ranges.
		reqs = append(reqs, i.(*cacheRequest))
		return true
	})

	// Expand the requests, inserting the spans into either the read or write
	// interval caches.
	for _, req := range reqs {
		tc.requests.Delete(req)
		if tc.reqSpans < req.numSpans() {
			panic(fmt.Sprintf("bad reqSpans: %d < %d", tc.reqSpans, req.numSpans()))
		}
		tc.reqSpans -= req.numSpans()
		for _, sp := range req.reads {
			tc.add(sp.Key, sp.EndKey, req.timestamp, req.txnID, true /* readTSCache */)
		}
		for _, sp := range req.writes {
			tc.add(sp.Key, sp.EndKey, req.timestamp, req.txnID, false /* !readTSCache */)
		}
		if req.txn.Key != nil {
			// We set txnID=nil because we want hits for same txn ID.
			tc.add(req.txn.Key, req.txn.EndKey, req.timestamp, nil, false /* !readTSCache */)
		}
	}
}

// GetMaxRead returns the maximum read timestamp which overlaps the
// interval spanning from start to end. If that timestamp belongs to a
// single transaction, that transaction's ID is returned. If no part
// of the specified range is overlapped by timestamps from different
// transactions in the cache, the low water timestamp is returned for
// the read timestamps. Also returns an "ok" bool, indicating whether
// an explicit match of the interval was found in the cache (as
// opposed to using the low-water mark).
func (tc *timestampCache) GetMaxRead(start, end roachpb.Key) (hlc.Timestamp, *uuid.UUID, bool) {
	return tc.getMax(start, end, true)
}

// GetMaxWrite returns the maximum write timestamp which overlaps the
// interval spanning from start to end. If that timestamp belongs to a
// single transaction, that transaction's ID is returned. If no part
// of the specified range is overlapped by timestamps from different
// transactions in the cache, the low water timestamp is returned for
// the write timestamps. Also returns an "ok" bool, indicating whether
// an explicit match of the interval was found in the cache (as
// opposed to using the low-water mark).
func (tc *timestampCache) GetMaxWrite(start, end roachpb.Key) (hlc.Timestamp, *uuid.UUID, bool) {
	return tc.getMax(start, end, false)
}

func (tc *timestampCache) getMax(
	start, end roachpb.Key, readTSCache bool,
) (hlc.Timestamp, *uuid.UUID, bool) {
	if len(end) == 0 {
		end = start.Next()
	}
	var ok bool
	maxTS := tc.lowWater
	var maxTxnID *uuid.UUID
	cache := tc.wCache
	if readTSCache {
		cache = tc.rCache
	}
	for _, o := range cache.GetOverlaps(start, end) {
		ce := o.Value.(*cacheValue)
		if maxTS.Less(ce.timestamp) {
			ok = true
			maxTS = ce.timestamp
			maxTxnID = ce.txnID
		} else if maxTS.Equal(ce.timestamp) && maxTxnID != nil &&
			(ce.txnID == nil || *maxTxnID != *ce.txnID) {
			maxTxnID = nil
		}
	}
	return maxTS, maxTxnID, ok
}

// MergeInto merges all entries from this timestamp cache into the
// dest timestamp cache. The clear parameter, if true, copies the
// values of lowWater and latest and clears the destination cache
// before merging in the source.
func (tc *timestampCache) MergeInto(dest *timestampCache, clear bool) {
	if clear {
		dest.Clear(tc.lowWater)
		dest.latest = tc.latest
		dest.reqIDAlloc = 0

		// Because we just cleared the destination cache, we can directly
		// insert entries from this cache.
		hardMerge := func(srcCache, destCache *cache.IntervalCache) {
			srcCache.Do(func(k, v interface{}) {
				// Cache entries are mutable (see Add), so we give each cache its own
				// unique copy.
				entry := makeCacheEntry(*k.(*cache.IntervalKey), *v.(*cacheValue))
				destCache.AddEntry(entry)
			})
		}
		hardMerge(tc.rCache, dest.rCache)
		hardMerge(tc.wCache, dest.wCache)
	} else {
		dest.lowWater.Forward(tc.lowWater)
		dest.latest.Forward(tc.latest)

		// The cache was not cleared before, so we can't just insert entries because
		// intervals may need to be adjusted or removed to maintain the non-overlapping
		// guarantee.
		softMerge := func(srcCache *cache.IntervalCache, readTSCache bool) {
			srcCache.Do(func(k, v interface{}) {
				key, val := *k.(*cache.IntervalKey), *v.(*cacheValue)
				dest.add(roachpb.Key(key.Start), roachpb.Key(key.End), val.timestamp, val.txnID, readTSCache)
			})
		}
		softMerge(tc.rCache, true)
		softMerge(tc.wCache, false)
	}

	// Copy the requests.
	tc.requests.Ascend(func(i btree.Item) bool {
		req := *(i.(*cacheRequest))
		dest.reqIDAlloc++
		req.uniqueID = dest.reqIDAlloc
		dest.requests.ReplaceOrInsert(&req)
		dest.reqSpans += req.numSpans()
		return true
	})
}

// shouldEvict returns true if the cache entry's timestamp is no
// longer within the MinTSCacheWindow.
func (tc *timestampCache) shouldEvict(size int, key, value interface{}) bool {
	if tc.len() <= tc.evictionSizeThreshold {
		return false
	}
	ce := value.(*cacheValue)
	// In case low water mark was set higher, evict any entries
	// which occurred before it.
	if ce.timestamp.Less(tc.lowWater) {
		return true
	}
	// Compute the edge of the cache window.
	edge := tc.latest
	edge.WallTime -= MinTSCacheWindow.Nanoseconds()
	// We evict and update the low water mark if the proposed evictee's
	// timestamp is <= than the edge of the window.
	if !edge.Less(ce.timestamp) {
		tc.lowWater = ce.timestamp
		return true
	}
	return false
}


text:
@import 'open-color/open-color.css';

.container {
  composes: dashboard_content from 'STYLES/common.css';
  position: relative;
  margin-top: 100px;
}

.head_switchers {
  font-size: 14px;
  line-height: 30px;
  margin: 10px 0;
}

.head_switcher {
  color: var(--oc-gray-5);
  cursor: pointer;
  display: inline-block;
  transition: color 0.3s;
  transition: border-bottom 0.3s;
  border-bottom: 2px solid transparent;

  &:hover {
    border-bottom: 2px solid var(--oc-gray-7);
    color: var(--oc-gray-7);
  }
}

.head_switcher_active {
  border-bottom: 2px solid transparent;
  color: var(--oc-gray-7);
}

.card_container {
  composes: card_container from 'STYLES/common.css';
  margin-top: 0;
}

.card {
  composes: card from 'STYLES/common.css';
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.cardLite {
  border: none;
  box-shadow: none;
}

.infoCard {
  margin: 0;
}

.infoText {
  font-size: 2.5em;
  display: inline-block;
  font-weight: bolder;
}

.infoTextSub {
  font-size: 1.5em;
  color: var(--oc-gray-5);
}

.share_controller_card {
  composes: card;
  display: flex;
  padding: 0;
  flex-direction: row;
  box-shadow: none;
  z-index: 9;
  background-color: transparent;
}

.shareCard {
  margin: 0;
  display: flex;
  margin-bottom: 30px;
}

.shareCardBg {
  background-color: var(--oc-white);
  padding: 10px;
}

.logsCardBg {
  z-index: 9 !important;
}

.disabled {
  composes: card_disabled from 'STYLES/common.css';

  &::before {
    z-index: 9;
  }
}

.info_container {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.share_controller {
  composes: info_container;
  height: 50px;
  width: 100%;
  justify-content: flex-start;
  position: relative;
}

.base_container {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.share_container_wrapper {
  composes: base_container;
  margin-left: 10px;
}

.share_container {
  composes: base_container;
}

.chart_container {
  composes: info_container;
  width: 100%;
  margin-bottom: 15px;

  &:not(:last-child) {
    border-bottom: 1px solid #e9ecef;
    padding-bottom: 15px;
  }
}

.pageview_chart_container {
  margin: 0 3% 15px 3%;
  width: 94%;
  position: relative;
}

.chart_info_container {
  composes: chart_info_container from 'STYLES/common.css';
  margin-bottom: 15px;
}

.radar_chart {
  flex: 1;
  max-width: 45%;
}

.radarChart {
  max-width: 250px !important;
  height: auto !important;
}

.viewDevicesChart {}

.viewSourcesChart {}

.qrcode_container {
  font-size: 14px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-top: 10px;

  & span {
    line-height: 25px;
  }
}

.card_group {
  width: 100%;
  margin-top: 0;
  margin-bottom: 15px;
}

/* chart controller */
.chart_controllers {
  position: absolute;
  top: 10px;
  right: 0;
  z-index: var(--zIndex9);
  border-radius: 2px;
  background-color: var(--oc-gray-7);
  font-size: 12px;
  padding: 7px;
  color: var(--oc-gray-5);
}

.chart_controller {
  cursor: pointer;

  &.controller_active {
    color: var(--oc-white);
  }
}

.recordsContainer {
  transition: transform 0.3s, opacity 0.3s;
  opacity: 1;
}

.recordsContainer-hidden {
  opacity: 0;
  transform: translateY(-15%);
}

.recordsContainer-entering {
  opacity: 1;
  transform: translateY(0);
}

.recordsContainer-entered {
  opacity: 1;
  transform: initial;
}

.recordsContainer-exiting {
  opacity: 0;
  transform: translateY(-15%);
}

.viewLog {
  display: flex;
  flex-direction: column;
  padding: 15px 0;
  width: 95%;

  &:not(:last-child) {
    border-bottom: 1px solid var(--oc-gray-2);
  }
}

.viewLogTop {
  width: 100%;
  font-size: 16px;
  line-height: 24px;
  color: var(--oc-gray-7);
  display: flex;
  flex-direction: row;
}

.viewLogBottom {
  display: flex;
  width: 100%;
  font-size: 12px;
  line-height: 18px;
  color: var(--oc-gray-5);
  flex-direction: row;
  margin-top: 5px;
}

.viewRow {
  flex: 1;
}

.viewTitle {
  width: 100%;
  font-size: 14px;
  padding: 10px 0 17px 0;
}

.logTipsoContainer {
  width: 180px;
  max-height: 250px;
  overflow-y: scroll;
}

.logTipso {
  padding: 5px 0;
}

.logTipsoMain {
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 20px;
}

.logTipsoSub {
  opacity: 0.5;
  font-size: 12px;
  margin-top: 2px;
}

redpajama_set_name: RedPajamaGithub


text:
package org.asynchttpclient.netty.channel.pool;

import io.netty.channel.Channel;

public interface ChannelPool {

    /**
     * Add a channel to the pool
     *
     * @param channel an I/O channel
     * @param partitionKey a key used to retrieve the cached channel
     * @return true if added.
     */
    boolean offer(Channel channel, Object partitionKey);

    /**
     * Remove the channel associated with the uri.
     *
     * @param partitionKey the partition used when invoking offer
     * @return the channel associated with the uri
     */
    Channel poll(Object partitionKey);

    /**
     * Remove all channels from the cache. A channel might have been associated
     * with several uri.
     *
     * @param channel a channel
     * @return the true if the channel has been removed
     */
    boolean removeAll(Channel channel);

    /**
     * Return true if a channel can be cached. A implementation can decide based
     * on some rules to allow caching Calling this method is equivalent of
     * checking the returned value of {@link ChannelPool#offer(Channel, Object)}
     *
     * @return true if a channel can be cached.
     */
    boolean isOpen();

    /**
     * Destroy all channels that has been cached by this instance.
     */
    void destroy();

    /**
     * Flush a partition
     *
     * @param partitionKey the partition
     */
    void flushPartition(Object partitionKey);

    /**
     * Flush partitions based on a selector
     *
     * @param selector the selector
     */
    void flushPartitions(ChannelPoolPartitionSelector selector);
}


text:
Alex's Personal Website & Blog

  Homepage |
  Twitter

## Performance

### Lighthouse

![alexdiliberto.com lighthouse score](https://raw.githubusercontent.com/alexdiliberto/alexdiliberto.github.io/master/img/lighthouse-score.png)

![alexdiliberto.com lighthouse runtime settings](https://raw.githubusercontent.com/alexdiliberto/alexdiliberto.github.io/master/img/lighthouse-runtime-settings.png)

https://gist.github.com/alexdiliberto/560b4fce0b9884852740ad2f6590b438

### PageSpeed Insights

![alexdiliberto.com google pagespeed insights score](https://raw.githubusercontent.com/alexdiliberto/alexdiliberto.github.io/master/img/pagespeed-insights-score.png)

## Contributing

See the [Contributing](CONTRIBUTING.md) guide for details.

## Configuration

### HTTPS

HTTPS is now configured with [Cloudflare](https://www.cloudflare.com/a/overview/alexdiliberto.com)

### Email

Email Forwarding is handled using [MailGun](https://app.mailgun.com)

### Caching

##### Cloudflare Cache

CDN caching is currently enabled. Cache is purged after each commit to master using the [Cloudflare Purge Cache](https://github.com/marketplace/actions/cloudflare-purge-cache) GitHub Action.

If, for some reason, you need to manually purge the cache, Login to Cloudflare and click ["Purge Everything"](https://blog.cloudflare.com/secure-and-fast-github-pages-with-cloudflare/#step4cacheallthethings) after successfully deploying a new post or as needed.

#### Service Worker Cache
Don't forget to increment the `sw.js` Service Worker cache value after publishing new content

#### Facebook Open Graph

Fetch new [Facebook Scrape Information](https://developers.facebook.com/tools/debug/og/object/)


text:
USING_STRINGS = False

# dataclass_module_1.py and dataclass_module_1_str.py are identical
# except only the latter uses string annotations.

import dataclasses
import typing

T_CV2 = typing.ClassVar[int]
T_CV3 = typing.ClassVar

T_IV2 = dataclasses.InitVar[int]
T_IV3 = dataclasses.InitVar

@dataclasses.dataclass
class CV:
    T_CV4 = typing.ClassVar
    cv0: typing.ClassVar[int] = 20
    cv1: typing.ClassVar = 30
    cv2: T_CV2
    cv3: T_CV3
    not_cv4: T_CV4  # When using string annotations, this field is not recognized as a ClassVar.

@dataclasses.dataclass
class IV:
    T_IV4 = dataclasses.InitVar
    iv0: dataclasses.InitVar[int]
    iv1: dataclasses.InitVar
    iv2: T_IV2
    iv3: T_IV3
    not_iv4: T_IV4  # When using string annotations, this field is not recognized as an InitVar.


text:
layout: post
title: "Five Reasons to Teach Elementary Statistics With R:  #3"
date: 2014-05-05 01:00:00
categories: [R]
published:  true
---

* will be replaced by TOC
{:toc}

## Introduction

This is the third in a projected five-part series of posts aimed at colleagues who teach elementary statistics.  If you teach with R but hesitate to spring such a powerful and complex tool on unsuspecting introductory students---many of whom whom will have had no prior experience with the command line, much less with coding---then I hope these posts will give you some encouragement.

The [previous post](http://statistics.rainandrhino.org/blog/2014/04/08/reasons-to-teach-with-R-2/) in this series described R Studio's package `manipulate` and its applications in the easy authoring of instructional applets.  Today we'll look at `shiny`, a related RStudio project.

In order to try the ensuing examples, download an ancillary package that we use for our elementary course:

{% highlight r %}
require(devtools)
install_github(repo="homerhanumat/tigerstats")
{% endhighlight %}

## Reason #3:  RStudio's `shiny`

[Shiny](https://www.rstudio.com/shiny/) appears to be intended primarily for data analysts working in industry or in academic or institutional research, but on the very day of its public release Victor Moreno pointed out its implications for statistics education (see his comment on [this RStudio blog post](http://blog.rstudio.org/2012/11/08/introducing-shiny/)).  For statistics instructors Shiny offers essentially the same benefits as `manipulate`, but in addition comes pimped out with:

* options for dynamic user input;
* output formats that go well beyond `manipulate`'s home in the Plots pane;
* default Bootstrap styling.

## Examples

### "Slow" Simulation

At my College we believe that simulation is important to understanding probability concepts, but we also find that our students don't easily grasp the import of a simulation when the computers simply generates, say, 3000 re-samples and summarizes the results, *all in flash*.  We feel the need for plenty of "one at a time" simulation experiences that serve as transitions to the analysis of large-scale simulation results, and we don't always find apps on the web that cater to our needs in just the way we would like.

Suppose for example you are wondering whether a certain die is loaded.  You don't want to crack it open, so you roll it sixty times, getting the following results:

|**Spots**|One|Two|Three|Four|Five|Six|
|:----:|:----:|:----:|:-----:|:----:|:-----:|:----:|
|**Freq**|8|18|11|7|9|7|

This looks like an awful lot of two-spots, but we were not expecting this in advance.  By this point in the course students have been made aware of the perils of "data snooping" and hence should be disinclined to employ an inferential procedure that is based specifically on a pattern that one happens to notice in one's data.  Therefore, rather than perform inferential procedures keyed to "Two-spot" side of the die, we might turn instead to the chi-square statistic as a neutral measure of the difference between the observed results and what one would expect if the die were fair.

The situation is addressed in this Shiny app:

[http://rstudio.georgetowncollege.edu:3838/SlowGoodness](http://rstudio.georgetowncollege.edu:3838/SlowGoodness)

After re-sampling for a few minutes, students are convinced that it's not so unlikely, after all to get results like the ones we observed, if the die is fair all along.

Students are then prepared to understand a full-scale re-sampling simulation like the following one:

{% highlight r %}
require(tigerstats)
{% endhighlight %}

{% highlight r %}
observed <- c(8,18,11,7,9,7)
fair <- rep(1/6,6)
set.seed(2020)
chisqtestGC(observed,p=fair,
      simulate.p.value=TRUE,
      B=3000,graph=TRUE)
{% endhighlight %}

{% highlight text %}
## Pearson's chi-squared test with simulated p-value
## 	 (based on 3000 resamples)
##
##   Observed counts Expected by Null Contr to chisq stat
## A               8               10                 0.4
## B              18               10                 6.4
## C              11               10                 0.1
## D               7               10                 0.9
## E               9               10                 0.1
## F               7               10                 0.9
##
##
## Chi-Square Statistic = 8.8
## Degrees of Freedom of the table = 5
## P-Value = 0.1253
{% endhighlight %}

![plot of chunk reasonsteachr3chisq](/knitr-jekyll/figure/source/2014-05-05-reasons-to-teach-with-R-3/reasonsteachr3chisq-1.png)

Sure enough, if the die is fair then there is a reasonably good chance---about 12.5%---of getting results at least as extreme as the ones we got in our 60 rolls.

**Note:**  Shiny users know that the apps are liable to run more quickly if you run them locally.  To run the foregoing app locally from an R session, pull it out of the `tigerstats` package:

{% highlight r %}
require(siny)
runApp(system.file("SlowGoodness",package="tigerstats"))
{% endhighlight %}

### Understanding Model Assumptions

Students tend to be somewhat rigid in their handling of "safety checks"---the diagnostics they are instructed to perform in order to judge whether the statistical model underlying a given inferential procedure is appropriate to the data at hand.  This rigidity stems partly from a lack of understanding of what the inferential procedure is intended to deliver (for example, that a method for making 95%-confidence intervals for a parameter should produce intervals that cover the parameter about 95% of the time in repeated sampling), and partly from a lack of experience with situations in which the mathematical assumptions of the model are not perfectly satisfied.

The following Shiny app:

{% highlight r %}
runApp(system.file("CIMean",package="tigerstats"))
{% endhighlight %}

addresses two learning outcomes:

* coverage properties of confidence intervals (e.g, what "95% confidence" means, from a frequentist point of view);
* the effect on coverage properties, at various sample sizes, of departures from normality assumptions in procedures based upon the t-statistic.

Both "slow" (one-at-a-time) simulation and large-scale simulation (5000 samples) are available to the student.

### Types of Error

Simulation is also helpful in coming to understand such notions as the level of significance of a hypothesis test (i.e., the probability a true Null Hypothesis in repeated sampling), and the notion of power as well.  See the following app:

{% highlight r %}
runApp(system.file("Type12Errors",package="tigerstats"))
{% endhighlight %}

### Illustrating Fine Points

Sometimes you want to have an app on hand, not because it addresses a major course objective, but simply in case students ask a particular question.  For example, sometimes when the class is looking at a scatter plot---with regression line---of data that comes from a bivariate normal distribution, a student will remark that the regression line looks "too shallow".  This root of this question is a confusion, in the student's mind, between two purposes that a line might serve:

* to provide a "linear summary"" of the scatter plot;
* to provide linear predictions, based on the scatter plot, of y-values from x-values.

The so-called "SD line"---the line that runs through the point of averages and whose slope is the ratio of the standard deviation of the $$ y $$-value to the standard deviation of the $$ x $$-value---is well-suited to the former task, whereas the regression line is, of course, the right choice for the latter one.  When many students first look at a scatter plot, they see an SD line in their mind's eye; when they get around to producing the regression line, it can look like a misfire.

The following app helps clear things up for students.  It is based on a discussion on the "shallow regression line" issue in [*Statistics*](http://books.wwnorton.com/books/Statistics/), the classic text by Freeman, Pisani and Purves.

{% highlight r %}
runApp(system.file("ShallowReg",package="tigerstats"))
{% endhighlight %}

### Playing Games

Here's is yet another of those "find the regression line" apps that you see all over the web:

{% highlight r %}
runApp(system.file("FindRegLine",package="tigerstats"))
{% endhighlight %}

You have the option to keep score.  Your score is the sum of the number of times you have submitted a guess and the following "closeness measure":

$$ 100 \times \frac{\textbf{Your Line's Error-SS}-\textbf{Residual-SS}}{\textbf{Total-SS}-\textbf{Residual-SS}}. $$

## Shiny vs. `manipulate`

You don't need to know much at all about web development in order to program in Shiny, but for R users there is the extra requirement of becoming comfortable with the reactive programming paradigm.  The hurdle is not all that high:  as an intermediate-level R-programmer, I was able to pick up Shiny over a weekend.  The [online Shiny tutorials](http://shiny.rstudio.com/tutorial/) and a few consultations with [Stack Overflow](http://stackoverflow.com/) provide almost everything I needed to know.

The pay-back for the extra learning is considerable.  Shiny apps permit a much more flexible user-interface, as compared to `manipulate`.  For example, it is easy to make input "dynamic", in the sense that the requests that a user can make of the app can be easily made to depend upon previous choices that the user has made.  It's also easy to provide plenty of written explanation for the activity, as it proceeds:  with `manipulate` apps this can be somewhat difficult.

On the other hand, since `manipulate` apps run directly within RStudio, they can easily be programmed to work with any data frame that the user specifies.  Shiny apps will allow you to upload a CSV file, but for elementary students this process is usually too much of a burden.

## Instructional Apps Gallery?

[Show Me Shiny](http://www.showmeshiny.com/) has some wonderful instructional apps.

Considering all of the buzz surrounding Shiny, I am baffled at how difficult it is has been for me to find other up-to-date sites featuring Shiny apps for statistics instruction.  Perhaps readers of this post could direct me to any that they know of.  Eventually it would be nice to develop something like a ShinyTeachingTube, which could serve as a central hub for Shiny instructional applets.


text:
package sandbox;

import com.almasb.fxgl.app.GameApplication;
import com.almasb.fxgl.app.GameSettings;
import com.almasb.fxgl.controllerinput.ControllerInputService;
import com.almasb.fxgl.dsl.components.FollowComponent;
import com.almasb.fxgl.dsl.views.MinimapView;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.input.Input;
import com.almasb.fxgl.input.UserAction;
import com.almasb.fxgl.input.virtual.VirtualButton;
import com.almasb.fxgl.physics.BoundingShape;
import com.almasb.fxgl.physics.HitBox;
import com.almasb.fxgl.physics.PhysicsComponent;
import com.almasb.fxgl.physics.box2d.dynamics.BodyType;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;

import static com.almasb.fxgl.dsl.FXGL.*;

/**
 * Sample that shows how to use ChainShape for platforms.
 *
 * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
 */
public class PlatformerSample extends GameApplication {

    private Entity player;
    private Entity poly;

    @Override
    protected void initSettings(GameSettings settings) {
        settings.setWidth(1200);
        settings.setHeight(600);
        settings.setTitle("PlatformerSample");
        settings.setVersion("0.1");
        settings.addEngineService(ControllerInputService.class);
    }

    @Override
    protected void initInput() {
        Input input = getInput();

        input.addAction(new UserAction("Left") {
            @Override
            protected void onActionBegin() {
                player.getComponent(PhysicsComponent.class).setVelocityX(-200);
            }
        }, KeyCode.A, VirtualButton.LEFT);

        input.addAction(new UserAction("Right") {
            @Override
            protected void onActionBegin() {
                player.getComponent(PhysicsComponent.class).setVelocityX(200);
            }
        }, KeyCode.D, VirtualButton.RIGHT);

        input.addAction(new UserAction("Jump") {
            @Override
            protected void onActionBegin() {
                PhysicsComponent physics = player.getComponent(PhysicsComponent.class);

                if (physics.isOnGround()) {
                    physics.setVelocityY(-500);
                }

                //getDevPane().addDebugPoint(player.getCenter());
            }
        }, KeyCode.W, VirtualButton.A);

        onKeyDown(KeyCode.I, "Info", () -> System.out.println(player.getCenter()));

        input.addAction(new UserAction("Grow") {
            @Override
            protected void onActionBegin() {

                player.setScaleX(player.getScaleX() * 1.25);
                player.setScaleY(player.getScaleY() * 1.25);

//                double x = player.getX();
//                double y = player.getY();
//
//                player.removeFromWorld();
//
//                player = createPlayer(x, y, 60, 80);
            }
        }, KeyCode.SPACE);

        input.addAction(new UserAction("Grow Poly") {
            @Override
            protected void onActionBegin() {
                poly.setScaleX(poly.getScaleX() * 1.25);
                poly.setScaleY(poly.getScaleY() * 1.25);
            }
        }, KeyCode.G);
    }

    @Override
    protected void initGame() {
        var controllerService = getService(ControllerInputService.class);
        controllerService.getGameControllers().forEach(con -> con.addInputHandler(getInput()));

        entityBuilder().buildScreenBoundsAndAttach(40);

        createPlatforms();
        player = createPlayer(100, 100, 40, 60);

        player.getTransformComponent().setScaleOrigin(new Point2D(20, 30));
        player.getComponent(PhysicsComponent.class).onGroundProperty().addListener((o, oldValue, newValue) -> {
            System.out.println(newValue ? "On Ground" : "In the air");
        });

        entityBuilder()
                .at(300, 150)
                .view(new Circle(25, Color.RED))
                .with(new FollowComponent(player, 150, 50, 60).setMoveDelay(Duration.seconds(2)))
                .buildAndAttach();
    }

    private void createPlatforms() {
        entityBuilder()
                .at(0, 500)
                .view(new Rectangle(120, 100, Color.GRAY))
                .bbox(new HitBox("Main", BoundingShape.chain(
                        new Point2D(0, 0),
                        new Point2D(120, 0),
                        new Point2D(120, 100),
                        new Point2D(0, 100)
                )))
                .with(new PhysicsComponent())
                .buildAndAttach();

        entityBuilder()
                .at(180, 500)
                .view(new Rectangle(400, 100, Color.GRAY))
                .bbox(new HitBox("Main", BoundingShape.chain(
                        new Point2D(0, 0),
                        new Point2D(400, 0),
                        new Point2D(400, 100),
                        new Point2D(0, 100)
                )))
                .with(new PhysicsComponent())
                .buildAndAttach();

        var view = new Group();

        var first = new Polygon(
                0, 0, 200, 0, 250, 100, 0, 30
        );
        first.setTranslateX(-15);
        first.setTranslateY(10);

        view.getChildren().add(first);

        Polygon second = new Polygon(
                0, -30, 30, -30, 60, 30, 0, 30
        );
        second.setTranslateX(280);
        second.setTranslateY(50);
        view.getChildren().add(second);

        var third = new Rectangle(30, 30);
        third.setTranslateX(250);
        third.setTranslateY(-30);
        view.getChildren().add(third);

        poly = entityBuilder()
                .at(180, 350)
                .view(view)
                .bbox(new HitBox("Main", new Point2D(-15, 10), BoundingShape.polygon(
                        new Point2D(0, 0),
                        new Point2D(200, 0),
                        new Point2D(250, 100),
                        new Point2D(0, 30)
                )))
                .bbox(new HitBox("2nd", new Point2D(250, -30), BoundingShape.box(30, 30)))
                //.bbox(new HitBox("4th", new Point2D(280, 0), BoundingShape.box(30, 30)))
                .bbox(new HitBox("3rd", new Point2D(280, 50), BoundingShape.polygon(
                        new Point2D(0, -30),
                        new Point2D(30, -30),
                        new Point2D(60, 30),
                        new Point2D(0, 30)
                )))
                .with(new PhysicsComponent())
                .buildAndAttach();
    }

    private Entity createPlayer(double x, double y, double width, double height) {
        PhysicsComponent physics = new PhysicsComponent();
        physics.addGroundSensor(new HitBox(new Point2D(5, height - 5), BoundingShape.box(width - 10, 10)));
        physics.setBodyType(BodyType.DYNAMIC);

        return entityBuilder()
                .at(x, y)
                .viewWithBBox(new Rectangle(width, height, Color.BLUE))
                .with(physics)
                .buildAndAttach();
    }

    @Override
    protected void initUI() {
        var minimap = new MinimapView(getGameWorld(), 800, 600, 200, 100);
        minimap.setEntityColor(Color.GREEN);

        addUINode(minimap, getAppWidth() - 210, getAppHeight() - 110);
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.parrot.arsdk.ardatatransfer"
    android:versionCode="1"
    android:versionName="1.0" >

</manifest>


text:
#pragma once

#include "modules/drivers/canbus/can_comm/protocol_data.h"
#include "modules/drivers/proto/racobit_radar.pb.h"

namespace apollo {
namespace drivers {
namespace racobit_radar {

using apollo::drivers::RacobitRadar;

class ObjectGeneralInfo60B
    : public apollo::drivers::canbus::ProtocolData<RacobitRadar> {
 public:
  static const uint32_t ID;
  ObjectGeneralInfo60B();
  void Parse(const std::uint8_t* bytes, int32_t length,
             RacobitRadar* racobit_radar) const override;

 private:
  int object_id(const std::uint8_t* bytes, int32_t length) const;

  double longitude_dist(const std::uint8_t* bytes, int32_t length) const;

  double lateral_dist(const std::uint8_t* bytes, int32_t length) const;

  double longitude_vel(const std::uint8_t* bytes, int32_t length) const;

  double lateral_vel(const std::uint8_t* bytes, int32_t length) const;

  double rcs(const std::uint8_t* bytes, int32_t length) const;

  int dynprop(const std::uint8_t* bytes, int32_t length) const;
};

}  // namespace racobit_radar
}  // namespace drivers
}  // namespace apollo


text:
from rest_framework.permissions import IsAdminUser, SAFE_METHODS

class IsAdminOrReadOnly(IsAdminUser):
    """
    Allows read-only access to all users (including anonymous users) and write access to admin users only
    """

    def has_permission(self, request, view):
        is_admin = super().has_permission(request, view)
        return is_admin or request.method in SAFE_METHODS


text:
class Soulver < Cask
  version 'latest'
  sha256 :no_check

  url 'http://www.acqualia.com/files/download.php?product=soulver'
  appcast 'http://www.acqualia.com/soulver/appcast/soulver2.xml'
  homepage 'http://www.acqualia.com/soulver/'

  link 'Soulver.app'

  after_install do
    # Don't ask to move the app bundle to /Applications
    system '/usr/bin/defaults', 'write', 'com.acqualia.soulver', 'moveToApplicationsFolderAlertSuppress', '-bool', 'true'
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>org.bridgedb.gui</artifactId>
  <name>BridgeDb GUI</name>

  <parent>
  	<artifactId>bridgedb-bundle</artifactId>
  	<groupId>org.bridgedb</groupId>
  	<version>3.0.17</version>
  </parent>

	<build>
		<directory>target</directory>
		<outputDirectory>target/classes</outputDirectory>
		<finalName>${project.artifactId}-${project.version}</finalName>
		<testOutputDirectory>target/test-classes</testOutputDirectory>
		<sourceDirectory>src</sourceDirectory>
		<scriptSourceDirectory>scripts</scriptSourceDirectory>
		<testSourceDirectory>test</testSourceDirectory>
		<resources>
			<resource>
				<directory>resources</directory>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<directory>test-data</directory>
			</testResource>
		</testResources>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>5.1.2</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-Name>org.bridgedb.gui</Bundle-Name>
                        <Bundle-SymbolicName>org.bridgedb.gui</Bundle-SymbolicName>
                        <Bundle-Version>${project.version}</Bundle-Version>
                        <Export-Package>org.bridgedb.gui</Export-Package>
                        <Require-Bundle>org.bridgedb,org.pathvisio.jgoodies.forms;bundle-version="1.2.0",org.bridgedb.rdb;resolution:=optional,org.bridgedb.webservice.bridgerest;resolution:=optional,org.bridgedb.webservice.biomart;resolution:=optional,org.bridgedb.webservice.cronos;resolution:=optional,org.bridgedb.webservice.picr;resolution:=optional,org.bridgedb.file.orthoxml;resolution:=optional,org.bridgedb.webservice.synergizer;resolution:=optional</Require-Bundle>
                        <Import-Package>com.mysql.jdbc;resolution:=optional</Import-Package>
                    </instructions>
            </configuration>
                <executions>
                    <execution>
                        <id>bundle-manifest</id>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>manifest</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <archive>
                        <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.bridgedb</groupId>
			<artifactId>org.bridgedb</artifactId>
			<version>${project.version}</version>
			<scope>compile</scope>
		</dependency>
                <dependency>
                        <groupId>com.jgoodies</groupId>
                        <artifactId>forms</artifactId>
                        <version>1.2.1</version>
                        <scope>compile</scope>
                </dependency>
	</dependencies>
</project>


text:
<?php

namespace Zmittapp\AuthBundle\Provider;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\NoResultException;

class UserProvider implements UserProviderInterface {
    protected $userRepository;

    public function __construct(ObjectRepository $userRepository){
        $this->userRepository = $userRepository;
    }

    public function loadUserByUsername($username)
    {
        $user = $this->userRepository->findOneBy(array('username' => $username));

        if(null === $user) {
            throw new UsernameNotFoundException(sprintf(
                'Unable to find an active Owner object identified by "%s".',
                $username
            ));
        }

        return $user;
    }

    public function refreshUser(UserInterface $user)
    {
        $class = get_class($user);
        if (!$this->supportsClass($class)) {
            throw new UnsupportedUserException(
                sprintf(
                    'Instances of "%s" are not supported.',
                    $class
                )
            );
        }

        return $this->userRepository->find($user->getId());
    }

    public function supportsClass($class)
    {
        return $this->userRepository->getClassName() === $class
        || is_subclass_of($class, $this->userRepository->getClassName());
    }
}


text:
/**
 * This is a factory function, returning a comparator to be used
 * in array.sort(comparator) to sort the array in descending order.
 *
 * Suitable for array consist of same type of primitives
 *
 * @since 0.0.1
 * @category Array
 *
 * @refactor April 15, 2017
 *
 * @export
 * @returns {FnSorter}
 */

import { FnSorter } from '../constants';
import { _orderBy } from '../base/_orderBy';

export const descOrder: FnSorter = (a: any, b: any) => _orderBy(b, a);


text:
<?php
	valida_acesso_admin();

	include_once 'includes/posts.inc';
	$form = include 'forms/post_form.frm';

	$categorias = load_categorias();

	$categorias_options = array();

	foreach($categorias as $categoria) {
		$categorias_options[$categoria['id']] = $categoria['nome'];
	}

	$form['criar_post']['categorias']['options'] = $categorias_options;

	$id = $params[0];

	$view_params['message'] = get_message();
	if(isset($_POST['titulo'])) {
		fill_form($form);
		if(validate_form($form)) {
			$post = form_to_simple_array($form);
			$post['id'] = $id;
			$post['ultima_atualizacao'] = date('c');
			if(save_post($post)) {
				redireciona_para("post/view/$id");
			} else {
				$view_params['message'] .= '
Nao foi possivel atualizar este post. Tente novamente.
' . get_last_error();
			}
		}
	} else {
		$post = load_post($id);
		fill_form($form, $post);
	}

	$view_params['form'] = $form;

	add_javascript('js/ckeditor/ckeditor.js');
	set_page_title('Editar post | Reino da Garotada');

	exibe_view($view_params, 'admin');
?>


text:
/**
 * @file
 * @brief Header of the `libfswatch` library functions for filter management.
 *
 * @copyright Copyright (c) 2014-2016 Enrico M. Crisostomo
 * @license GNU General Public License v. 3.0
 * @author Enrico M. Crisostomo
 * @version 1.8.0
 */

#ifndef FSW__CFILTER_H
#  define FSW__CFILTER_H
#  include "cevent.h"

#  ifdef __cplusplus
extern "C"
{
#  endif

  /**
   * @brief Event filter type.
   */
  enum fsw_filter_type
  {
    filter_include,
    filter_exclude
  };

  typedef struct fsw_cmonitor_filter
  {
    char * text;
    enum fsw_filter_type type;
    bool case_sensitive;
    bool extended;
  } fsw_cmonitor_filter;

 /**
  * @brief Event type filter.
  */
  typedef struct fsw_event_type_filter
  {
    enum fsw_event_flag flag;
  } fsw_event_type_filter;

#  ifdef __cplusplus
}
#  endif

#endif  /* FSW__CFILTER_H */


text:
require 'rails_helper'

RSpec.describe Api::V1::AddressesController do
  describe 'GET #index' do
    it 'gets all the building addresses' do
      buildings = create_list(:user_building, 2)

      get :index

      expect(json_response).not_to be_empty
      expect(json_response.map{|h| h['value']}).to eq buildings.map(&:id)
    end
  end
end


text:
"""Gets a single finalized deal for the given account and deal IDs."""

import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util

_FINALIZED_DEALS_NAME_TEMPLATE = 'buyers/%s/finalizedDeals/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_FINALIZED_DEAL_RESOURCE_ID = 'ENTER_DEAL_RESOURCE_ID_HERE'

def main(marketplace, args):
    finalized_deal_name = _FINALIZED_DEALS_NAME_TEMPLATE % (
        args.account_id, args.deal_id)

    print(f'Get finalized deal with name "{finalized_deal_name}":')
    try:
        # Construct and execute the request.
        response = marketplace.buyers().finalizedDeals().get(
            name=finalized_deal_name).execute()
    except HttpError as e:
        print(e)
        sys.exit(1)

    pprint.pprint(response)

if __name__ == '__main__':
    try:
        service = util.get_service(version='v1')
    except IOError as ex:
        print(f'Unable to create marketplace service - {ex}')
        print('Did you specify the key file in util.py?')
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description=('Get a finalized deal for the given buyer account ID and '
                     'deal ID.'))
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
        help=('The resource ID of the buyers resource for which the finalized '
              'deal is being accessed. This will be used to construct the '
              'name used as a path parameter for the finalizedDeals.get '
              'request.'))
    parser.add_argument(
        '-d', '--deal_id', default=DEFAULT_FINALIZED_DEAL_RESOURCE_ID,
        help=('The resource ID of the buyers.finalizedDeals resource that is '
              'being accessed. Note that this will be identical to the '
              'resource ID of the corresponding buyers.proposals.deals '
              'resource. This will be used to construct the name used as a '
              'path parameter for the finalizedDeals.get request.'))

    main(service, parser.parse_args())


text:
<?php
//declare(strict_types=1);

namespace PDFen\Exceptions;
// not used yet... maybe remove
class NoSuchValueException extends NoAccessException {

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.cnd.makeproject</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/make-project/1">
            <name>InputStats</name>
            <make-project-type>0</make-project-type>
            <c-extensions/>
            <cpp-extensions>cpp</cpp-extensions>
            <header-extensions/>
            <sourceEncoding>UTF-8</sourceEncoding>
            <make-dep-projects/>
        </data>
    </configuration>
</project>


text:
.. highlight:: objective-c

==================
Accessor Reference
==================

Here lists all the accessors currently available in Hydrant. Accessors
abstract the details of getting and setting values from objects so that each
:ref:`HYDMapper` does not have to implement them individually. All the functions
listed here return objects that conform to the :ref:`HYDAccessor` protocol.

You might be thinking the overload functions listed require Objective-C++, but
:ref:`clang supports function overloading <FunctionOverloading>`.

.. _HYDAccessKeyPath:
.. _HYDAccessKeyPathInArray:
.. _HYDKeyPathAccessor:

HYDAccessKeyPath
================

This accessor provides KeyPath-styled access to objects. They only support the
dot-access from KeyPath to walk nested data structures. Like :ref:`HYDAccessKey`,
this mapper will correctly convert boxed typed into their native c-types since
it internally uses ``-[valueForKey:]`` and ``-[setValue:forKey:]``.

If given ``[NSNull null]`` values, when setting values, then that **assignment
is considered a no-op**, not assigning to nil. This is because the accessor
cannot safely assign ``nil`` vs ``[NSNull null]`` (eg - property vs dictionary
key).

There is a macro to create this accessor::

    HYDAccessKeyPath(...)

Which takes a variatic sequence of NSStrings that represent the keyPaths to
walk. Giving multiple keyPaths will generate a large array value and the
expected input values when setting it too.

The macro is based off of the c function::

    HYDAccessKeyPathInArray(NSArray *keyPaths)

As the name suggests, accepts an explicit array of keyPaths.

.. _HYDAccessKey:
.. _HYDKeyAccessor:

HYDAccessKey
============

This accessor provides KVC-styled access to objects. Like :ref:`HYDAccessKeyPath`,
this mapper will correctly convert boxed typed into their native c-types since
it internally uses ``-[valueForKey:]`` and ``-[setValue:forKey:]``.

If given ``[NSNull null]`` values, when setting values, then that **assignment
is considered a no-op**, not assigning to nil. This is because the accessor
cannot safely assign ``nil`` vs ``[NSNull null]`` (eg - property vs dictionary
key).

There is a macro to create this accessor::

    HYDAccessKey(...)

Which takes a variatic sequence of NSStrings that represent the keys to
walk. Giving multiple keyPaths will generate a large array value and the
expected input values when setting it too.

The macro is based off of the c function::

    HYDAccessKeyInArray(NSArray *keyPaths)

As the name suggests, accepts an explicit array of keys.

.. _HYDAccessIndex:
.. _HYDIndexAccessor:

HYDAccessIndex
==============

.. warning:: This is feature alpha. It's API and capabilities may change
             between versions. Please avoid use if you can't accept
             instability.

This accessor provides index access to objects. This is useful for extracting
values from an array where the order has a specific, known meaning.

If given ``[NSNull null]`` values, when setting values, then that **assignment
is valid**. This is unlike the other mappers. Also, this accessor will place
add ``[NSNull null]`` instances to arrays if they do not meet the size
requirement that the accessor expects to update indicies.

There is a macro to create this accessor::

    HYDAccessIndex(...)

Which takes a variatic sequence of NSNumbers that represent the indicies to
read. Giving multiple indicies will generate a large array value and the
expected input values when setting it too.

The macro is based off of the c function::

    HYDAccessIndiciesInArray(NSArray *indicies)

As the name suggests, accepts an explicit array of indicies (NSNumbers).

.. _HYDAccessDefault:

HYDAccessDefault
================

This is a helper function that maps to the default accessor that Hydrant's
mappers prefer. Handy if you need a default but don't have an opinion for your
own mappers. Hydrant currently maps this to :ref:`HYDAccessKeyPath`.

There are two variants::

    HYDAccessDefault(NSString *field)
    HYDAccessDefault(NSArray *fields)

Which currently ties to the same behavior as ``HYDAccessKeyPath``.


text:
<?php

use \App\Migration\Migration;

class BooksChanges extends Migration
{
    public function up()
    {
        $this->execute("
ALTER TABLE `books`
	CHANGE COLUMN `book-title` `title` VARCHAR(250) NOT NULL DEFAULT '0' AFTER `id`;
        ");
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.config.security (Public javadocs 2017.4.0 API)</title>
<meta name="date" content="2017-04-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.wildfly.swarm.config.security

Interfaces

ClassicVaultConsumer

ClassicVaultSupplier

SecurityDomainConsumer

SecurityDomainSupplier

Classes

ClassicVault

SecurityDomain

SecurityDomain.SecurityDomainResources

Enums

Flag

SecurityDomain.CacheType


text:
from heat.common.i18n import _
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources.openstack.keystone import role_assignments
from heat.engine import support

class KeystoneGroup(resource.Resource,
                    role_assignments.KeystoneRoleAssignmentMixin):
    """Heat Template Resource for Keystone Group."""

    support_status = support.SupportStatus(
        version='2015.1',
        message=_('Supported versions: keystone v3'))

    default_client_name = 'keystone'

    PROPERTIES = (
        NAME, DOMAIN, DESCRIPTION
    ) = (
        'name', 'domain', 'description'
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name of keystone group.'),
            update_allowed=True
        ),
        DOMAIN: properties.Schema(
            properties.Schema.STRING,
            _('Name or id of keystone domain.'),
            default='default',
            update_allowed=True,
            constraints=[constraints.CustomConstraint('keystone.domain')]
        ),
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            _('Description of keystone group.'),
            default='',
            update_allowed=True
        )
    }

    properties_schema.update(
        role_assignments.KeystoneRoleAssignmentMixin.mixin_properties_schema)

    def validate(self):
        super(KeystoneGroup, self).validate()
        self.validate_assignment_properties()

    def _create_group(self,
                      group_name,
                      description,
                      domain):
        domain = self.client_plugin().get_domain_id(domain)

        return self.client().client.groups.create(
            name=group_name,
            domain=domain,
            description=description)

    def _delete_group(self, group_id):
        return self.client().client.groups.delete(group_id)

    def _update_group(self,
                      group_id,
                      domain,
                      new_name=None,
                      new_description=None):
        values = dict()

        if new_name is not None:
            values['name'] = new_name
        if new_description is not None:
            values['description'] = new_description

        values['group'] = group_id
        domain = self.client_plugin().get_domain_id(domain)
        values['domain_id'] = domain
        return self.client().client.groups.update(**values)

    def handle_create(self):
        group_name = (self.properties.get(self.NAME) or
                      self.physical_resource_name())
        description = self.properties.get(self.DESCRIPTION)
        domain = self.properties.get(self.DOMAIN)

        group = self._create_group(
            group_name=group_name,
            description=description,
            domain=domain
        )

        self.resource_id_set(group.id)

        self.create_assignment(group_id=group.id)

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        name = prop_diff.get(self.NAME) or self.physical_resource_name()
        description = prop_diff.get(self.DESCRIPTION)
        domain = (prop_diff.get(self.DOMAIN) or
                  self._stored_properties_data.get(self.DOMAIN))

        self._update_group(
            group_id=self.resource_id,
            new_name=name,
            new_description=description,
            domain=domain
        )

        self.update_assignment(prop_diff=prop_diff, group_id=self.resource_id)

    def handle_delete(self):
        if self.resource_id is not None:
            try:
                self.delete_assignment(group_id=self.resource_id)

                self._delete_group(group_id=self.resource_id)
            except Exception as ex:
                self.client_plugin().ignore_not_found(ex)

def resource_mapping():
    return {
        'OS::Keystone::Group': KeystoneGroup
    }


text:
using System;
using System.Xml.Linq;

namespace Prolog.Code
{
    /// <summary>
    /// Represents a <see cref="CodeValue"/> containing a <see cref="String"/> value.
    /// </summary>
    [Serializable]
    public sealed class CodeValueString : CodeValue, IEquatable<CodeValueString>, IImmuttable
    {
        #region Fields

        public new const string ElementName = "CodeValueString";

        private string m_value;

        #endregion

        #region Constructors

        public CodeValueString(string value)
        {
            if (value == null)
            {
                value = string.Empty;
            }
            m_value = value;
        }

        public static new CodeValueString Create(XElement xCodeValueString)
        {
            string value = xCodeValueString.Value;

            return new CodeValueString(value);
        }

        #endregion

        #region Public Properties

        public override object Object
        {
            get { return Value; }
        }

        public string Value
        {
            get { return m_value; }
        }

        #endregion

        #region Public Methods

        public override bool Equals(object obj)
        {
            if (obj == null) return false;

            CodeValueString rhs = obj as CodeValueString;
            if (rhs == null) return false;

            return Value == rhs.Value;
        }

        public override int GetHashCode()
        {
            return Value.GetHashCode();
        }

        public static bool operator ==(CodeValueString lhs, CodeValueString rhs)
        {
            if (object.ReferenceEquals(lhs, rhs)) return true;

            if (object.ReferenceEquals(lhs, null) || object.ReferenceEquals(rhs, null)) return false;

            return lhs.Equals(rhs);
        }

        public static bool operator !=(CodeValueString lhs, CodeValueString rhs)
        {
            return !(lhs == rhs);
        }

        public override string ToString()
        {
            string escapedString = Value.Replace(@"""", @"""""");
            return string.Format(@"""{0}""", escapedString);
        }

        public override XElement ToXElement()
        {
            return ToXElementBase(
                new XElement(ElementName, Value));
        }

        #endregion

        #region IEquatable<CodeStringConstant> Members

        public override bool Equals(CodeValue other)
        {
            return Equals(other as CodeValueString);
        }

        public bool Equals(CodeValueString other)
        {
            if (object.ReferenceEquals(other, null)) return false;

            return Value == other.Value;
        }

        #endregion
    }
}


text:
<?php

namespace Bitbucket\API\User;

use Bitbucket\API;
use Buzz\Message\MessageInterface;

/**
 * Get the details of the repositories associated with
 * an individual or team account.
 *
 * @author  Alexandru G.    <alex@gentle.ro>
 */
class Repositories extends API\Api
{
    /**
     * Get a list of repositories visible to an account
     *
     * @access public
     * @return MessageInterface
     */
    public function get()
    {
        return $this->requestGet('user/repositories');
    }

    /**
     * Get a list of repositories the account is following
     *
     * @access public
     * @return MessageInterface
     */
    public function overview()
    {
        return $this->requestGet('user/repositories/overview');
    }

    /**
     * Get the list of repositories on the dashboard
     *
     * @access public
     * @return MessageInterface
     */
    public function dashboard()
    {
        return $this->requestGet('user/repositories/dashboard');
    }
}


text:
package race // import "github.com/open-telemetry/opentelemetry-collector-contrib/processor/schemaprocessor/internal/race"

const Enabled = true


text:
layout: post
date: 2020-09-10
title: Probabilistic Inverse Graphics
inline: false
---

### Project Description
The research topic "Probabilistic Inverse Graphics problem" involves solving reconstruction problems, which are particular case of nonlinear optimisation. The way we're approaching this task is by performing search in the space of 3D shapes, representing various objects, to approximate given multi-modal data set, acquired from various sensors such as structured light, RGB camera, lidar, etc.

Impact of this research is an ability to create a system that makes 3D scene reconstructions with variable amount of details based on heterogeneous data and prior knowledge. A particular instance of such work is [1]. Currently we develop a further follow up on a similar topic.

### References
1. Avetisyan, Armen and Dahnert, Manuel and Dai, Angela and Savva, Manolis and Chang, Angel X. and Niessner, Matthias. Scan2CAD: Learning CAD Model Alignment in RGB-D Scans. The IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2019


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.futurice.vor.activity.ToiletActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/toiletTabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#F0F0F0"
            app:tabIndicatorColor="@color/colorPrimary"
            app:tabSelectedTextColor="@color/colorPrimary"
            app:tabTextColor="@color/selectedTabText"
            app:tabMode="fixed"
            app:tabGravity="fill" />

    </android.support.design.widget.AppBarLayout>

    <com.futurice.vor.view.CustomViewPager
        android:id="@+id/toiletViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>


text:
<?php

/**
 * @see Microsoft_AutoLoader
 */
require_once dirname(__FILE__) . '/../../../AutoLoader.php';

/**
 * @category   Microsoft
 * @package    Microsoft_Console
 * @copyright  Copyright (c) 2009 - 2011, RealDolmen (http://www.realdolmen.com)
 * @license    http://phpazure.codeplex.com/license
 */
class Microsoft_Console_Command_ParameterSource_StdIn
	implements Microsoft_Console_Command_ParameterSource_ParameterSourceInterface
{
	/**
	 * Get value for a named parameter.
	 *
	 * @param mixed $parameter Parameter to get a value for
	 * @param array $argv Argument values passed to the script when run in console.
	 * @return mixed
	 */
	public function getValueForParameter($parameter, $argv = array())
	{
		// Default value
		$parameterValue = null;

		// Check STDIN for data
		if (ftell(STDIN) !== false) {
			// Read from STDIN
			$fs = fopen("php://stdin", "r");
			if ($fs !== false) {
				/*
				while (!feof($fs)) {
					$data = fread($fs, 1);
					var_dump($data);
					$parameterValue .= $data;
				} */
				$parameterValue = stream_get_contents($fs);
				fclose($fs);
			}

			// Remove ending \r\n
			$parameterValue = rtrim($parameterValue);

			if (strtolower($parameterValue) == 'true') {
				$parameterValue = true;
			} else if (strtolower($parameterValue) == 'false') {
				$parameterValue = false;
			}
		}

		// Done!
		return $parameterValue;
	}
}


text:
module GxapiHelper

  #
  # Get the HTMl to load script from Google Ananlytics
  # and setChosenVariation to tell it which one we served
  #
  # @return [String] HTML
  def gxapi_experiment_js(*args)
    # extract options
    opts = args.last.is_a?(Hash) ? args.pop : {}
    # default
    ivar_name = args.first || :variant

    unless variant = self.get_this_variant(ivar_name)
      return ""
    end

    # our return value
    ret = ""
    # first time we call this, we add the script
    unless @gxapi_experiment_called == true
      ret += self.gxapi_source(opts)
      Gxapi.logger.debug {"Rendered Gxapi source"}
    end

    @gxapi_experiment_called = true
    ret += self.get_variant_js(variant)

    Gxapi.logger.debug { "#{ivar_name} is now #{variant.value.name}" }

    ret.html_safe
  end

  #
  # Get the version for a given variant
  # @return [String]
  def gxapi_variant_name(ivar_name = :variant)
    # if we have params[ivar], we just use it
    return "default" unless variant = instance_variable_get("@#{ivar_name}")
    return variant.value.try(:name) || "default"
  end

  protected

  #
  # Get the variant if it exists and has an experiment_id
  #
  # @param  ivar_name [String] Name of the instance variable for the
  # variant
  #
  # @return [Gxapi::Ostruct, false] Variant if it exists, false otherwise
  def get_this_variant(ivar_name)
    # make sure we have our variant
    unless variant = instance_variable_get("@#{ivar_name}")
      Gxapi.logger.debug { "No variant found - #{ivar_name}" }
      return false
    end
    # and a valid experiment id
    unless variant.value.experiment_id.present?
      Gxapi.logger.debug { "No experiment_id found : #{variant.value} "}
      return false
    end
    return variant
  end

  #
  # Get the JS for a variant
  #
  # @param  variant [Ostruct] Variant definition
  #
  # @return [String] JS to render
  def get_variant_js(variant)
    javascript_tag{
      "cxApi.setChosenVariation(
        #{variant.value.index},
        '#{escape_javascript(variant.value.experiment_id)}'
      );".html_safe
    }
  end

  #
  # The Javascript tag for the Content experiment API
  #
  # @param [Hash] opts Hash of options
  #
  # @return [String] HTML for the tag
  def gxapi_source(opts)
    ret = javascript_include_tag(
      "https://www.google-analytics.com/cx/api.js"
    )
    ret += "\n"
    # set domain name if present
    if opts[:domain]
      domain_call = javascript_tag{
        "cxApi.setDomainName('#{escape_javascript(opts[:domain])}');".html_safe
      }
      ret += domain_call.html_safe
      ret += "\n"
    end
    ret
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Deprecated List (Mockito 1.10.19 API)</title>
<meta name="date" content="2014-12-31">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

          Mockito 1.10.19 API

Prev

Next

Frames

No Frames

All Classes

Deprecated API

Contents

Deprecated Interfaces

Deprecated Classes

Deprecated Enums

Deprecated Annotation Types

Deprecated Methods

Deprecated Constructors

Deprecated Interfaces

Interface and Description

org.mockito.exceptions.PrintableInvocation

org.mockito.ReturnValues

Instead, please use Answer interface

 In rare cases your code might not compile with recent deprecation & changes.
 Very sorry for inconvenience but it had to be done in order to keep framework consistent.

 Why it is deprecated? ReturnValues is being replaced by Answer
 for better consistency & interoperability of the framework.
 Answer interface has been in Mockito for a while and it has the same responsibility as ReturnValues.
 There's no point in mainting exactly the same interfaces.

 Configures return values for an unstubbed invocation

 Can be used in Mockito.mock(Class, ReturnValues)

Deprecated Classes

Class and Description

org.mockito.BDDMockito.BDDOngoingStubbingImpl

not part of the public API, use BDDMockito.BDDMyOngoingStubbing instead.

org.mockito.BDDMockito.BDDStubberImpl

not part of the public API, use BDDMockito.BDDStubber instead.

org.mockito.exceptions.Discrepancy

org.mockito.exceptions.verification.junit.JUnitTool

org.mockito.runners.MockitoJUnit44Runner

org.mockito.junit.MockitoJUnitRule

org.mockito.exceptions.Pluralizer

org.mockito.stubbing.answers.ReturnsElementsOf

Use AdditionalAnswers.returnsElementsOf(java.util.Collection<?>)

Deprecated Enums

Enum and Description

org.mockito.internal.stubbing.defaultanswers.Answers

- please use Answers from top Mockito package: Answers

 WARNING Those answers no longer are used by the framework!!! Please use Answers

 See Mockito for more information.

Deprecated Annotation Types

Annotation Type and Description

org.mockito.MockitoAnnotations.Mock

Deprecated Methods

Method and Description

org.mockito.verification.VerificationWithTimeout.atMost(int)

Deprecated
 Validation with timeout combined with never simply does not make sense, as atMost() will typically immediately pass,
 and therefore not wait the timeout. The behaviour you may be looking for is actually provided by after().atMost().

 To avoid compilation errors upon upgrade the method is deprecated and it throws a "friendly reminder" exception.

 In a future release we will remove timeout(x).atMost(y) and timeout(x).never() from the API.

 Do you want to find out more? See issue 235

org.mockito.configuration.AnnotationEngine.createMockFor(Annotation, Field)

Please use AnnotationEngine.process(Class, Object) method instead that is more robust

 Creates mock, ArgumentCaptor or wraps field instance in spy object.
 Only if of correct annotation type.

org.mockito.internal.configuration.InjectingAnnotationEngine.createMockFor(Annotation, Field)

org.mockito.configuration.DefaultMockitoConfiguration.getReturnValues()

org.mockito.configuration.IMockitoConfiguration.getReturnValues()

Please use IMockitoConfiguration.getDefaultAnswer()

 Steps:

 1. Leave the implementation of getReturnValues() method empty - it's not going to be used anyway.

 2. Implement getDefaultAnswer() instead.

 In rare cases your code might not compile with recent deprecation & changes.
 Very sorry for inconvenience but it had to be done in order to keep framework consistent.

 See javadoc ReturnValues for info why this method was deprecated

 Allows configuring the default return values of unstubbed invocations

 See javadoc for IMockitoConfiguration

org.mockito.Mockito.mock(Class<T>, ReturnValues)

Please use mock(Foo.class, defaultAnswer);

org.mockito.verification.VerificationWithTimeout.never()

Validation with timeout combined with never simply does not make sense, as never() will typically immediately pass,
 and therefore not wait the timeout. The behaviour you may be looking for is actually provided by after().never().

 To avoid compilation errors upon upgrade the method is deprecated and it throws a "friendly reminder" exception.

 In a future release we will remove timeout(x).atMost(y) and timeout(x).never() from the API.

 Do you want to find out more? See issue 235

org.mockito.Mockito.stubVoid(T)

Use Mockito.doThrow(Throwable) method for stubbing voids

Deprecated Constructors

Constructor and Description

org.mockito.ArgumentCaptor()

Please use factory method ArgumentCaptor.forClass(Class) to create captors

 This is required to avoid NullPointerExceptions when autoUnboxing primitive types.
 See issue 99.

 Example:

   ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
   verify(mock).doSomething(argument.capture());
   assertEquals("John", argument.getValue().getName());

org.mockito.junit.MockitoJUnitRule()

org.mockito.junit.MockitoJUnitRule(Object)

org.mockito.stubbing.answers.ReturnsElementsOf(Collection<?>)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

          Mockito 1.10.19 API

Prev

Next

Frames

No Frames

All Classes


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

namespace MGR.CommandLineParser.UnitTests.Extensions
{
    public partial class TypeExtensionsTests
    {
        public class IsMultiValuedType
        {
            [Fact]
            public void ListIntTest()
            {
                // Arrange
                var testedType = typeof (List<int>);
                var expected = true;

                // Act
                var actual = testedType.IsMultiValuedType();

                // Assert
                Assert.Equal(expected, actual);
            }

            [Fact]
            public void TupleInt()
            {
                // Arrange
                var testedType = typeof (Tuple<int>);
                var expected = false;

                // Act
                var actual = testedType.IsMultiValuedType();

                // Assert
                Assert.Equal(expected, actual);
            }

            [Fact]
            public void DictionaryStringInt()
            {
                // Arrange
                var testedType = typeof (Dictionary<string, int>);
                var expected = true;

                // Act
                var actual = testedType.IsMultiValuedType();

                // Assert
                Assert.Equal(expected, actual);
            }

            [Fact]
            // ReSharper disable once InconsistentNaming
            public void IDictionaryStringInt()
            {
                // Arrange
                var testedType = typeof (IDictionary<string, int>);
                var expected = true;

                // Act
                var actual = testedType.IsMultiValuedType();

                // Assert
                Assert.Equal(expected, actual);
            }

            [Fact]
            public void NullTypeException()
            {
                // Arrange
                Type testedType = null;
                var expectedExceptionMessage = SourceParameterName;

                // Act
                // ReSharper disable once ExpressionIsAlwaysNull
                var actualException = Assert.Throws<ArgumentNullException>(() => testedType.IsMultiValuedType());

                // Assert
                Assert.Equal(expectedExceptionMessage, actualException.ParamName);
            }
        }
    }
}


text:
import './dashboard.component.css';

export const DashboardComponent  = {
    template: require('./dashboard.component.html'),
    controllerAs: 'vm',
    controller: class DashboardComponent {
        constructor(ProfileService, $scope, AnnouncementService, $state, FirebaseService) {
            'ngInject';
            this.profileService = ProfileService;
            this.announcementService = AnnouncementService;
            this.firebaseService = FirebaseService;
            this.$scope = $scope;
            this.$state = $state;
        }

        $onInit() {
            this.users = [];
            this.profileService.getNeighbhoods((position)=>{
                this.$scope.$apply(() =>{
                    this.users.push(position);
                });
            });

            this.announcements = [];
            this.announcementService.getMyInvintesStream((announcement) => {
                this.$scope.$apply(() => {
                    this.announcements.unshift(announcement);
                });
            });
        }

        join(announcement) {
            this.announcementService.join(announcement)
                .then(()=>{
                    this.$state.go('modules.announcements.show.details', {id: announcement.key})
                })
        }

        showAnnouncment(announcement){
            if(announcement && !announcement.users){
                return true;
            } else if(announcement && announcement.users &&
                !announcement.users.hasOwnProperty(this.firebaseService.auth.currentUser.uid)) {
                return true;
            } else {
                return false;
            }
        }

        getAnnouncementMessage(type){
            if(type == 'near'){
                return "esta procurando alguém para"
            }
        }
    }
};


text:
/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
.carousel {
	width: 440px;
}
.carousel-caption {
	color: maroon;
	bottom: -130px;
}
.carousel .item {
	text-align: center;
}
.carousel-inner {
	padding-bottom: 170px;
}
.carousel-inner > .item > img {
	margin: 0 auto;
}
.carousel-indicators li {
	background-color: rgba(255, 255, 255, 0);
    border: 1px solid #000;
}

/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */
body, #bestsellers, #shop {
	padding-top: 40px;
}
h1, h2 {
	color: #613A67;
}
.featurette-heading {
	color: #333;
}
.navbar-inverse {
	background-image: -webkit-linear-gradient(top, #613A67 0%, #B7ADD2 100%);
	background-image:         linear-gradient(to bottom, #613A67 0%, #B7ADD2 100%);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff613A67', endColorstr='#ffB7ADD2', GradientType=0);
	background-repeat: repeat-x;
	border-color: #613A67;
}
.navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-toggle:hover, .navbar-inverse .navbar-toggle:focus {
	background-image: -webkit-linear-gradient(top, #B7ADD2 0%, #613A67 100%);
	background-image:         linear-gradient(to bottom, #B7ADD2 0%, #613A67 100%);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff613A67', endColorstr='#ffB7ADD2', GradientType=0);
	background-repeat: repeat-x;
}
.navbar-inverse .navbar-brand,
.navbar-inverse .navbar-nav > li > a {
	text-shadow: none;
	color: #fff;
}
.navbar-inverse .navbar-toggle {
	border-color: #613A67;
}
.navbar .pull-right {
    padding-top: 16px;
}
#like {
	padding-top: 40px;
	padding-bottom: 10px;
}
.carousel-control-extra-wrapper {
	bottom: 10px;
    left: 50%;
    margin-left: -30%;
    padding-left: 0;
    position: absolute;
    text-align: center;
    width: 60%;
    z-index: 15;
}
.carousel-control-extra, span[class*="chevron-"] {
	cursor: pointer;
}
span[class^="chevron-"] {
	color: #428bca;
}
#cart-wrapper .table > thead > tr > th {
	vertical-align: top;
}
.cart-item-amount {
	width: 64px !important;
}
.cart-item-amount-group label {
	font-weight: normal;
}
#cart-item-size {
	max-width: 220px !important;
}
#cart-item-promocode {
	width: 130px;
}
.dashed-link {
    border-bottom-style: dashed;
    border-bottom-width: 1px;
    text-decoration: none;
    white-space: nowrap;
}
.dashed-link:hover {
	text-decoration: none;
}
.price, #blueimp-gallery .modal-title {
	color: maroon;
}
.zoom-in {
	cursor: -webkit-zoom-in;
	cursor: zoom-in;
}
.well {
	max-width: 700px;
}
#links a:hover {
	text-decoration: none;
	opacity: 0.7;
}
input[name$="[math]"] {
	width: 100px;
}
#footer {
	background-image: -webkit-linear-gradient(top, #B7ADD2 0%, #613A67 100%);
	background-image:         linear-gradient(to bottom, #B7ADD2 0%, #613A67 100%);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffB7ADD2', endColorstr='#ff613A67', GradientType=0);
	background-repeat: repeat-x;
}
#footer .text-muted {
	margin: 20px 0;
	color: #333;
}
#footer .text-muted small, #footer .text-muted a {
	color: #333;
}
#footer .text-muted a {
	text-decoration: underline;
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MultiChainLib.Harness
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var task = Task.Run(async () =>
                {
                    await new Complete().RunAsync();
//                    await new Example().RunAsync();
                });
                task.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine("**********************");
                Console.WriteLine(ex);
            }
            finally
            {
                if (Debugger.IsAttached)
                    Console.ReadLine();
            }
        }
    }
}