text:
//  Copyright (c) 2014 Marty Schoch
//  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.

package gouchstore

import (
	"bytes"
	"fmt"
	"sort"
)

const gs_DB_CHUNK_THRESHOLD int = 1279

type btreeFetchCallback func(req *modifyRequest, k []byte, v []byte, context interface{})
type btreePurgeKPFunc func(np *nodePointer, context interface{}) int
type btreePurgeKVFunc func(key, val []byte, context interface{}) int

type nodeList struct {
	data    []byte
	key     []byte
	pointer *nodePointer
	next    *nodeList
}

type indexUpdateContext struct {
	seqacts []modifyAction
	actpos  int
	seqs    [][]byte
	seqvals [][]byte
	valpos  int
}

const (
	gs_ACTION_FETCH  int = 0
	gs_ACTION_REMOVE int = 1
	gs_ACTION_INSERT int = 2
)

const (
	gs_PURGE_ITEM    int = 0
	gs_PURGE_STOP    int = 1
	gs_PURGE_KEEP    int = 2
	gs_PURGE_PARTIAL int = 3
)

const (
	gs_KP_NODE int = 0
	gs_KV_NODE int = 1
)

type modifyAction struct {
	typ   int
	key   []byte
	value []byte
	arg   interface{}
}

type modifyRequest struct {
	cmp                btreeKeyComparator
	actions            []modifyAction
	fetchCallback      btreeFetchCallback
	reduce             reduceFunc
	rereduce           reduceFunc
	reduceContext      interface{}
	kvChunkThreshold   int
	kpChunkThreshold   int
	compacting         bool
	purgeKP            btreePurgeKPFunc
	purgeKV            btreePurgeKVFunc
	enablePurging      bool
	guidedPurgeContext interface{}
}

type modifyResult struct {
	request     *modifyRequest
	values      *nodeList
	valuesEnd   *nodeList
	nodeLen     int64
	count       int
	pointers    *nodeList
	pointersEnd *nodeList
	modified    bool
	nodeType    int
	errState    int
}

func (g *Gouchstore) addDocToUpdateList(doc *Document, docInfo *DocumentInfo, seq uint64) ([]byte, []byte, []byte, []byte, error) {
	updated := *docInfo
	updated.Seq = seq
	seqterm := encode_raw48(seq)

	if doc != nil {
		var diskSize uint64

		err := g.writeDoc(doc, &updated.bodyPosition, &diskSize, docInfo.compressed())
		if err != nil {
			return nil, nil, nil, nil, err
		}

		updated.Size = diskSize
	} else {
		updated.Deleted = true
		updated.bodyPosition = 0
		updated.Size = 0
	}

	idterm := []byte(updated.ID)
	seqval := updated.encodeBySeq()
	idval := updated.encodeById()

	return seqterm, idterm, seqval, idval, nil
}

func (g *Gouchstore) writeDoc(doc *Document, bp *uint64, diskSize *uint64, compress bool) error {
	var err error
	var pos, size int64
	if compress {
		pos, size, err = g.writeCompressedChunk(doc.Body)
	} else {
		pos, size, err = g.writeChunk(doc.Body, false)
	}
	if err != nil {
		return err
	}
	if bp != nil {
		*bp = uint64(pos)
	}
	if diskSize != nil {
		*diskSize = uint64(size)
	}
	return nil
}

func idFetchUpdate(req *modifyRequest, k []byte, v []byte, context interface{}) {
	indexUpdateContext := context.(*indexUpdateContext)
	if v == nil {
		return // doc not found
	}

	raw := DocumentInfo{}
	decodeByIdValue(&raw, v)
	oldseq := raw.Seq

	indexUpdateContext.seqacts[indexUpdateContext.actpos].typ = gs_ACTION_REMOVE
	indexUpdateContext.seqacts[indexUpdateContext.actpos].value = nil
	indexUpdateContext.seqacts[indexUpdateContext.actpos].key = encode_raw48(oldseq)
	indexUpdateContext.actpos++
}

func (g *Gouchstore) updateIndexes(seqs, seqvals, ids, idvals [][]byte) error {
	var fetcharg indexUpdateContext
	var seqrq, idrq modifyRequest

	numdocs := len(seqs)
	idacts := make([]modifyAction, 2*numdocs)
	seqacts := make([]modifyAction, 2*numdocs)

	fetcharg.seqacts = seqacts
	fetcharg.actpos = 0
	fetcharg.seqs = seqs
	fetcharg.seqvals = seqvals
	fetcharg.valpos = 0

	// sort the ids
	sortedIds := idAndValueList{
		ids:  ids,
		vals: idvals,
	}
	sort.Sort(sortedIds)

	for i := 0; i < numdocs; i++ {
		idacts[i*2].typ = gs_ACTION_FETCH
		idacts[(i * 2)].key = ids[i]
		idacts[i*2].arg = &fetcharg
		idacts[(i*2)+1].typ = gs_ACTION_INSERT
		idacts[(i*2)+1].key = ids[i]
		idacts[(i*2)+1].value = idvals[i]
	}

	idrq.cmp = gouchstoreIdComparator
	idrq.actions = idacts
	idrq.reduce = byIdReduce
	idrq.rereduce = byIdReReduce
	idrq.fetchCallback = idFetchUpdate
	idrq.compacting = false
	idrq.enablePurging = false
	idrq.purgeKP = nil
	idrq.purgeKV = nil
	idrq.kpChunkThreshold = gs_DB_CHUNK_THRESHOLD
	idrq.kvChunkThreshold = gs_DB_CHUNK_THRESHOLD

	newIdRoot, err := g.modifyBtree(&idrq, g.header.byIdRoot)
	if err != nil {
		return err
	}

	for fetcharg.valpos < numdocs {
		seqacts[fetcharg.actpos].typ = gs_ACTION_INSERT
		seqacts[fetcharg.actpos].value = seqvals[fetcharg.valpos]
		seqacts[fetcharg.actpos].key = seqs[fetcharg.valpos]
		fetcharg.valpos++
		fetcharg.actpos++
	}

	// we need to resize seqacts, as it was oversized intially
	// which leaves around invalid actions
	// FIXME evaluate for cleaner/faster way to do this
	seqacts = append([]modifyAction{}, seqacts[:fetcharg.actpos]...)
	sortedSeqActs := seqModifyActionList(seqacts)
	sort.Sort(sortedSeqActs)

	seqrq.cmp = gouchstoreSeqComparator
	seqrq.actions = seqacts
	seqrq.reduce = bySeqReduce
	seqrq.rereduce = bySeqReReduce
	seqrq.compacting = false
	seqrq.enablePurging = false
	seqrq.purgeKP = nil
	seqrq.purgeKV = nil
	seqrq.kpChunkThreshold = gs_DB_CHUNK_THRESHOLD
	seqrq.kvChunkThreshold = gs_DB_CHUNK_THRESHOLD

	newSeqRoot, err := g.modifyBtree(&seqrq, g.header.bySeqRoot)
	if err != nil {
		return err
	}

	if g.header.byIdRoot != newIdRoot {
		g.header.byIdRoot = newIdRoot
	}

	if g.header.bySeqRoot != newSeqRoot {
		g.header.bySeqRoot = newSeqRoot
	}

	return nil
}

func (g *Gouchstore) modifyBtree(req *modifyRequest, np *nodePointer) (*nodePointer, error) {
	var retPtr *nodePointer = np
	var err error
	rootResult := makeModifyResult(req)
	rootResult.nodeType = gs_KP_NODE

	err = g.modifyNode(req, np, 0, len(req.actions), rootResult)
	if err != nil {
		return nil, err
	}

	val := rootResult.values
	for val != nil {
		val = val.next
	}

	if rootResult.valuesEnd.pointer == np {
		//If we got the root pointer back, remove it from the list
		//so we don't try to free it.
		rootResult.valuesEnd.pointer = nil
	}

	if rootResult.modified {
		if rootResult.count > 1 || rootResult.pointers != rootResult.pointersEnd {
			//The root was split
			//Write it to disk and return the pointer to it.
			retPtr, err = g.finishRoot(req, rootResult)
			if err != nil {
				return nil, err
			}
		} else {
			retPtr = rootResult.valuesEnd.pointer
		}
	}

	return retPtr, nil
}

func (g *Gouchstore) modifyNode(req *modifyRequest, np *nodePointer, start, end int, dst *modifyResult) error {
	var nodebuf []byte
	var err error
	var bufpos int = 1
	var nodebuflen int = 0
	if start == end {
		return nil
	}

	if np != nil {
		nodebuf, err = g.readCompressedDataChunkAt(int64(np.pointer))
		if err != nil {
			return err
		}
		nodebuflen = len(nodebuf)
	}

	localResult := makeModifyResult(req)
	val := localResult.values
	for val != nil {
		val = val.next
	}

	if np == nil || nodebuf[0] == 1 { // KV Node
		localResult.nodeType = gs_KV_NODE
		for bufpos < nodebuflen {
			var cmpKey, valBuf []byte
			cmpKey, valBuf, bufpos = decodeKeyValue(nodebuf, bufpos)
			advance := false
			for !advance && start < end {
				advance = true
				cmpVal := req.cmp(cmpKey, req.actions[start].key)

				if cmpVal < 0 { // Key less than action key
					err = g.maybePurgeKV(req, cmpKey, valBuf, localResult)
					if err != nil {
						return err
					}
				} else if cmpVal > 0 { // Key greater than action key
					switch req.actions[start].typ {
					case gs_ACTION_INSERT:
						localResult.modified = true
						g.mrPushItem(req.actions[start].key, req.actions[start].value, localResult)
					case gs_ACTION_REMOVE:
						localResult.modified = true
					case gs_ACTION_FETCH:
						if req.fetchCallback != nil {
							// not found
							req.fetchCallback(req, req.actions[start].key, nil, req.actions[start].arg)
						}
					}
					start++
					// Do next action on same item in the node, as our action was
					// not >= it.
					advance = false
				} else if cmpVal == 0 { // Node key is equal to action key
					switch req.actions[start].typ {
					case gs_ACTION_INSERT:
						localResult.modified = true
						g.mrPushItem(req.actions[start].key, req.actions[start].value, localResult)
					case gs_ACTION_REMOVE:
						localResult.modified = true
					case gs_ACTION_FETCH:
						if req.fetchCallback != nil {
							req.fetchCallback(req, req.actions[start].key, valBuf, req.actions[start].arg)
						}
						// Do next action on same item in the node, as our action was a fetch
						// and there may be an equivalent insert or remove
						// following.
						advance = false
					}
					start++
				}
			}
			if start == end && !advance {
				// If we've exhausted actions then just keep this key
				err = g.maybePurgeKV(req, cmpKey, valBuf, localResult)
				if err != nil {
					return err
				}
			}
		}
		for start < end {
			// We're at the end of a leaf node.
			switch req.actions[start].typ {
			case gs_ACTION_INSERT:
				localResult.modified = true
				g.mrPushItem(req.actions[start].key, req.actions[start].value, localResult)
			case gs_ACTION_REMOVE:
				localResult.modified = true
			case gs_ACTION_FETCH:
				if req.fetchCallback != nil {
					// not found
					req.fetchCallback(req, req.actions[start].key, nil, req.actions[start].arg)
				}
			}
			start++
		}
	} else if nodebuf[0] == 0 { // KP Node
		localResult.nodeType = gs_KP_NODE
		for bufpos < nodebuflen && start < end {
			var cmpKey, valBuf []byte
			cmpKey, valBuf, bufpos = decodeKeyValue(nodebuf, bufpos)
			cmpVal := req.cmp(cmpKey, req.actions[start].key)
			if bufpos == nodebuflen {
				// We're at the last item in the kpnode, must apply all our
				// actions here.
				desc := decodeNodePointer(valBuf)
				desc.key = cmpKey

				err = g.modifyNode(req, desc, start, end, localResult)
				if err != nil {
					return nil
				}
				break
			}

			if cmpVal < 0 {
				// Key in node item less than action item and not at end
				// position, so just add it and continue.
				add := decodeNodePointer(valBuf)
				add.key = cmpKey

				err := g.maybePurgeKP(req, add, localResult)
				if err != nil {
					return err
				}
			} else if cmpVal >= 0 {
				// Found a key in the node greater than the one in the current
				// action. Descend into the pointed node with as many actions as
				// are less than the key here.
				rangeEnd := start
				for rangeEnd < end && req.cmp(req.actions[rangeEnd].key, cmpKey) <= 0 {
					rangeEnd++
				}

				desc := decodeNodePointer(valBuf)
				desc.key = cmpKey

				err := g.modifyNode(req, desc, start, rangeEnd, localResult)
				start = rangeEnd
				if err != nil {
					return err
				}
			}
		}
		for bufpos < nodebuflen {
			var cmpKey, valBuf []byte
			cmpKey, valBuf, bufpos = decodeKeyValue(nodebuf, bufpos)
			add := decodeNodePointer(valBuf)
			add.key = cmpKey

			err := g.maybePurgeKP(req, add, localResult)
			if err != nil {
				return err
			}
		}
	} else {
		return gs_ERROR_CORRUPT
	}
	val = localResult.values
	for val != nil {
		val = val.next
	}
	// If we've done modifications, write out the last leaf node.
	err = g.flushMR(localResult)
	if err != nil {
		return err
	}
	val = localResult.values
	for val != nil {
		val = val.next
	}
	ptr := localResult.pointers
	for ptr != nil {
		ptr = ptr.next
	}
	if !localResult.modified && np != nil {
		// If we didn't do anything, give back the pointer to the original
		g.mrPushPointerInfo(np, dst)
	} else {
		// Otherwise, give back the pointers to the nodes we've created.
		dst.modified = true
		err = g.mrMovePointers(localResult, dst)
		if err != nil {
			return err
		}
	}

	return nil
}

func (g *Gouchstore) mrMovePointers(src *modifyResult, dst *modifyResult) error {
	var err error
	if src.pointersEnd == src.pointers {
		return err
	}

	ptr := src.pointers.next
	next := ptr
	for ptr != nil && err == nil {
		dst.nodeLen += int64(len(ptr.data) + len(ptr.key) + gs_KEY_VALUE_LEN)
		dst.count++

		next = ptr.next
		ptr.next = nil

		dst.valuesEnd.next = ptr
		dst.valuesEnd = ptr
		ptr = next
		err = g.maybeFlush(dst)
	}

	src.pointers.next = next
	src.pointersEnd = src.pointers
	return err
}

// Write a node using enough items from the values list to create a node
// with uncompressed size of at least mr_quota
func (g *Gouchstore) flushMRPartial(res *modifyResult, quota int64) error {
	var err error
	itemCount := 0
	nodebuf := new(bytes.Buffer)
	var subtreesize uint64 = 0
	var diskpos int64 = 0
	var disksize int64 = 0
	var finalKey []byte
	var reduceBuf []byte

	if !res.modified || res.valuesEnd == res.values {
		//Empty
		return nil
	}

	nodebuf.Write([]byte{byte(res.nodeType)})

	i := res.values.next

	//We don't care that we've reached mr_quota if we haven't written out
	//at least two items and we're not writing a leaf node.
	for i != nil && (quota > 0 || itemCount < 2 && res.nodeType == gs_KP_NODE) {
		nodebuf.Write(encodeKeyValue(i.key, i.data))
		if i.pointer != nil {
			subtreesize += i.pointer.subtreeSize
		}
		quota -= int64(len(i.key) + len(i.data) + gs_KEY_VALUE_LEN)
		finalKey = i.key
		i = i.next
		res.count--
		itemCount++
	}

	diskpos, disksize, err = g.writeCompressedChunk(nodebuf.Bytes())
	if err != nil {
		return err
	}

	if res.nodeType == gs_KV_NODE && res.request.reduce != nil {
		reduceBuf, err = res.request.reduce(res.values.next, itemCount, res.request.reduceContext)
		if err != nil {
			return err
		}
	}

	if res.nodeType == gs_KP_NODE && res.request.rereduce != nil {
		reduceBuf, err = res.request.rereduce(res.values.next, itemCount, res.request.reduceContext)
		if err != nil {
			return err
		}
	}

	// build new node pointer
	ptr := &nodePointer{
		key:          finalKey,
		pointer:      uint64(diskpos),
		reducedValue: reduceBuf,
		subtreeSize:  subtreesize + uint64(disksize),
	}

	// encode it as node list
	rawBytes := ptr.encode()
	pel := makeNodeList()
	pel.data = rawBytes
	pel.key = ptr.key
	pel.pointer = ptr

	res.pointersEnd.next = pel
	res.pointersEnd = pel

	res.nodeLen -= int64(nodebuf.Len() - 1) // FIXME why -1 here?

	res.values.next = i
	if i == nil {
		res.valuesEnd = res.values
	}

	return nil
}

func (g *Gouchstore) maybeFlush(mr *modifyResult) error {
	if mr.request.compacting {
		/* The compactor can (and should), just write out nodes
		 * of size CHUNK_SIZE as soon as it can, so that it can
		 * free memory it no longer needs. */
		if mr.modified &&
			(((mr.nodeType == gs_KV_NODE) && mr.nodeLen > int64(mr.request.kvChunkThreshold*2/3)) ||
				((mr.nodeType == gs_KP_NODE) && mr.nodeLen > int64(mr.request.kpChunkThreshold*2/3))) {
			return g.flushMR(mr)
		}

	} else if mr.modified && mr.count > 3 {
		/* Don't write out a partial node unless we've collected
		 * at least three items */
		if mr.nodeType == gs_KV_NODE && mr.nodeLen > int64(mr.request.kvChunkThreshold) {
			return g.flushMRPartial(mr, int64(mr.request.kvChunkThreshold*2/3))
		}
		if mr.nodeType == gs_KP_NODE && mr.nodeLen > int64(mr.request.kpChunkThreshold) {
			return g.flushMRPartial(mr, int64(mr.request.kpChunkThreshold*2/3))
		}
	}
	return nil
}

func (g *Gouchstore) mrPushPointerInfo(ptr *nodePointer, dst *modifyResult) error {
	rawBytes := ptr.encode()
	pel := makeNodeList()
	pel.data = rawBytes
	pel.key = ptr.key
	pel.pointer = ptr

	dst.valuesEnd.next = pel
	dst.valuesEnd = pel
	dst.nodeLen += int64(len(pel.key) + len(pel.data) + gs_KEY_VALUE_LEN)
	dst.count++

	return g.maybeFlush(dst)
}

func (g *Gouchstore) flushMR(res *modifyResult) error {
	return g.flushMRPartial(res, res.nodeLen)
}

func (g *Gouchstore) mrPushItem(key, val []byte, dst *modifyResult) error {
	itm := makeNodeList()
	itm.key = key
	itm.data = val
	itm.pointer = nil
	dst.valuesEnd.next = itm
	dst.valuesEnd = itm
	// Encoded size (see flush_mr)
	dst.nodeLen += int64(len(key) + len(val) + gs_KEY_VALUE_LEN)
	dst.count++
	return g.maybeFlush(dst)
}

func (g *Gouchstore) finishRoot(req *modifyRequest, rootResult *modifyResult) (*nodePointer, error) {
	var retPtr *nodePointer
	collector := makeModifyResult(req)
	collector.modified = true
	collector.nodeType = gs_KP_NODE
	g.flushMR(rootResult)
	for {
		if rootResult.pointersEnd == rootResult.pointers.next {
			// The root result split into exactly one kp_node.
			// Return the pointer to it.
			retPtr = rootResult.pointersEnd.pointer
			break
		} else {
			// The root result split into more than one kp_node.
			// Move the pointer list to the value list and write out the new node.
			err := g.mrMovePointers(rootResult, collector)
			if err != nil {
				return nil, err
			}

			err = g.flushMR(collector)
			if err != nil {
				return nil, err
			}

			// Swap root_result and collector mr's.
			tmp := rootResult
			rootResult = collector
			collector = tmp
		}
	}
	return retPtr, nil
}

// Perform purging for a kv-node if it qualifies for purging
func (g *Gouchstore) maybePurgeKV(req *modifyRequest, key, val []byte, res *modifyResult) error {
	var action int
	var err error
	if req.enablePurging && req.purgeKV != nil {
		action = req.purgeKV(key, val, req.guidedPurgeContext)
		if action < 0 {
			return fmt.Errorf("purge action failed: %d", action)
		}
	} else {
		action = gs_PURGE_KEEP
	}

	switch action {
	case gs_PURGE_ITEM:
		res.modified = true
	case gs_PURGE_STOP:
		req.enablePurging = false
	case gs_PURGE_KEEP:
		err = g.mrPushItem(key, val, res)
	}
	return err
}

func (g *Gouchstore) maybePurgeKP(req *modifyRequest, np *nodePointer, res *modifyResult) error {
	var action int
	var err error
	if req.enablePurging && req.purgeKP != nil {
		action = req.purgeKP(np, req.guidedPurgeContext)
		if action < 0 {
			return fmt.Errorf("purge action failed: %d", action)
		}
	} else {
		action = gs_PURGE_KEEP
	}

	switch action {
	case gs_PURGE_ITEM:
		res.modified = true
	case gs_PURGE_PARTIAL:
		err = g.purgeNode(req, np, res)
	case gs_PURGE_STOP:
		req.enablePurging = false
	case gs_PURGE_KEEP:
		err = g.mrPushPointerInfo(np, res)
	}
	return err
}

func (g *Gouchstore) purgeNode(req *modifyRequest, np *nodePointer, dst *modifyResult) error {
	var err error
	var nodebuf []byte
	var localResult *modifyResult
	bufpos := 1
	nodebuflen := 0

	if np == nil {
		return err
	}

	// noop: add back current node to destination
	if !req.enablePurging {
		dst.modified = true
		return g.mrPushPointerInfo(np, dst)
	}

	nodebuf, err = g.readCompressedDataChunkAt(int64(np.pointer))
	if err != nil {
		return err
	}
	nodebuflen = len(nodebuf)

	localResult = makeModifyResult(req)
	if nodebuf[0] == 1 { //KV Node
		localResult.nodeType = gs_KV_NODE
		for bufpos < nodebuflen {
			var cmpKey, valBuf []byte
			cmpKey, valBuf, bufpos = decodeKeyValue(nodebuf, bufpos)
			err = g.maybePurgeKV(req, cmpKey, valBuf, localResult)
			if err != nil {
				return err
			}
		}

	} else if nodebuf[0] == 0 { //KP Node
		localResult.nodeType = gs_KP_NODE
		for bufpos < nodebuflen {
			cmpKey, valBuf, posOffset := decodeKeyValue(nodebuf, bufpos)
			bufpos += posOffset

			desc := decodeNodePointer(valBuf)
			desc.key = cmpKey

			err = g.maybePurgeKP(req, desc, localResult)
			if err != nil {
				return err
			}
		}

	} else {
		return gs_ERROR_CORRUPT
	}

	// Write out changes and add node back to parent
	if localResult.modified {
		err = g.flushMR(localResult)
		if err != nil {
			return err
		}
		dst.modified = true
		err = g.mrMovePointers(localResult, dst)
		if err != nil {
			return err
		}
	}

	return nil
}

func makeModifyResult(req *modifyRequest) *modifyResult {
	v := makeNodeList()
	p := makeNodeList()
	rv := modifyResult{
		values:      v,
		valuesEnd:   v,
		pointers:    p,
		pointersEnd: p,
		nodeLen:     0,
		request:     req,
	}
	return &rv
}

func newBtreeModifyResult(cmp btreeKeyComparator, reduce reduceFunc, rereduce reduceFunc, reduceContext interface{}, kvChunkThreshold, kpChunkThreshold int) *modifyResult {
	rq := modifyRequest{
		cmp:              cmp,
		actions:          []modifyAction{},
		fetchCallback:    nil,
		reduce:           reduce,
		rereduce:         rereduce,
		reduceContext:    reduceContext,
		compacting:       true,
		enablePurging:    false,
		purgeKP:          nil,
		purgeKV:          nil,
		kvChunkThreshold: kvChunkThreshold,
		kpChunkThreshold: kpChunkThreshold,
	}

	mr := makeModifyResult(&rq)
	mr.modified = true
	mr.nodeType = gs_KV_NODE

	return mr
}

func makeNodeList() *nodeList {
	rv := nodeList{}
	return &rv
}

func (g *Gouchstore) completeNewBtree(mr *modifyResult) (*nodePointer, error) {
	err := g.flushMR(mr)
	if err != nil {
		return nil, err
	}

	targMr := makeModifyResult(mr.request)
	targMr.modified = true
	targMr.nodeType = gs_KP_NODE

	err = g.mrMovePointers(mr, targMr)
	if err != nil {
		return nil, err
	}

	var retPtr *nodePointer
	if targMr.count > 1 || targMr.pointers != targMr.pointersEnd {
		retPtr, err = g.finishRoot(mr.request, targMr)
		if err != nil {
			return nil, err
		}
	} else {
		retPtr = targMr.valuesEnd.pointer
	}

	return retPtr, nil
}


text:
If you do not have either installed, go to the respective links to set them up: https://www.vagrantup.com/downloads.html and https://www.virtualbox.org/wiki/Downloads

If you have either of those installed, please make sure that they are both up to date!

## Download Scotchbox

To download Scotchbox you will need to have access to Git. If you don't please download git at the following link: https://git-scm.com/downloads

On the command line, type cd into the directory where you would like your sites stored and copy and paste `git clone https://github.com/scotch-io/scotch-box.git my-project`. Replace `my-project` with whatever you'd like to name this. I have named my repository `Drupal-8-Demo`

## Run Vagrant

`cd` into your new project clone and run `vagrant up`. Depending on your computer, this can take a bit of time, so be patient! If you set up your site successfully, you can go to 192.168.33.10 and see a scotchbox site!

## Setting up Database access

If you have a Mac, I would highly recommend downloading SequelPro https://sequelpro.com/. If you have a Windows, I hear Navicat is good as well https://www.navicat.com/download. Once you download that, navigate to the program and setup your database (SSH Connection) with the following credentials:

- Name: Scotchbox/Vagrant/Whaever you want to call it
- Host: 127.0.0.1
- Database Name: (leave blank)
- Database User: root
- Database Password: root
- SSH Host: 192.168.33.10
- SSH User: vagrant
- SSH Password: vagrant

Now you should be able to connect to MySQL. You can either create a database using your respective programs, or you can do it manually through your vagrant box. To set it up manually:

- Make sure you are in your vagrant box. From your vagrant directory type: `vagrant ssh` and press enter.
- Once you are in your box, type `mysql` and press enter
- To see what databases exist, type `SHOW DATABASES;` and press enter. Don't forget the semi-colon!
- You should see something like this:
```
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| scotchbox          |
+--------------------+
4 rows in set (0.01 sec)
```
- To create a new database type `CREATE DATABASE drupal_demo;` and press enter. You should get confirmation saying that 1 row was affected, or something similar.
- If you created your database successfully you will see it when you type in `SHOW DATABASES;`
- To exit out of MySQL type `exit`, and to exit out of the Vagrant box, type `exit`
- Congrats! Now let's set up Drupal!

# Setting up all the things.

- `cd` into the Vagrant directory and type ls to see what other files there are. You should see a `public` directory and a `Vagrantfile`
- Go to drupal.org and get a zip or tar of the website https://www.drupal.org/project/drupal/releases/8.2.6. Unzip it and put the unzipped directory in the same directory. Once you are done you should have public, drupal (or whatever you named it) and Vagrantfile, you can put as many sites in here as you'd like!

### Setting up Hosts

- In order to get Drupal site to work, we will have to go into our hosts file and update the names to make sure scotchbox can tell which site is which.
- We need to go back inside our box, so type `vagrant ssh`
- Once you are in the box type: `cd /etc/apache2/sites-available/` and press enter. If you type ls you should see three files: 000-default.conf, default-ssl.conf, and scotchbox.local.conf.
- We are going to need to make a copy of the scotchbox.local.conf file. To do this from the command line, type `sudo cp scotchbox.local.conf drupal-demo.dev.conf` or whatever you would like the new file to be named. After drupal-demo, I would recommend having a .dev or .local before the .conf to make it less confusing.
- We need to edit the new file we created. To do this we can type `sudo vi drupal-demo.dev.conf` and you will see our virtual hosts file.
- To edit this file, you will need to press "I" (for insert). All we need to do is change anything that has scotchbox.local to drupal-demo.dev (or whatever we named our site).
- In my case, ServerName should be drupal-demo.dev, ServerAlias should be www.drupal-demo.dev and DocumentRoot should be /var/www/drupal-demo where drupal-demo is what you named your DRUPAL project (not the vagrant project overall) that you placed alongside the public directory and the Vagrantfile.
- To save this file, press Esc, then type :wq and press enter.
- Now within your box type `sudo a2ensite drupal-demo.dev.conf` or whatever you named that file and press enter.
- After that it will prompt you to reload apache2, so type `service apache2 reload`
- This is all we need to do in the Vagrant box, so type `exit`
- Now we need to set up the configuration of our hosts file.
- Type `sudo vi /etc/hosts` from the command line.
- Press "I" to edit this file, and at the bottom of this file create a vagrant hosts area.
- Type 192.168.33.10 drupal-demo.dev Under the scotchbox configuration. Press Esc to and :wq to save.
- Now you should be able to go to drupal-demo.dev on your browser to start setting up your drupal site.

## Setting up Drupal

- You will start getting prompted through the screens.
- Choose Language, you can select English. For choose profile, You can do standard.
- Verify Requirements, you can click 'continue anyway'
- For the database configuration, you can type your database name and the user root and password root. Then when you Save and Continue, it will start installing your Drupal site.
- You can put in the information, but I would uncheck the email notifications, since this is a local site.
- Congrats, you have set up your first Drupal Site.

redpajama_set_name: RedPajamaGithub


text:
package net.ontopia.utils;

import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections4.iterators.IteratorChain;

/**
 * INTERNAL: An iterator that works as a facade for multiple
 * iterators. The iterator represents the sum of all the
 * iterators.
 */
@Deprecated
public class IteratorIterator<T> extends IteratorChain<T> {

  /**
   * @param colls_or_iters a collection of collections or iterators.
   */
  public IteratorIterator(Collection<Collection<T>> colls_or_iters) {
    super();
    for (Collection<T> col : colls_or_iters) {
      addIterator(col.iterator());
    }
  }

  public IteratorIterator(Iterator<Iterator<T>> colls_or_iters) {
    while (colls_or_iters.hasNext()) {
      addIterator(colls_or_iters.next());
    }
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException();
  }
}


text:
import { actions } from "common/actions";

import { map } from "underscore";
import { Watcher } from "common/util/watcher";

import { ModalButtonSpec } from "common/types";
import { modals } from "common/modals";
import { makeUploadButton } from "main/reactors/make-upload-button";

export default function (watcher: Watcher) {
  watcher.on(actions.showGameUpdate, async (store, action) => {
    const { update } = action.payload;
    const { game } = update;

    const { title } = game;

    let dialogTitle = ["pick_update_upload.single.title", { title }];
    let dialogMessage = ["pick_update_upload.single.message", { title }];
    let dialogDetail = ["pick_update_upload.single.detail"];

    const dialogButtons: ModalButtonSpec[] = [
      {
        icon: "moon",
        label: ["pick_update_upload.buttons.skip_update"],
        action: actions.snoozeCave({ caveId: update.caveId }),
        className: "secondary",
      },
      {
        icon: "play2",
        label: ["pick_update_upload.buttons.just_launch"],
        action: actions.queueGame({ game }),
        className: "secondary",
      },
      "cancel",
    ];

    store.dispatch(
      actions.openModal(
        modals.naked.make({
          wind: "root",
          title: dialogTitle,
          message: dialogMessage,
          detail: dialogDetail,
          bigButtons: map(update.choices, (choice) => {
            const spec: ModalButtonSpec = {
              ...makeUploadButton(choice.upload, { showSize: false }),
              action: actions.queueGameUpdate({ update, choice }),
            };
            spec.tags.push({
              icon: choice.confidence > 0.5 ? "like" : "neutral",
              label: ` ${(choice.confidence * 100).toFixed()}%`,
            });
            return spec;
          }),
          buttons: dialogButtons,
          widgetParams: null,
        })
      )
    );
  });
}


text:
package net.makito.himitsu;

import com.google.zxing.WriterException;
import com.umeng.analytics.MobclickAgent;

import android.os.Bundle;
import android.app.*;
import android.content.*;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.*;
import android.widget.*;
import android.widget.AutoCompleteTextView.Validator;
import android.view.View.OnClickListener;
import android.view.View;
import net.makito.himitsu.AES;

public class ScanByEncrypted extends Activity implements View.OnClickListener {

	private TextView SBEContentEncrypted;
	private TextView SBEPassword;
	private TextView SBEDecOutput;
	private Button SBEBtnDecrypted;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scan_by_encrypted);
		SBEContentEncrypted = (TextView) findViewById(R.id.SBEContentEncrypted);
		SBEPassword = (TextView) findViewById(R.id.SBEPassword);
		SBEDecOutput = (TextView) findViewById(R.id.SBEDecOutput);
		SBEBtnDecrypted = (Button) findViewById(R.id.SBEBtnDecrypt);
		SBEBtnDecrypted.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.SBEBtnDecrypt:
			Valid();
			break;
		default:
			break;
		}
	}

	private void Valid() {  //验证输入内容及密码
		String mContentEnc= SBEContentEncrypted.getText().toString();
		String mPassword = SBEPassword.getText().toString();
		if (TextUtils.isEmpty(mContentEnc)) {
			Toast.makeText(this, "请输入加密内容", Toast.LENGTH_LONG).show();
		} else if (TextUtils.isEmpty(mPassword)) {
			Toast.makeText(this, "请输入条码密码", Toast.LENGTH_LONG).show();
		} else {
			do_decrypt();
		}
	}
	private void do_decrypt() {
		String mContentEnc= SBEContentEncrypted.getText().toString();
		String mPassword = SBEPassword.getText().toString();
		String mDecrypted = net.makito.himitsu.AES.decrypt(mPassword, mContentEnc);
		SBEDecOutput.setText("字符串解密结果: "+mDecrypted);
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		}
		public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		}
}


text:
<?php $this->load->view('admin/theme/message'); ?>
<?php

if(array_key_exists(0,$config_data))
$section1_html=$config_data[0]["section1_html"];
else $section1_html="";

if(array_key_exists(0,$config_data))
$section1_html_mobile=$config_data[0]["section1_html_mobile"];
else $section1_html_mobile="";;

if(array_key_exists(0,$config_data))
$section2_html=$config_data[0]["section2_html"];
else $section2_html="";;

if(array_key_exists(0,$config_data))
$section3_html=$config_data[0]["section3_html"];
else $section3_html="";;

if(array_key_exists(0,$config_data))
$section4_html=$config_data[0]["section4_html"];
else $section4_html="";

if(array_key_exists(0,$config_data))
$selected=$config_data[0]["status"];
else $selected="1";

if($selected==0) $class="disabled";
else $class="";

$placeholder=htmlspecialchars('Example: ');
?>

 <?php echo $this->lang->line("advertisement settings");?>

		    <form class="form-horizontal" enctype="multipart/form-data" action="<?php echo site_url().'admin_config_ad/edit_ad_config';?>" method="POST">

		             	<?php echo $this->lang->line("status");?> *

	               			<?php	$status=array("1"=>$this->lang->line("i want to advertise"),"0"=>$this->lang->line("i do not want advertise"));
							echo form_dropdown('status',$status,$selected,'class="form-control" id="status"');  ?>
	             			<?php echo form_error('status'); ?>

		              	Section - 1 (970x90 px)

	               			<textarea name="section1_html"  id="section1_html"  placeholder="<?php echo $placeholder;?>" class="change_status form-control <?php echo $class; ?>"><?php echo $section1_html;?></textarea>
	             			<?php echo form_error('section1_html'); ?>

		              	Section - 1 : Mobile  (320x100 px)

	               			<textarea name="section1_html_mobile"  placeholder="<?php echo $placeholder;?>" id="section1_html_mobile"  class="change_status form-control <?php echo $class; ?>"><?php echo $section1_html_mobile;?></textarea>
	             			<?php echo form_error('section1_html_mobile'); ?>

		              	Section: 2 (300x250 px)

	               			<textarea name="section2_html"  placeholder="<?php echo $placeholder;?>" id="section2_html"  class="change_status form-control <?php echo $class; ?>"><?php echo $section2_html;?></textarea>
	             			<?php echo form_error('section2_html'); ?>

		              	Section: 3 (300x250 px)

	               			<textarea name="section3_html" placeholder="<?php echo $placeholder;?>" id="section3_html"  class="change_status form-control <?php echo $class; ?>"><?php echo $section3_html;?></textarea>
	             			<?php echo form_error('section3_html'); ?>

		              	Section: 4 (300x600 px)

	               			<textarea name="section4_html"  placeholder="<?php echo $placeholder;?>" id="section4_html"  class="change_status form-control <?php echo $class; ?>"><?php echo $section4_html;?></textarea>
	             			<?php echo form_error('section4_html'); ?>

		               			<input name="submit" type="submit" class="btn btn-warning btn-lg" value="<?php echo $this->lang->line("Save");?>"/>
		              			<input type="button" class="btn btn-default btn-lg" value="<?php echo $this->lang->line("Cancel");?>" onclick='goBack("admin_config_ad/index",1)'/>

		    </form>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/android-photo-picker.iml" filepath="$PROJECT_DIR$/android-photo-picker.iml" />
      <module fileurl="file://$PROJECT_DIR$/android-photo-picker/android-photo-picker-android-photo-picker.iml" filepath="$PROJECT_DIR$/android-photo-picker/android-photo-picker-android-photo-picker.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text:
using System;
using Robust.Shared.Serialization;

namespace Content.Shared.GameObjects.Components.Singularity
{
    [NetSerializable, Serializable]
    public enum EmitterVisuals
    {
        VisualState,
        Locked
    }

    [NetSerializable, Serializable]
    public enum EmitterVisualState
    {
        On,
        Underpowered,
        Off
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>aura-resources</artifactId>
    <parent>
        <groupId>org.auraframework</groupId>
        <artifactId>aura-framework</artifactId>
        <version>0.3042-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.auraframework</groupId>
            <artifactId>aura-tools</artifactId>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <!-- We generate resources into a separate directory from
                     target/classes, so Eclipse can look for it with C-S-r if
                     anyone wants that for debugging. -->
                <directory>target/src-gen/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
                <excludes>
                    <exclude>**/jsdoc/*.html</exclude>
                    <exclude>**/jsdoc/symbols</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
            <resource>
                <directory>target/resources-gen</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>buildnumber-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>create</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <timestampFormat>{0,date,yyyy-MM-dd HH:mm:ss}</timestampFormat>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-jsdoc3</id>
                        <!-- here the phase you need -->
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/jsdoc3/jsdoc</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>config/jsdoc3/jsdoc</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>aura-version</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/classes/aura/resources/version</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/resources/aura/resources/version</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>generate-javascript</id>
                        <phase>generate-resources</phase>
                        <configuration>
                            <target>
                                <java classname="org.auraframework.tools.javascript.GenerateJavascript" classpathref="maven.runtime.classpath" fork="true" maxmemory="512m" failonerror="true">
                                    <jvmarg value="-Daura.home=${basedir}/.." />
                                </java>
                            </target>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>combine-libraries</id>
                        <phase>generate-resources</phase>
                        <configuration>
                            <target>
                                <java classname="org.auraframework.tools.javascript.CombineJavascriptLibraries" classpathref="maven.runtime.classpath" fork="true" maxmemory="512m" failonerror="true">
                                    <jvmarg value="-Daura.home=${basedir}/.." />
                                </java>
                            </target>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <!--This plugin's configuration is used to store Eclipse m2e settings
                    only. It has no influence on the Maven build itself. -->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>com.github.phasebash</groupId>
                                        <artifactId>jsdoc3-maven-plugin</artifactId>
                                        <versionRange>[1.0.7,)</versionRange>
                                        <goals>
                                            <goal>jsdoc3</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore />
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <profiles>
        <profile>
            <id>jsDoc</id>
            <activation>
                <property>
                    <name>!skipJsDoc</name>
                </property>
            </activation>
            <properties>
                <jsDoc.mode>internal</jsDoc.mode>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.phasebash</groupId>
                        <artifactId>jsdoc3-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>generate-jsdoc</id>
                                <phase>generate-resources</phase>
                                <configuration>
                                    <sourceFiles>
                                        <sourceFile>${basedir}/target/src-gen/main/resources/aura/javascript/aura_doc.js</sourceFile>
                                    </sourceFiles>
                                    <outputDirectory>${basedir}/target/src-gen/main/resources/jsdoc</outputDirectory>
                                    <configFile>${basedir}/config/jsdoc3/${jsDoc.mode}.json</configFile>
                                </configuration>
                                <goals>
                                    <goal>jsdoc3</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
<!doctype html>

    <title>Code coverage report for src/components/profile/profile.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / src/components/profile/ profile.js

        81.25%
        Statements
        13/16

        50%
        Branches
        4/8

        33.33%
        Functions
        1/3

        77.78%
        Lines
        7/9

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41	1×
1×

1×
1×

1×

1×

import React, { PropTypes } from 'react'
import { connect } from 'react-redux';

import ProfileForm from './profileForm';
import Avatar from './avatar';

const Profile = ({err, suc}) => {
    return (
        <div>
            <div className="jumbotron">
            	<Avatar/>
            </div>
            <div className="container">
                { err.length == 0 ? '' :
                    <div className="alert alert-danger">
                        <div id="errorMessage">{err}</div>
                    </div>
                }
                { suc.length == 0 ? '' :
                    <div className="alert alert-success">
                        <div id="successMessage">{suc}</div>
                    </div>
                }
            </div>
            <div className="container">
                <ProfileForm/>
            </div>
        </div>
    )
}
Profile.propTypes = {
    err: PropTypes.string.isRequired,
    suc: PropTypes.string.isRequired
}
export default connect(
    (state) => {
            return {
                err: state.errors.updateFileError,
                suc: state.errors.updateFileSuccess
            }
})(Profile)

  Code coverage
  generated by istanbul at Wed Mar 22 2017 23:40:09 GMT-0500 (CDT)


text:
package com.p3trur0

package object packtsub {
  type HTML = String
}


text:
<?php

class m141015_170000_store_product_image_column extends yupe\components\DbMigration
{
    public function safeUp()
    {
        $this->addColumn('{{store_product}}', 'image', 'varchar(250) null');
        $this->dropColumn('{{store_product_image}}', 'is_main');
    }

    public function safeDown()
    {

    }
}


text:
[![DOI](https://zenodo.org/badge/73214261.svg)](https://zenodo.org/badge/latestdoi/73214261)

This code calculates cross sections and produces events using a Madgraph model file describing the new physics (NP), scanning the requested phase space of Wilson coefficients. Multidimensional scans (changing multiple coefficients per scan) is supported. Currently only the [Higgs Effective Lagrangian](https://arxiv.org/abs/1310.5150) model is implemented. The code relies on [Lobster](https://github.com/matz-e/lobster) for workflow management. In the following instructions a general familiarity with Madgraph and Lobster is assumed-- see the [Madgraph documentation](https://cp3.irmp.ucl.ac.be/projects/madgraph/wiki/ManualAndHelp) and [Lobster documentation](http://lobster.readthedocs.io/en/latest/).
## Installation
To install Lobster, see the [documentation](http://lobster.readthedocs.io/en/latest/). Next, set up your working directory:

    curl https://raw.githubusercontent.com/annawoodard/NPFitProduction/master/setup.sh|sh -

## Quick start
### Scanning cross sections
When scanning Wilson coefficients, it is not usually obvious what range of values are optimal.  The approach used here is to start with a large range and zoom in until `(NP cross section) / (SM cross section) < scale` for a given set of processes, where `scale` is set by the user. To scan cross sections, edit [test/cross_sections.py](test/cross_sections.py). This Lobster configuration should work out of the box without modification for testing, but for your own purposes you will need to adjust the variables defined at the top. The following commands assume you are in the `test` directory. To run, activate your Lobster virtualenv:

    . ~/.lobster/bin/activate

Next, start the Lobster processing run:

    lobster process cross_sections.py

Finally, start a work queue factory to submit your jobs. If you are running at Notre Dame, login to a CRC headnode (for example `condorfe.crc.nd.edu`) and execute:

    nohup work_queue_factory -T condor -M lobster_$USER.*ttV.*cross_sections.* -d all -o /tmp/${USER}_lobster_ttV_factory.debug -C $(readlink -f factory_cross_sections_CRC.json) --wrapper "python /afs/crc.nd.edu/group/ccl/software/runos/runos.py rhel6" --extra-options="--workdir=/disk" --worker-binary=/afs/crc.nd.edu/group/ccl/software/x86_64/redhat6/cctools/$cctools/bin/work_queue_worker >&  /tmp/${USER}_lobster_ttV.log &

Submitting to the CRC cluster is recommended as there are far more resources. For additional resources, you can submit to the ND T3 by logging into to `earth.crc.nd.edu` and executing:

    nohup work_queue_factory -T condor -M lobster_$USER.*ttV.*cross_sections.* -d all -o /tmp/${USER}_lobster_ttV_factory.debug -C $(readlink -f factory_cross_sections_T3.json) >& /tmp/${USER}_lobster_ttV_xsec.log &

If you are not running at Notre Dame, you will need to setup [cctools](https://ccl.cse.nd.edu/software/) yourself. It should be possible to submit jobs by substituting `-T condor` in the factory command above with your batch system type. Supported batch systems include condor, sge, torque, moab, slurm, chirp, and amazon.

### Producing gen samples
The Lobster configuration for producing gen samples is located at [test/gen.py](test/gen.py). Two approaches to finding the range of Wilson coefficient values are supported. A `low` and `high` interval can be specified, which will fix the range to [low, high] for each coefficient. Alternatively, a scan from the previous step can be used to restrict the ranges such that `(NP cross section) / (SM cross section) < scale`. The configuration runs the interval method out of the box without modification for testing, but for your own purposes you will need to adjust the variables defined at the top. The following commands assume you are in the `test` directory. To run, activate your Lobster virtualenv:

    . ~/.lobster/bin/activate

Next, start the Lobster processing run:

    lobster process gen.py

Finally, start a work queue factory to submit your jobs (currently only submitting from the ND T3 or other cluster with access to `/cvmfs` is supported):

    nohup work_queue_factory -T condor -M lobster_$USER.*ttV.*gen -d all -o /tmp/${USER}_lobster_ttV_gen.debug -C $(readlink -f factory_gen_T3.json) >& /tmp/${USER}_lobster_ttV_gen.log &

## More details

### Reproducibility
Using this in an analysis may require tweaking of various parameters in the input cards. Each time you make any changes and run new samples, you should iterate the `version` at the top of your Lobster configuration. The cards you use are copied to a `cards` directory under that version number; the output goes to your `storage.output` directory under that version number, and all of the configuration files are copied to `workdir` under that version number. As long as you do not delete the past versions, it should be possible to reproduce a run, or figure out what the difference is between two runs.

### Producing gen samples using the scaling method
The scaling method is recommended (the interval method is used in the example above because it works out of the box, without requiring a previous cross section scan). To use the scaling method: first, run a cross section scan. Then merge the output into a single file (this example assumes `version=ttV/cross_sections/1/` in your [test/cross_sections.py](test/cross_sections.py), replace it with your version):

    merge_scans final_pass.total.npz /hadoop/store/user/$USER/ttV/cross_sections/1/final_pass_*/*npz
    mv final_pass.total.npz /hadoop/store/user/$USER/ttV/cross_sections/1/

Now replace the `command` in [test/gen.py](test/gen.py) with the commented out one, adjust `cross_sections_version` to match what you used above, and if necessary adjust `constraints` to match the processes that you want the restriction `(NP cross section) / (SM cross section) < scale` to be applied to. Finally, follow the instructions above for producing gen samples.

### Multidimensional scans
For multidimensional scans increase `dimension` in your Lobster configuration file. Each coefficient can take on `numvalues` different values, which are chosen in evenly spaced intervals between `low` and `high`. As an example, consider a Lobster configuration file with the following definitions:

    coefficients = ['cuB', 'cuW']
    constraints = ['ttH', 'ttZ', 'ttW']
    dimensions = 2
    low = -2
    high = 2
    numvalues = 3

Both `cuB` and `cuW` will be sampled at values -2.,  0.,  and 2. The sampled points will be (the first column corresponds to `cuB` and the second to `cuW`):

    array([[-2., -2.],
           [-2.,  0.],
           [-2.,  2.],
           [ 0., -2.],
           [ 0.,  0.],
           [ 0.,  2.],
           [ 2., -2.],
           [ 2.,  0.],
           [ 2.,  2.]])

When using the scaling method of coefficient rangefinding, an input 'coarse-grained scan' is required. All points for which none of the `constraint` processes exceed `(NP cross section) / (SM cross section) < scale` will be found. From those points, the maximum and minimum value for each coefficient is set as `low` and `high` for that coefficient. Note that due to interference effects between coefficients, a more sophisticated approach might be needed.

### Using the gen samples
By default [test/gen.py](test/gen.py) produces one output dataset per group of coefficients to scan, lumping all parameter points together. The sampled parameter point is saved to each event for further processing; see [plugins/wilsonCoefficientAnnotator.cc](plugins/wilsonCoefficientAnnotator.cc).

### Adding processing steps
Lobster can chain together processing steps. If you want to run reco, etc on your gen samples, create a new workflow in your Lobster configuration file by copying the `gen` workflow and adjusting the `pset` and `outputs` to match the CMSSW pset that runs your subsequent step.

### Analysis
This code was used in the CMS TOP-17-005 analysis (paper submitted to JHEP.) The preprint is available [here](https://arxiv.org/abs/1711.02547) and a restricted [analysis note](http://cms.cern.ch/iCMS/jsp/db_notes/noteInfo.jsp?cmsnoteid=CMS%20AN-2017/048).  The analysis code is posted [here](http://github.com/annawoodard/EffectiveTTV).

### Running MG efficiently
For calculating a single point in NP parameter space, time and core time are plotted below for a range of assigned cores. As cores are added, the time to calculate a single point falls, but the total core seconds consumed rises. If you have fewer points to calculate than cores, and you don't mind losing some efficiency, you can finish work faster by assigning more cores to each task (`cores` in [test/cross_sections.py](test/cross_sections.py)). If you have more points to calculate than cores, you should assign the lowest feasible `cores`, depending on the ratio of cores/memory/disk available where you are running (in my experience, each point requires ~2 GB memory and ~1.5 GB disk).


text:
layout: post
title:  "Daniel receives NSERC CGS M scholarship"
description: Daniel McClement receives NSERC CGS M scholarship
date:   "2021-04-29"
---

Congratulations to DAIS Lab MASc student Daniel McClement on receiving the NSERC CGS M scholarship! Well done, Daniel.


text:
package com.amazonaws.util.awsclientgenerator.domainmodels.defaults;

import lombok.Data;
import java.util.Map;

@Data
public class DefaultClientConfigs {
    String version;
    Map<String, BaseOption> base;
    Map<String, Map<String, BaseOptionModifier>> modes;
    Map<String, Map<String, String>> documentation;
}


text:
class CreateTaggings < ActiveRecord::Migration[5.1]
  def change
    create_table :taggings do |t|
      t.integer :response_id
      t.integer :tag_id

      t.timestamps
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="VMware vSphere Editions Demystified">
    <meta name="author" content="Scott Bollinger/@kfalconspb">
    <link rel="alternate" type="application/rss+xml" title="VirtuallyBollinger.com RSS Feed Virtualization VMware Citrix Microsoft and Linux by Scott Bollinger @kfalconspb" href="rss.xml" />
    <title>VMware vSphere Editions Demystified</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation
                    Menu
                </button>
                VirtuallyBollinger.com

                        Home

                        About

                        Disclaimer

                        infoFireHose

vSphere Editions Demystified

VMware vSphere Editions

                        Posted by Scott Bollinger / @kfalconspb on September 21, 2016

Let's get vSphere!

But where to start? You want to deploy VMware vSphere as your virtualization platform but...

What edition?

What's an Addon?

Do I need a kit?

What do all these features do?

Does the kit come with a screwdriver?

It all depends right? No, I'm not going to tell you that, because I know it doesn't really help.

You may ask your Sales contact what you need and they'll gladly help you rolling out Enterprise Plus with vRealize Operations Manager and NSX for your six computer doctors office. Is that what you need though? You know your environment the best.

Size Matters, oh and the features

How big does your environment need to be? Is it one site or a several data centers in multiple countries? What features do you need?

As you look through the features, understand that some features require a minimum edition. Editions are really only groupings of features and the Kits are bundles of Products and features to get you up and running as quickly as possible.

This post will outline the options and in individual posts I'll go into what each feature does and how it could benefit your environment.

Have fun,

Scott Bollinger / @kfalconspb

Editions, Features, Add-Ons, and Kits. Oh My!

Per VMware, there are three editions of vSphere. VMware doesn't call the two kits for smaller deployments, Editions, I don't know why.

Officially, the three editions are vSphere Standard Edition, vSphere Enterprise Edition, vSphere Enterprise Plus Edition. [1 pg 5]

The editions, are bundles of individual features. See the matrix below.

On top of the editions, there are Add-Ons which are bundles of Products.

"VMware vSphere with Operations Management 6 combines two components (vSphere and VMware vRealize™ Operations™ Standard) into a single product with a single license." [1 pg 3]

Next are the Kits

Kits are bundles of features and products grouped together to ease deploy and get things up and running as quickly as possible.

Look out for my feature description posts.

References

VMware vSphere with Operations Management and VMware vSphere Licensing, Pricing and Packaging

Copyright © 2018 Scott Bollinger / @kfalconspb

Please Also Visit: Scott-Bollinger.com/PapaShell.com/Sniffer.Fun/VirtuallyBollinger.com/BollingerUSA.com


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Potato Pancake</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation
                    Menu
                </button>
                Antoine Bichara

                        Home

                        About

                        Contact

Indian Potato Pancake

                        Posted by Antoine on January 20, 2017

Note: This is not a Dosa, but an easier alternative. Dosa is made with Idli rice, not the flour mix used in this recipe.

Filling

5 peeled boiled potatoes, roughly cut

1/2 yellow onion, thinly sliced

1 tsp mustard seeds

1 tsp turmeric

			 Pancake

1 cup all-purpose flour

1 egg

1 cup whole milk

2 tsp cumin seeds

3 garlic cloves, minced

1 fresh serrano chili, very finely chopped

1.5 inches ginger route, very finely chopped, or grated

			 Simplified Mango Chutney

			One mango

			Two tbsp white vinegar

			2 tbsp brown sugar

			1 shallot, finely chopped

			1/3 cup golden raisins, or crushed candied dates

	 Serves Two       Total Time: 45 minutes

 Filling

Add mustard seeds and tbsp olive oil to pan on low heat. After one minute add in onions, and stir for about 4 minutes. Then add in potatoes and turmeric, salt, pepper, and several more tbsp olive oil. Stir for another 4 minutes.

Pancake

In a small pan toast cumin seeds on low heat for about 2 minutes. Then add tbsp olive oil, garlic, ginger and serrano chili and try on medium heat for about 4 minutes.

In a mixing bowl mix the egg, pan mixture, and flour. Very slowly add milk stirring continuously. Heat a large pan to medium heat. Take a ladle of the mixture and carefully pour into center of pan. As quickly as possible twirl the pan around so the mix spreads out across the whole pan as thinly as possible. Cook for one minute, or until pancake comes loose when you shake the pan. Then flip over and cook other side for one minute, turning heat down slightly so as not to burn other side. Repeat for each pancake.

 Simplified Mango Chutney

This is a quick alternative to real mango chutney which is far more complex. Another side you can do instead of this is simply some greek yogurt with chopped cilantro.

Cut the mango into small pieces, add the rest of the ingredients, stir, and then salt to taste.

To serve, either add line of filling at edge of pancake and then roll up pancake or add filling over one side of pancake and fold over once, serving mango chutney on the side.

Copyright © Antoine Bichara 2017

Please enable JavaScript to view the comments powered by Disqus.


text:
<?xml version="1.0" encoding="UTF-8"?>

    <title>Wicket Examples - wizard</title>
    <link rel="stylesheet" type="text/css" href="style.css"/>

Examples of extension's wizards package

    	static wizard using plain text steps

    	static wizard using panel steps

    	wizard for creating a new user


text:
<?php
	require_once("fonctions.php");
	echo getSecteurIdByProjetId($_POST["projet_id"]);
?>


text:
using System;
using System.IO;
using System.Xml;
using NUnit.Framework;

namespace Palaso.Lift.Tests.Migration
{
	public class MigratorTestBase
	{
		public void AssertXPathNotFound(string xpath, string filePath)
		{
			XmlDocument doc = new XmlDocument();
			try
			{
				doc.Load(filePath);
			}
			catch (Exception err)
			{
				Console.WriteLine(err.Message);
				Console.WriteLine(File.ReadAllText(filePath));
			}
			XmlNode node = doc.SelectSingleNode(xpath);
			if (node != null)
			{
				XmlWriterSettings settings = new XmlWriterSettings();
				settings.Indent = true;
				settings.ConformanceLevel = ConformanceLevel.Fragment;
				XmlWriter writer = XmlTextWriter.Create(Console.Out, settings);
				doc.WriteContentTo(writer);
				writer.Flush();
			}
			Assert.IsNull(node);
		}

		public void AssertXPathAtLeastOne(string xpath, string filePath)
		{
			XmlDocument doc = new XmlDocument();
			try
			{
				doc.Load(filePath);
			}
			catch (Exception err)
			{
				Console.WriteLine(err.Message);
				Console.WriteLine(File.ReadAllText(filePath));
			}
			XmlNode node = doc.SelectSingleNode(xpath);
			if (node == null)
			{
				XmlWriterSettings settings = new XmlWriterSettings();
				settings.Indent = true;
				settings.ConformanceLevel = ConformanceLevel.Fragment;
				XmlWriter writer = XmlTextWriter.Create(Console.Out, settings);
				doc.WriteContentTo(writer);
				writer.Flush();
			}
			Assert.IsNotNull(node);
		}
	}
}


text:
#include <arch.h>
#include <text_buffer.h>
#include <gdt.h>
#include <pit.h>
#include <cmos.h>
#include <keyboard.h>
#include <pthread.h>
#include <kernel.h>

#if CONFIG_SWI
enum {
	IRQ_SYSTEM_CALL = 0x80
};

static void system_call(struct interrupt_context *ctx)
{
	(void)ctx;
}
#endif

void arch_early_init(void)
{
	text_buffer_init();
}

void arch_init(void)
{
	gdt_init();
	interrupt_init();
	pit_init();
	cmos_init();
	keyboard_init();
#if CONFIG_SWI
	interrupt_register(IRQ_SYSTEM_CALL, system_call);
#endif
}

void arch_pthread_init(pthread_t th, void (*wrapper)(void *(*)(void *), void *),
		       void *(*start_routine)(void *), void *arg)
{
	unsigned long *stack;
	struct interrupt_context *ctx;

	stack = (unsigned long *)((char *)th->stack_addr + th->stack_size);
	stack[-1] = (unsigned long)arg;
	stack[-2] = (unsigned long)start_routine;
	stack[-3] = (unsigned long)abort;
#if CONFIG_USERSPACE
	ctx = (struct interrupt_context *)(stack - 1) - 1;
	ctx->gs = ctx->fs = ctx->es = ctx->ds = KERNEL_DS;
#else
	ctx = (struct interrupt_context *)(stack - 3) - 1;
#endif
	ctx->eip = (unsigned long)wrapper;
	ctx->ebp = (unsigned long)(stack - 1);
	ctx->esp = (unsigned long)(stack - 3);
	ctx->cs = KERNEL_CS;
	ctx->eflags = CPU_FLAG_IF;
	th->context.esp = (unsigned long)ctx;
}


text:
<?php

namespace Travel\Controller;

use Travel\Form\BookingForm;
use Zend\Db\ResultSet\ResultSet;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Travel\Form\SearchForm;
use Travel\View\Helper\AtdwClassifications;
use Travel\View\Helper\GetCategory;
/**
 * Class AccommodationController
 * @package Travel\Controller
 * @author Laurynas Tretjakovas(n3ziniuka5) <laurynas.tretjakovas@gmail.com>
 * @property \Travel\Model\ProductModel                 $productModel
 * @property \Travel\Service\AccommodationSearchService $accommodationSearchService
 * @property \Travel\Model\DestinationModel             $destinationModel
 */
class AccommodationController extends AbstractActionController
{
    private $productTable;
    private $destinationTable;
    private $hotelRoomTable;
    private $multimediaTable;
    private $productInfoTable;
    private $productAttributesTable;
	private $attributeTable;
    private $menuItemTable;
    public $category;
    public $destCurrent;
    public $destination;
    public $classification;
    public $city;
    public $slug;
    public $page;
	private $itemsPerPage = 10;
	private $pageRange = 5;

    protected $productModel;
    protected $accommodationSearchService;
    protected $destinationModel;

    public function indexAction()
    {
        $viewParams     = array();
        $this->category = $this->params('category');

        $this->city = $this->params('location3');
        $this->page = $this->params('page');

        // $dest = new Model_Destination();
        $this->destCurrent = array(
            'CITY'  => $this->params('location3'),
            'AREA'  => $this->params('location2'),
            'STATE' => $this->params('location1')
        );

		if ($this->params('classification')){
			$classification = array_search($this->params('classification'), AtdwClassifications::$aliases);
			$this->classification = $this->getAttributeTable()->getByCode($classification);
		}

		if (($d = $this->destCurrent['CITY']) || ($d = $this->destCurrent['AREA']) || ($d = $this->destCurrent['STATE'])) {

            $this->destination = $this->getDestinationTable()->getByUrl($d);

            $viewParams['destination'] = $d;
        }

		$enabledProviders    = $this->getProductModel()->getEnabledProviders();
        $product             = $this->getProductTable()->getNewList($this->getProductAbbrev($this->category), $this->page, $this->destination, $this->classification, $enabledProviders);

		$paginator = new Paginator(new paginatorIterator($product));
		$paginator->setCurrentPageNumber($this->page)
				  ->setItemCountPerPage($this->itemsPerPage)
				  ->setPageRange($this->pageRange);

        $accommodationCounts = $this->getDestinationModel()->getAccommodationCountsInAreas($this->getProductAbbrev($this->category), $this->classification);
		$breadcrumbs         = $this->getDestinationModel()->getAccommodationBreadcrumbs($this->getProductAbbrev($this->category), $this->destination, $this->classification);

        if ($this->getProductAbbrev($this->category) == 'ACCOMM') {
        	if($this->classification){
        		$viewParams['countRoute'] = 'accommcategorycity';
        	} else {
            	$viewParams['countRoute'] = 'accommcity';
			}
        }
        else if ($this->getProductAbbrev($this->category) == 'ATTRACTION') {
        	if($this->classification){
        		$viewParams['countRoute'] = 'attractioncategorycity';
			} else {
				$viewParams['countRoute'] = 'attractioncity';
			}
        }
        //$viewParams['products']            = $product;
        $viewParams['products']            = $paginator;
        $viewParams['categoryurl']         = $this->getCategoryUrl($this->category);
        $viewParams['accommodationCounts'] = $accommodationCounts;
        $viewParams['breadcrumbs']         = $breadcrumbs;
		$viewParams['classification']      = $this->classification;

		if($this->classification) {
			$viewParams['title'] = "Browse Accommodation " . $this->classification->attr_name . " By Area";
		} else {
			$getCategory = new GetCategory();
			$viewParams['title'] = "Browse Accommodation " . $getCategory->category($this->category) . " By Area";
		}

		$uri = $_SERVER['REQUEST_URI'];
		$uri = rtrim($uri, "/" . $this->page);
		$viewParams['uri']         		   = $uri;

		if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
			/* ajax process here */
			$view = new ViewModel;
			$view->setTemplate('layout/product-list');
			$view->setVariables(array('products' => $paginator, 'uri' => $uri));
			$viewHtml = $this->getServiceLocator()->get('viewrenderer')->render($view);

			$result = array(
				"success" => true,
				"HTML" => $viewHtml,
			);
			$this->response->setContent(\Zend\Json\Json::encode($result));
			return $this->response;
		}

		$searchForm       = new SearchForm($this->getServiceLocator());
		if(count($this->destination) == 1) {
			$searchForm->setData(array('area' => $this->destination[0]['baodestination_id']));
		}
		$viewParams['searchForm'] = $searchForm;
        return $viewParams;
    }

	public function getProductsAsyncAction()
    {
        //$viewParams     = array();
        $this->category = $this->params('category');

        $this->city = $this->params('location3');
        $this->page = $this->params('page');

        // $dest = new Model_Destination();
        $this->destCurrent = array(
            'CITY'  => $this->params('location3'),
            'AREA'  => $this->params('location2'),
            'STATE' => $this->params('location1')
        );

		if (($d = $this->destCurrent['CITY']) || ($d = $this->destCurrent['AREA']) || ($d = $this->destCurrent['STATE'])) {

            $this->destination = $this->getDestinationTable()->getByUrl($d);

            $viewParams['destination'] = $d;
        }

		$enabledProviders    = $this->getProductModel()->getEnabledProviders();
        $product             = $this->getProductTable()->getNewList($this->getProductAbbrev($this->category), $this->page, $this->destination, $this->classification, $enabledProviders);

		$paginator = new Paginator(new paginatorIterator($product));
		$paginator->setCurrentPageNumber($this->page)
				  ->setItemCountPerPage($this->itemsPerPage)
				  ->setPageRange($this->pageRange);
        //$viewParams['products']            = $paginator;

		$uri = $_SERVER['REQUEST_URI'];
		$uri = rtrim($uri, "/" . $this->page);
		$viewParams['uri']         		   = $uri;
        //return $viewParams;

		$view = new ViewModel;
		$view->setTemplate('article-template');
		$view->setVariables(array('products' => $paginator, 'uri' => $uri));

		$viewHtml = $this->getServiceLocator()->get('viewrenderer')->render($view);

		$result = array(
			"success" => true,
			"HTML" => $viewHtml,
		);
		$this->response->setContent(\Zend\Json\Json::encode($result));
		return $this->response;

    }
    public function fooAction()

    {
        // This shows the :controller and :action parameters in default route
        // are working when you browse to /accommodation/accommodation/foo
        return array();
        echo "
travel controller
";
    }

    /**
     *
     * @return \Zend\View\Model\ViewModel
     */
    public function viewAction()
    {
    	$viewParams  = array();
        $bookingForm = new BookingForm($this->getServiceLocator());
        $request     = $this->getRequest();

        $this->category = $this->params('category');
        $this->slug     = $this->params('slug');

        $urlParams = explode('-', $this->params('slug'));
        $id        = $urlParams[0];
        if (isset($urlParams[1])) {
            $url = $urlParams[1];
        }

        $product = $this->getProductTable()->getProduct($id);

        if ($request->isPost()) {
            $post = $request->getPost();
            $bookingForm->setData($post);
            if ($bookingForm->isValid()) {
                $bookingFormData                = $bookingForm->getData();
                $productDoctrine                = $this->getProductModel()->get($id);
                $search                         = array();
                $search['results']              = $this->getAccommodationSearchService()->getProductResults($productDoctrine, $bookingFormData['commencing'], $bookingFormData['nights'], $bookingFormData['adults'], $bookingFormData['children']);
                $search['params']               = array();
                $search['params']['commencing'] = $bookingFormData['commencing'];
                $search['params']['nights']     = $bookingFormData['nights'];
                $search['params']['adults']     = $bookingFormData['adults'];
                $search['params']['children']   = $bookingFormData['children'];
                $viewParams['individualSearch'] = $search;
            }
        }

        $product->category = $this->getProductType($product->product_category);
        $area_info         = $this->getDestinationTable()->getDestination($product->product_area_id);
        $region_info       = $this->getDestinationTable()->getDestination($product->product_region_id);

        $product->setArea_info($area_info);
        $product->setRegion_info($region_info);
        //	$product->setMultimedia($this->getMultimediaTable()->getMultimedia($product->product_id)->toArray());
        $product->setMultimedia($this->getMultimediaTable()->getProductPhotos($product->product_id, 'ACCOMM', $product->product_source_id)->toArray());
        $product->setProduct_info($this->getProductInfoTable()->getInfo($product->product_id)->toArray());
        $product->setAttributes($this->getProductAttributesTable()->getAccommodationAttributes($product->product_id)->toArray());
        if ($product->category == 'accommodation') {
            $hotelrooms = $this->getHotelRoomTable()->getRooms($product->product_id);
            $product->setHotel_rooms($hotelrooms->toArray());
        }

        $viewParams['products']    = $product;
        $viewParams['bookingForm'] = $bookingForm;
        return $viewParams;
    }

    public function getProductTable()
    {
        if (!$this->productTable) {
            $this->productTable = $this->getServiceLocator()->get('Travel\Model\ProductTable');
        }

        return $this->productTable;
    }

    public function getDestinationTable()
    {
        if (!$this->destinationTable) {
            $this->destinationTable = $this->getServiceLocator()->get('Travel\Model\DestinationTable');
        }

        return $this->destinationTable;
    }

    public function getHotelRoomTable()
    {
        if (!$this->hotelRoomTable) {
            $this->hotelRoomTable = $this->getServiceLocator()->get('Travel\Model\HotelRoomTable');
        }

        return $this->hotelRoomTable;
    }

    public function getMultimediaTable()
    {
        if (!$this->multimediaTable) {
            $this->multimediaTable = $this->getServiceLocator()->get('Travel\Model\MultimediaTable');
        }

        return $this->multimediaTable;
    }

    public function getProductInfoTable()
    {

        if (!$this->productInfoTable) {
            $this->productInfoTable = $this->getServiceLocator()->get('Travel\Model\productInfoTable');
        }

        return $this->productInfoTable;

    }

    public function getProductAttributesTable()
    {

        if (!$this->productAttributesTable) {
            $this->productAttributesTable = $this->getServiceLocator()->get('Travel\Model\AttributeTable');
        }

        return $this->productAttributesTable;

    }

    public function getMenuItemTable()
    {

        if (!$this->menuItemTable) {
            $this->menuItemTable = $this->getServiceLocator()->get('Travel\Model\MenuItemTable');
        }

        return $this->menuItemTable;

    }

    public function getProductType($producttype)
    {
        switch ($producttype) {
            case 'ACCOMM' :
                $producttype = "accommodation";
                break;
            case 'ATTRACTION' :
                $producttype = "attractions";
                break;
            case 'EVENT' :
                $producttype = "event";
                break;

            default :
                break;
        }
        return $producttype;
    }

    public function getProductAbbrev($producttype)
    {
        switch ($producttype) {
            case 'accommodation' :
                $producttype = "ACCOMM";
                break;
            case 'attractions' :
                $producttype = "ATTRACTION";
                break;
            case 'event' :
                $producttype = "EVENT";
                break;

            default :
                break;
        }
        return $producttype;

    }

    public function getCategoryUrl($producttype)
    {
        switch ($producttype) {
            case 'ACCOMM' :
                $producttype = "accommodation";
                break;
            case 'ATTRACTION' :
                $producttype = "attractions";
                break;
            case 'EVENT' :
                $producttype = "event";
                break;

            default :
                break;
        }
        return $producttype;

    }

    protected function getProductModel()
    {
        if (!$this->productModel) {
            $this->productModel = $this->getServiceLocator()->get('Travel\Model\ProductModel');
        }
        return $this->productModel;
    }

	protected function getAttributeTable()
    {
        if (!$this->attributeTable) {
            $this->attributeTable = $this->getServiceLocator()->get('Travel\Model\AttributeTable');
        }
        return $this->attributeTable;
    }

    protected function getAccommodationSearchService()
    {
        if (!$this->accommodationSearchService) {
            $this->accommodationSearchService = $this->getServiceLocator()->get('Travel\Service\AccommodationSearchService');
        }
        return $this->accommodationSearchService;
    }

    protected function getDestinationModel()
    {
        if (!$this->destinationModel) {
            $this->destinationModel = $this->getServiceLocator()->get('Travel\Model\DestinationModel');
        }
        return $this->destinationModel;
    }
}


text:
using System;
using CocosSharp;

namespace tests.Extensions
{
    public class CCControlScene : CCLayer
	{

        public virtual CCLabel SceneTitleLabel { get; set; }
        public virtual CCLabel SceneSubtitleLabel { get; set; }

        public CCControlScene()
		{

            SceneTitleLabel = new CCLabel(" ", "Arial", 12, CCLabelFormat.SpriteFont);
            AddChild(SceneTitleLabel, 1);

		}

        public override void OnEnter()
        {
            base.OnEnter();

            // Get the screensize
            CCSize screensize = Layer.VisibleBoundsWorldspace.Size;

            var pBackItem = new CCMenuItemFont("Back", toExtensionsMainLayer);
            pBackItem.Position = new CCPoint(screensize.Width - 50, 25);
            var pBackMenu = new CCMenu(pBackItem);
            pBackMenu.Position =  CCPoint.Zero;
            AddChild(pBackMenu, 10);

            // Add the generated background
            var background = new CCSprite("extensions/background");
            background.Position = screensize.Center;
            AddChild(background);

            // Add the ribbon
            //var ribbon = new CCScale9SpriteFile("extensions/ribbon", new CCRect(1, 1, 48, 55));
            //ribbon.ContentSize = new CCSize(screensize.Width, 57);
            //ribbon.Position = new CCPoint(screensize.Width / 2.0f, screensize.Height - ribbon.ContentSize.Height / 2.0f);
            //AddChild(ribbon);

            // Add the title
            SceneTitleLabel.Position = new CCPoint(screensize.Width / 2, screensize.Height - SceneTitleLabel.ContentSize.Height / 2 - 5);

            // Add the subtitle
            SceneSubtitleLabel = new CCLabel(" ", "Arial", 12, CCLabelFormat.SpriteFont);
            SceneSubtitleLabel.Position = new CCPoint(screensize.Width / 2,
                screensize.Height - SceneTitleLabel.ContentSize.Height -
            SceneSubtitleLabel.ContentSize.Height / 2 - 10);
            AddChild(SceneSubtitleLabel, 1);

            // Add the menu
            var item1 = new CCMenuItemImage("Images/b1", "Images/b2", previousCallback);
            var item2 = new CCMenuItemImage("Images/r1", "Images/r2", restartCallback);
            var item3 = new CCMenuItemImage("Images/f1", "Images/f2", nextCallback);

            var menu = new CCMenu(item1, item3, item2);
            menu.Position = CCPoint.Zero;
            item1.Position = new CCPoint(screensize.Width / 2 - 100, 37);
            item2.Position = new CCPoint(screensize.Width / 2, 35);
            item3.Position = new CCPoint(screensize.Width / 2 + 100, 37);

            AddChild(menu, 1);
        }
		// Menu Callbacks
		public void toExtensionsMainLayer(object sender)
		{
			var pScene = new ExtensionsTestScene();
			pScene.runThisTest();
		}

		public virtual void previousCallback(object sender)
		{
			Scene.Director.ReplaceScene(CCControlSceneManager.SharedControlSceneManager.PreviousControlScene);
		}

		public virtual void restartCallback(object sender)
		{
			Scene.Director.ReplaceScene(CCControlSceneManager.SharedControlSceneManager.CurrentControlScene);
		}

		public virtual void nextCallback(object sender)
		{
			Scene.Director.ReplaceScene(CCControlSceneManager.SharedControlSceneManager.NextControlScene);
		}

//        private CCLabel sceneSubtitleLabel;
//        public virtual CCLabel getSceneSubtitleLabel() { return sceneSubtitleLabel; }
//
//
//        public virtual void setSceneSubtitleLabel(CCLabel var)
//        {
//            if (sceneSubtitleLabel != var)
//            {
//                sceneSubtitleLabel = var;
//            }
//        }

		/** Title label of the scene. */
        public static CCScene sceneWithTitle(string title, CCScene scene)
		{
			var pScene = new CCScene(scene);
		    var controlLayer = new CCControlScene();
		    if (controlLayer != null)
		    {
		        controlLayer.SceneTitleLabel.Text = (title);
		        pScene.AddChild(controlLayer);
		    }
			return pScene;
		}
	}
}


text:
import json
import urllib2

from coliw.utils import EOL, TIMEOUT, ENCODING, OPENER, WebArgumentParser

HELP = "get weather by giving a city name"

KEY = "db310acfbeeb7a7697f13bb18c43a073"

URL = ("http://api.openweathermap.org/data/2.5/"
       "weather?q={input}&appid={key}").format(key=KEY, input="{input}")

def weather(args):
    url = URL.format(input=urllib2.quote(args.city))
    data = OPENER.open(url, timeout=TIMEOUT).read()
    wdict = json.loads(data)
    # Extract results.
    info = wdict["weather"][0]
    info.update(wdict["main"])
    if not args.verbose:
        info = {key: value for key, value in info.items()
                if key in ("main", "description")}
    return EOL.join([value.encode(ENCODING)
                     if isinstance(value, unicode) else str(value)
                     for value in info.values()])

parser = WebArgumentParser(add_help=False)
parser.add_argument(
    "city", metavar="CITY",
    help="city for which weather will be shown"
)
parser.add_argument(
    "-v", "--verbose", action="store_true",
    help="show full information regarding the results"
)
parser.set_defaults(func=weather)


text:
import React                   from 'react';
import InputRange              from 'react-input-range';
import { connect }             from 'react-redux';
import { filter }              from '../../actions/filter-actions';
import { isEmpty, isEmptyObj } from '../../utils/utility';
import PropTypes               from 'prop-types';

class SearchFilter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            priceRange : {
                min: 1000,
                max: 20000
            }
        };
    }

    startFiltering = (value) => {
        this.props.filter(value);
    }

    render() {
        return (

 Refine flight search

                <InputRange
                    maxValue         = {30000}
                    minValue         = {0}
                    formatLabel      = {value => `${value}`}
                    value            = {this.state.priceRange}
                    onChange         = {value => this.setState({ priceRange : value })}
                    onChangeComplete = {this.startFiltering}
                />

        );
    }
}

SearchFilter.propTypes = {
    filter : PropTypes.func.isRequired
}

export default connect(null , { filter })(SearchFilter);


text:
package org.apache.tinkerpop.gremlin.structure.io.gryo;

/**
 * Provides path access to test data resources.
 *
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class GryoResourceAccess {
}


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:id="@+id/mTagTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dp"
        android:textSize="16sp"
        android:visibility="visible" />

    <EditText
        android:id="@+id/mAddTagEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dp"
        android:imeOptions="actionDone"
        android:lines="1"
        android:maxLines="1"
        android:singleLine="true"
        android:textSize="16sp"
        android:visibility="gone" />

</merge>