text:
package v2v3

import (
	"context"
	"fmt"
	"path"
	"sort"
	"strings"
	"time"

	"go.etcd.io/etcd/clientv3"
	"go.etcd.io/etcd/clientv3/concurrency"
	"go.etcd.io/etcd/etcdserver/api/v2error"
	"go.etcd.io/etcd/etcdserver/api/v2store"
	"go.etcd.io/etcd/mvcc/mvccpb"
)

// store implements the Store interface for V2 using
// a v3 client.
type v2v3Store struct {
	c *clientv3.Client
	// pfx is the v3 prefix where keys should be stored.
	pfx string
	ctx context.Context
}

const maxPathDepth = 63

var errUnsupported = fmt.Errorf("TTLs are unsupported")

func NewStore(c *clientv3.Client, pfx string) v2store.Store { return newStore(c, pfx) }

func newStore(c *clientv3.Client, pfx string) *v2v3Store { return &v2v3Store{c, pfx, c.Ctx()} }

func (s *v2v3Store) Index() uint64 { panic("STUB") }

func (s *v2v3Store) Get(nodePath string, recursive, sorted bool) (*v2store.Event, error) {
	key := s.mkPath(nodePath)
	resp, err := s.c.Txn(s.ctx).Then(
		clientv3.OpGet(key+"/"),
		clientv3.OpGet(key),
	).Commit()
	if err != nil {
		return nil, err
	}

	if kvs := resp.Responses[0].GetResponseRange().Kvs; len(kvs) != 0 || isRoot(nodePath) {
		nodes, err := s.getDir(nodePath, recursive, sorted, resp.Header.Revision)
		if err != nil {
			return nil, err
		}
		cidx, midx := uint64(0), uint64(0)
		if len(kvs) > 0 {
			cidx, midx = mkV2Rev(kvs[0].CreateRevision), mkV2Rev(kvs[0].ModRevision)
		}
		return &v2store.Event{
			Action: v2store.Get,
			Node: &v2store.NodeExtern{
				Key:           nodePath,
				Dir:           true,
				Nodes:         nodes,
				CreatedIndex:  cidx,
				ModifiedIndex: midx,
			},
			EtcdIndex: mkV2Rev(resp.Header.Revision),
		}, nil
	}

	kvs := resp.Responses[1].GetResponseRange().Kvs
	if len(kvs) == 0 {
		return nil, v2error.NewError(v2error.EcodeKeyNotFound, nodePath, mkV2Rev(resp.Header.Revision))
	}

	return &v2store.Event{
		Action:    v2store.Get,
		Node:      s.mkV2Node(kvs[0]),
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func (s *v2v3Store) getDir(nodePath string, recursive, sorted bool, rev int64) ([]*v2store.NodeExtern, error) {
	rootNodes, err := s.getDirDepth(nodePath, 1, rev)
	if err != nil || !recursive {
		if sorted {
			sort.Sort(v2store.NodeExterns(rootNodes))
		}
		return rootNodes, err
	}
	nextNodes := rootNodes
	nodes := make(map[string]*v2store.NodeExtern)
	// Breadth walk the subdirectories
	for i := 2; len(nextNodes) > 0; i++ {
		for _, n := range nextNodes {
			nodes[n.Key] = n
			if parent := nodes[path.Dir(n.Key)]; parent != nil {
				parent.Nodes = append(parent.Nodes, n)
			}
		}
		if nextNodes, err = s.getDirDepth(nodePath, i, rev); err != nil {
			return nil, err
		}
	}

	if sorted {
		sort.Sort(v2store.NodeExterns(rootNodes))
	}
	return rootNodes, nil
}

func (s *v2v3Store) getDirDepth(nodePath string, depth int, rev int64) ([]*v2store.NodeExtern, error) {
	pd := s.mkPathDepth(nodePath, depth)
	resp, err := s.c.Get(s.ctx, pd, clientv3.WithPrefix(), clientv3.WithRev(rev))
	if err != nil {
		return nil, err
	}

	nodes := make([]*v2store.NodeExtern, len(resp.Kvs))
	for i, kv := range resp.Kvs {
		nodes[i] = s.mkV2Node(kv)
	}
	return nodes, nil
}

func (s *v2v3Store) Set(
	nodePath string,
	dir bool,
	value string,
	expireOpts v2store.TTLOptionSet,
) (*v2store.Event, error) {
	if expireOpts.Refresh || !expireOpts.ExpireTime.IsZero() {
		return nil, errUnsupported
	}

	if isRoot(nodePath) {
		return nil, v2error.NewError(v2error.EcodeRootROnly, nodePath, 0)
	}

	ecode := 0
	applyf := func(stm concurrency.STM) error {
		// build path if any directories in path do not exist
		dirs := []string{}
		for p := path.Dir(nodePath); !isRoot(p); p = path.Dir(p) {
			pp := s.mkPath(p)
			if stm.Rev(pp) > 0 {
				ecode = v2error.EcodeNotDir
				return nil
			}
			if stm.Rev(pp+"/") == 0 {
				dirs = append(dirs, pp+"/")
			}
		}
		for _, d := range dirs {
			stm.Put(d, "")
		}

		key := s.mkPath(nodePath)
		if dir {
			if stm.Rev(key) != 0 {
				// exists as non-dir
				ecode = v2error.EcodeNotDir
				return nil
			}
			key = key + "/"
		} else if stm.Rev(key+"/") != 0 {
			ecode = v2error.EcodeNotFile
			return nil
		}
		stm.Put(key, value, clientv3.WithPrevKV())
		stm.Put(s.mkActionKey(), v2store.Set)
		return nil
	}

	resp, err := s.newSTM(applyf)
	if err != nil {
		return nil, err
	}
	if ecode != 0 {
		return nil, v2error.NewError(ecode, nodePath, mkV2Rev(resp.Header.Revision))
	}

	createRev := resp.Header.Revision
	var pn *v2store.NodeExtern
	if pkv := prevKeyFromPuts(resp); pkv != nil {
		pn = s.mkV2Node(pkv)
		createRev = pkv.CreateRevision
	}

	vp := &value
	if dir {
		vp = nil
	}
	return &v2store.Event{
		Action: v2store.Set,
		Node: &v2store.NodeExtern{
			Key:           nodePath,
			Value:         vp,
			Dir:           dir,
			ModifiedIndex: mkV2Rev(resp.Header.Revision),
			CreatedIndex:  mkV2Rev(createRev),
		},
		PrevNode:  pn,
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func (s *v2v3Store) Update(nodePath, newValue string, expireOpts v2store.TTLOptionSet) (*v2store.Event, error) {
	if isRoot(nodePath) {
		return nil, v2error.NewError(v2error.EcodeRootROnly, nodePath, 0)
	}

	if expireOpts.Refresh || !expireOpts.ExpireTime.IsZero() {
		return nil, errUnsupported
	}

	key := s.mkPath(nodePath)
	ecode := 0
	applyf := func(stm concurrency.STM) error {
		if rev := stm.Rev(key + "/"); rev != 0 {
			ecode = v2error.EcodeNotFile
			return nil
		}
		if rev := stm.Rev(key); rev == 0 {
			ecode = v2error.EcodeKeyNotFound
			return nil
		}
		stm.Put(key, newValue, clientv3.WithPrevKV())
		stm.Put(s.mkActionKey(), v2store.Update)
		return nil
	}

	resp, err := s.newSTM(applyf)
	if err != nil {
		return nil, err
	}
	if ecode != 0 {
		return nil, v2error.NewError(v2error.EcodeNotFile, nodePath, mkV2Rev(resp.Header.Revision))
	}

	pkv := prevKeyFromPuts(resp)
	return &v2store.Event{
		Action: v2store.Update,
		Node: &v2store.NodeExtern{
			Key:           nodePath,
			Value:         &newValue,
			ModifiedIndex: mkV2Rev(resp.Header.Revision),
			CreatedIndex:  mkV2Rev(pkv.CreateRevision),
		},
		PrevNode:  s.mkV2Node(pkv),
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func (s *v2v3Store) Create(
	nodePath string,
	dir bool,
	value string,
	unique bool,
	expireOpts v2store.TTLOptionSet,
) (*v2store.Event, error) {
	if isRoot(nodePath) {
		return nil, v2error.NewError(v2error.EcodeRootROnly, nodePath, 0)
	}
	if expireOpts.Refresh || !expireOpts.ExpireTime.IsZero() {
		return nil, errUnsupported
	}
	ecode := 0
	applyf := func(stm concurrency.STM) error {
		ecode = 0
		key := s.mkPath(nodePath)
		if unique {
			// append unique item under the node path
			for {
				key = nodePath + "/" + fmt.Sprintf("%020s", time.Now())
				key = path.Clean(path.Join("/", key))
				key = s.mkPath(key)
				if stm.Rev(key) == 0 {
					break
				}
			}
		}
		if stm.Rev(key) > 0 || stm.Rev(key+"/") > 0 {
			ecode = v2error.EcodeNodeExist
			return nil
		}
		// build path if any directories in path do not exist
		dirs := []string{}
		for p := path.Dir(nodePath); !isRoot(p); p = path.Dir(p) {
			pp := s.mkPath(p)
			if stm.Rev(pp) > 0 {
				ecode = v2error.EcodeNotDir
				return nil
			}
			if stm.Rev(pp+"/") == 0 {
				dirs = append(dirs, pp+"/")
			}
		}
		for _, d := range dirs {
			stm.Put(d, "")
		}

		if dir {
			// directories marked with extra slash in key name
			key += "/"
		}
		stm.Put(key, value)
		stm.Put(s.mkActionKey(), v2store.Create)
		return nil
	}

	resp, err := s.newSTM(applyf)
	if err != nil {
		return nil, err
	}
	if ecode != 0 {
		return nil, v2error.NewError(ecode, nodePath, mkV2Rev(resp.Header.Revision))
	}

	var v *string
	if !dir {
		v = &value
	}

	return &v2store.Event{
		Action: v2store.Create,
		Node: &v2store.NodeExtern{
			Key:           nodePath,
			Value:         v,
			Dir:           dir,
			ModifiedIndex: mkV2Rev(resp.Header.Revision),
			CreatedIndex:  mkV2Rev(resp.Header.Revision),
		},
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func (s *v2v3Store) CompareAndSwap(
	nodePath string,
	prevValue string,
	prevIndex uint64,
	value string,
	expireOpts v2store.TTLOptionSet,
) (*v2store.Event, error) {
	if isRoot(nodePath) {
		return nil, v2error.NewError(v2error.EcodeRootROnly, nodePath, 0)
	}
	if expireOpts.Refresh || !expireOpts.ExpireTime.IsZero() {
		return nil, errUnsupported
	}

	key := s.mkPath(nodePath)
	resp, err := s.c.Txn(s.ctx).If(
		s.mkCompare(nodePath, prevValue, prevIndex)...,
	).Then(
		clientv3.OpPut(key, value, clientv3.WithPrevKV()),
		clientv3.OpPut(s.mkActionKey(), v2store.CompareAndSwap),
	).Else(
		clientv3.OpGet(key),
		clientv3.OpGet(key+"/"),
	).Commit()

	if err != nil {
		return nil, err
	}
	if !resp.Succeeded {
		return nil, compareFail(nodePath, prevValue, prevIndex, resp)
	}

	pkv := resp.Responses[0].GetResponsePut().PrevKv
	return &v2store.Event{
		Action: v2store.CompareAndSwap,
		Node: &v2store.NodeExtern{
			Key:           nodePath,
			Value:         &value,
			CreatedIndex:  mkV2Rev(pkv.CreateRevision),
			ModifiedIndex: mkV2Rev(resp.Header.Revision),
		},
		PrevNode:  s.mkV2Node(pkv),
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func (s *v2v3Store) Delete(nodePath string, dir, recursive bool) (*v2store.Event, error) {
	if isRoot(nodePath) {
		return nil, v2error.NewError(v2error.EcodeRootROnly, nodePath, 0)
	}
	if !dir && !recursive {
		return s.deleteNode(nodePath)
	}
	if !recursive {
		return s.deleteEmptyDir(nodePath)
	}

	dels := make([]clientv3.Op, maxPathDepth+1)
	dels[0] = clientv3.OpDelete(s.mkPath(nodePath)+"/", clientv3.WithPrevKV())
	for i := 1; i < maxPathDepth; i++ {
		dels[i] = clientv3.OpDelete(s.mkPathDepth(nodePath, i), clientv3.WithPrefix())
	}
	dels[maxPathDepth] = clientv3.OpPut(s.mkActionKey(), v2store.Delete)

	resp, err := s.c.Txn(s.ctx).If(
		clientv3.Compare(clientv3.Version(s.mkPath(nodePath)+"/"), ">", 0),
		clientv3.Compare(clientv3.Version(s.mkPathDepth(nodePath, maxPathDepth)+"/"), "=", 0),
	).Then(
		dels...,
	).Commit()
	if err != nil {
		return nil, err
	}
	if !resp.Succeeded {
		return nil, v2error.NewError(v2error.EcodeNodeExist, nodePath, mkV2Rev(resp.Header.Revision))
	}
	dresp := resp.Responses[0].GetResponseDeleteRange()
	return &v2store.Event{
		Action:    v2store.Delete,
		PrevNode:  s.mkV2Node(dresp.PrevKvs[0]),
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func (s *v2v3Store) deleteEmptyDir(nodePath string) (*v2store.Event, error) {
	resp, err := s.c.Txn(s.ctx).If(
		clientv3.Compare(clientv3.Version(s.mkPathDepth(nodePath, 1)), "=", 0).WithPrefix(),
	).Then(
		clientv3.OpDelete(s.mkPath(nodePath)+"/", clientv3.WithPrevKV()),
		clientv3.OpPut(s.mkActionKey(), v2store.Delete),
	).Commit()
	if err != nil {
		return nil, err
	}
	if !resp.Succeeded {
		return nil, v2error.NewError(v2error.EcodeDirNotEmpty, nodePath, mkV2Rev(resp.Header.Revision))
	}
	dresp := resp.Responses[0].GetResponseDeleteRange()
	if len(dresp.PrevKvs) == 0 {
		return nil, v2error.NewError(v2error.EcodeNodeExist, nodePath, mkV2Rev(resp.Header.Revision))
	}
	return &v2store.Event{
		Action:    v2store.Delete,
		PrevNode:  s.mkV2Node(dresp.PrevKvs[0]),
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func (s *v2v3Store) deleteNode(nodePath string) (*v2store.Event, error) {
	resp, err := s.c.Txn(s.ctx).If(
		clientv3.Compare(clientv3.Version(s.mkPath(nodePath)+"/"), "=", 0),
	).Then(
		clientv3.OpDelete(s.mkPath(nodePath), clientv3.WithPrevKV()),
		clientv3.OpPut(s.mkActionKey(), v2store.Delete),
	).Commit()
	if err != nil {
		return nil, err
	}
	if !resp.Succeeded {
		return nil, v2error.NewError(v2error.EcodeNotFile, nodePath, mkV2Rev(resp.Header.Revision))
	}
	pkvs := resp.Responses[0].GetResponseDeleteRange().PrevKvs
	if len(pkvs) == 0 {
		return nil, v2error.NewError(v2error.EcodeKeyNotFound, nodePath, mkV2Rev(resp.Header.Revision))
	}
	pkv := pkvs[0]
	return &v2store.Event{
		Action: v2store.Delete,
		Node: &v2store.NodeExtern{
			Key:           nodePath,
			CreatedIndex:  mkV2Rev(pkv.CreateRevision),
			ModifiedIndex: mkV2Rev(resp.Header.Revision),
		},
		PrevNode:  s.mkV2Node(pkv),
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func (s *v2v3Store) CompareAndDelete(nodePath, prevValue string, prevIndex uint64) (*v2store.Event, error) {
	if isRoot(nodePath) {
		return nil, v2error.NewError(v2error.EcodeRootROnly, nodePath, 0)
	}

	key := s.mkPath(nodePath)
	resp, err := s.c.Txn(s.ctx).If(
		s.mkCompare(nodePath, prevValue, prevIndex)...,
	).Then(
		clientv3.OpDelete(key, clientv3.WithPrevKV()),
		clientv3.OpPut(s.mkActionKey(), v2store.CompareAndDelete),
	).Else(
		clientv3.OpGet(key),
		clientv3.OpGet(key+"/"),
	).Commit()

	if err != nil {
		return nil, err
	}
	if !resp.Succeeded {
		return nil, compareFail(nodePath, prevValue, prevIndex, resp)
	}

	// len(pkvs) > 1 since txn only succeeds when key exists
	pkv := resp.Responses[0].GetResponseDeleteRange().PrevKvs[0]
	return &v2store.Event{
		Action: v2store.CompareAndDelete,
		Node: &v2store.NodeExtern{
			Key:           nodePath,
			CreatedIndex:  mkV2Rev(pkv.CreateRevision),
			ModifiedIndex: mkV2Rev(resp.Header.Revision),
		},
		PrevNode:  s.mkV2Node(pkv),
		EtcdIndex: mkV2Rev(resp.Header.Revision),
	}, nil
}

func compareFail(nodePath, prevValue string, prevIndex uint64, resp *clientv3.TxnResponse) error {
	if dkvs := resp.Responses[1].GetResponseRange().Kvs; len(dkvs) > 0 {
		return v2error.NewError(v2error.EcodeNotFile, nodePath, mkV2Rev(resp.Header.Revision))
	}
	kvs := resp.Responses[0].GetResponseRange().Kvs
	if len(kvs) == 0 {
		return v2error.NewError(v2error.EcodeKeyNotFound, nodePath, mkV2Rev(resp.Header.Revision))
	}
	kv := kvs[0]
	indexMatch := prevIndex == 0 || kv.ModRevision == int64(prevIndex)
	valueMatch := prevValue == "" || string(kv.Value) == prevValue
	var cause string
	switch {
	case indexMatch && !valueMatch:
		cause = fmt.Sprintf("[%v != %v]", prevValue, string(kv.Value))
	case valueMatch && !indexMatch:
		cause = fmt.Sprintf("[%v != %v]", prevIndex, kv.ModRevision)
	default:
		cause = fmt.Sprintf("[%v != %v] [%v != %v]", prevValue, string(kv.Value), prevIndex, kv.ModRevision)
	}
	return v2error.NewError(v2error.EcodeTestFailed, cause, mkV2Rev(resp.Header.Revision))
}

func (s *v2v3Store) mkCompare(nodePath, prevValue string, prevIndex uint64) []clientv3.Cmp {
	key := s.mkPath(nodePath)
	cmps := []clientv3.Cmp{clientv3.Compare(clientv3.Version(key), ">", 0)}
	if prevIndex != 0 {
		cmps = append(cmps, clientv3.Compare(clientv3.ModRevision(key), "=", mkV3Rev(prevIndex)))
	}
	if prevValue != "" {
		cmps = append(cmps, clientv3.Compare(clientv3.Value(key), "=", prevValue))
	}
	return cmps
}

func (s *v2v3Store) JsonStats() []byte                  { panic("STUB") }
func (s *v2v3Store) DeleteExpiredKeys(cutoff time.Time) { panic("STUB") }

func (s *v2v3Store) Version() int { return 2 }

// TODO: move this out of the Store interface?

func (s *v2v3Store) Save() ([]byte, error)       { panic("STUB") }
func (s *v2v3Store) Recovery(state []byte) error { panic("STUB") }
func (s *v2v3Store) Clone() v2store.Store        { panic("STUB") }
func (s *v2v3Store) SaveNoCopy() ([]byte, error) { panic("STUB") }
func (s *v2v3Store) HasTTLKeys() bool            { panic("STUB") }

func (s *v2v3Store) mkPath(nodePath string) string { return s.mkPathDepth(nodePath, 0) }

func (s *v2v3Store) mkNodePath(p string) string {
	return path.Clean(p[len(s.pfx)+len("/k/000/"):])
}

// mkPathDepth makes a path to a key that encodes its directory depth
// for fast directory listing. If a depth is provided, it is added
// to the computed depth.
func (s *v2v3Store) mkPathDepth(nodePath string, depth int) string {
	normalForm := path.Clean(path.Join("/", nodePath))
	n := strings.Count(normalForm, "/") + depth
	return fmt.Sprintf("%s/%03d/k/%s", s.pfx, n, normalForm)
}

func (s *v2v3Store) mkActionKey() string { return s.pfx + "/act" }

func isRoot(s string) bool { return len(s) == 0 || s == "/" || s == "/0" || s == "/1" }

func mkV2Rev(v3Rev int64) uint64 {
	if v3Rev == 0 {
		return 0
	}
	return uint64(v3Rev - 1)
}

func mkV3Rev(v2Rev uint64) int64 {
	if v2Rev == 0 {
		return 0
	}
	return int64(v2Rev + 1)
}

// mkV2Node creates a V2 NodeExtern from a V3 KeyValue
func (s *v2v3Store) mkV2Node(kv *mvccpb.KeyValue) *v2store.NodeExtern {
	if kv == nil {
		return nil
	}
	n := &v2store.NodeExtern{
		Key:           s.mkNodePath(string(kv.Key)),
		Dir:           kv.Key[len(kv.Key)-1] == '/',
		CreatedIndex:  mkV2Rev(kv.CreateRevision),
		ModifiedIndex: mkV2Rev(kv.ModRevision),
	}
	if !n.Dir {
		v := string(kv.Value)
		n.Value = &v
	}
	return n
}

// prevKeyFromPuts gets the prev key that is being put; ignores
// the put action response.
func prevKeyFromPuts(resp *clientv3.TxnResponse) *mvccpb.KeyValue {
	for _, r := range resp.Responses {
		pkv := r.GetResponsePut().PrevKv
		if pkv != nil && pkv.CreateRevision > 0 {
			return pkv
		}
	}
	return nil
}

func (s *v2v3Store) newSTM(applyf func(concurrency.STM) error) (*clientv3.TxnResponse, error) {
	return concurrency.NewSTM(s.c, applyf, concurrency.WithIsolation(concurrency.Serializable))
}


text:
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
    <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

// private
// This is a support class used internally by the Grid components
Ext.grid.GridEditor = function(field, config){
    Ext.grid.GridEditor.superclass.constructor.call(this, field, config);
    field.monitorTab = false;
};

Ext.extend(Ext.grid.GridEditor, Ext.Editor, {
    alignment: "tl-tl",
    autoSize: "width",
    hideEl : false,
    cls: "x-small-editor x-grid-editor",
    shim:false,
    shadow:false
});

redpajama_set_name: RedPajamaGithub


text:
package org.openkilda.wfm.topology.isllatency.bolts;

import static org.openkilda.wfm.topology.isllatency.IslLatencyTopology.CACHE_DATA_FIELD;
import static org.openkilda.wfm.topology.isllatency.IslLatencyTopology.ISL_GROUPING_FIELD;
import static org.openkilda.wfm.topology.isllatency.IslLatencyTopology.ISL_STATUS_FIELD;
import static org.openkilda.wfm.topology.isllatency.IslLatencyTopology.ISL_STATUS_UPDATE_BOLT_ID;
import static org.openkilda.wfm.topology.isllatency.IslLatencyTopology.LATENCY_DATA_FIELD;
import static org.openkilda.wfm.topology.isllatency.IslLatencyTopology.ROUTER_BOLT_ID;

import org.openkilda.messaging.info.event.IslRoundTripLatency;
import org.openkilda.messaging.info.event.IslStatusUpdateNotification;
import org.openkilda.persistence.PersistenceManager;
import org.openkilda.persistence.context.PersistenceContextRequired;
import org.openkilda.wfm.AbstractBolt;
import org.openkilda.wfm.error.PipelineException;
import org.openkilda.wfm.share.model.Endpoint;
import org.openkilda.wfm.share.model.IslReference;
import org.openkilda.wfm.topology.isllatency.carriers.CacheCarrier;
import org.openkilda.wfm.topology.isllatency.model.StreamType;
import org.openkilda.wfm.topology.isllatency.service.CacheService;

import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

public class CacheBolt extends AbstractBolt implements CacheCarrier {
    private final PersistenceManager persistenceManager;
    private transient CacheService cacheService;

    public CacheBolt(PersistenceManager persistenceManager) {
        this.persistenceManager = persistenceManager;
    }

    @Override
    @PersistenceContextRequired(requiresNew = true)
    public void init() {
        cacheService = new CacheService(this, persistenceManager.getRepositoryFactory());
    }

    @Override
    protected void handleInput(Tuple tuple) throws PipelineException {

        if (ISL_STATUS_UPDATE_BOLT_ID.equals(tuple.getSourceComponent())) {
            handleStatusUpdate(tuple);
        } else if (ROUTER_BOLT_ID.equals(tuple.getSourceComponent())) {
            IslRoundTripLatency roundTripLatency = pullValue(tuple, LATENCY_DATA_FIELD, IslRoundTripLatency.class);
            cacheService.handleGetDataFromCache(roundTripLatency);
        } else {
            unhandledInput(tuple);
        }
    }

    private void handleStatusUpdate(Tuple tuple) throws PipelineException {
        IslStatusUpdateNotification notification = pullValue(
                tuple, ISL_STATUS_FIELD, IslStatusUpdateNotification.class);
        cacheService.handleUpdateCache(notification);
    }

    @Override
    public void emitCachedData(IslRoundTripLatency data, Endpoint destination) {
        IslReference islReference = new IslReference(
                Endpoint.of(data.getSrcSwitchId(), data.getSrcPortNo()), destination);

        Values values = new Values(islReference, data, destination, getCommandContext());
        getOutput().emit(StreamType.LATENCY.toString(), getCurrentTuple(), values);
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        Fields fields = new Fields(ISL_GROUPING_FIELD, LATENCY_DATA_FIELD, CACHE_DATA_FIELD, FIELD_ID_CONTEXT);
        declarer.declareStream(StreamType.LATENCY.toString(), fields);
    }
}


text:
package com.battlelancer.seriesguide.ui;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.billing.BillingActivity;
import com.battlelancer.seriesguide.util.Utils;

/**
 * Activities at the top of the navigation hierarchy, show menu on going up.
 */
public abstract class BaseTopActivity extends BaseNavDrawerActivity {

    private static final String TAG = "BaseTopActivity";

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        setupActionBar();

    }

    private void setupActionBar() {
        final ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void setupNavDrawer() {
        super.setupNavDrawer();

        // show a drawer indicator
        setDrawerIndicatorEnabled(true);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_fade_enter_sg, R.anim.activity_fade_exit_sg);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.base_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        // show subscribe button if not subscribed, yet
        menu.findItem(R.id.menu_subscribe).setVisible(!Utils.hasAccessToX(this));

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // check if we should toggle the navigation drawer (app icon was touched)
        if (toggleDrawer(item)) {
            return true;
        }

        int itemId = item.getItemId();
        if (itemId == R.id.menu_subscribe) {
            startActivity(new Intent(this, BillingActivity.class));

            fireTrackerEvent("Subscribe");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * Google Analytics helper method for easy sending of click events.
     */
    protected abstract void fireTrackerEvent(String label);
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: xiaohongyang
 * Date: 2015/6/21
 * Time: 21:46
 */

namespace app\modules\admin\models;

use yii\rbac\Role;

class Auth_item_child extends BaseModel{

    const SCENARIO_CREATE = 'event_create';

    public $parent;

    public $child;

    public $childType;

    public $auth = null;

    public function init()
    {
        $this->auth = \Yii::$app->authManager;
    }

    public function rules()
    {
        return [

            [['prent'], 'required', 'on' => self::SCENARIO_CREATE],
            ['child', 'required', 'on' => self::SCENARIO_CREATE, 'message'=> t_arr('app', ['child','node','can\'t','be','null'],'','!')],
            ['child',   function ($attribute) {

                            if ($this->find()->where(['parent'=>$this->parent, 'child'=>$this->child])->count() > 0) {
                                //子节点已经存在
                                $this->addError($attribute, t_arr('app',['child','node','allready','exists'],'','!'));
                            }
                        }, 'on' => self::SCENARIO_CREATE
            ]

        ];
    }

    public function scenarios()
    {
        return [
          self::SCENARIO_CREATE => ['parent', 'child']
        ];
    }

    public function getAuthItem()
    {
        return $this->hasOne(Auth_item::className(), ['name' => 'child']);
    }

    //获取指定角色的子节点
    public function getChildListByName($name)
    {
        $auth = \Yii::$app->authManager;

        $childList = $auth->getChildren($name);

        foreach ($childList as &$child) {
            //子节点的子节点列表
            $child->data = $auth->getChildren($child->name);
        }

        return $childList ;
    }

    //添加子节点
    public function addChild( $parms )
    {

        $this->setScenario(self::SCENARIO_CREATE);
        if ($this->load($parms) && $this->validate()) {

            $auth = \Yii::$app->authManager;

            $this->childType = $parms[self::formName()]['childType'];

            $parent = $auth->getRole($this->parent);

            if($this->childType == 1)
                $child = $auth->getRole($this->child);
            else
                $child = $auth->getPermission($this->child);

            if (!$child) {

                $this->addError('child', t_arr('app',['child','node','not','exists'],'','!'));
                return false;
            }

            return $auth->addChild($parent, $child);
        }

    }

    public function deleteChild($parentName, $childName )
    {

        $auth = \Yii::$app->authManager;

        $parent = $auth->getRole( $parentName );
        $child = $auth->getPermission( $childName )? : $auth->getRole( $childName );

        if ($parent && $child) {

            return $auth->removeChild($parent, $child);
        } else {
            $this->addError( 'error', '父节点或子节点不存在!' );
            return false;
        }

    }

}


text:
set -euo pipefail
source ./scripts/env.sh

DUAL_VMS_PROFILE="../multicluster-gke/vm-migration/scripts/install.yaml"
cd ../../common

# Cluster 1
log "⛵ Installing Istio on Cluster 1..."
gcloud config set project $PROJECT_ID
gcloud container clusters get-credentials $CLUSTER_1_NAME --zone $CLUSTER_1_ZONE
kubectl config use-context $CTX_1
INSTALL_YAML=${DUAL_VMS_PROFILE} ./install_istio.sh

# Cluster 2
log "⛵ Installing Istio on Cluster 2..."
gcloud container clusters get-credentials $CLUSTER_2_NAME --zone $CLUSTER_2_ZONE
kubectl config use-context $CTX_2
INSTALL_YAML=${DUAL_VMS_PROFILE} ./install_istio.sh

# Configure dns
log "🌎 Configuring CoreDNS..."

configure_kubedns () {
     kubectl apply -f - <<EOF
apiVersion: v1
kind: ConfigMap
metadata:
  name: kube-dns
  namespace: kube-system
data:
  stubDomains: |
    {"global": ["$(kubectl get svc -n istio-system istiocoredns -o jsonpath={.spec.clusterIP})"]}
EOF
}

# Cluster 1
log "Configuring DNS on Cluster 1..."
kubectl config use-context $CTX_1
configure_kubedns
log "...done with cluster 1."

# Cluster 2
log "Configuring DNS on Cluster 2..."
kubectl config use-context $CTX_2
configure_kubedns
log "...done with cluster 2."


text:
layout: page
title: Strickland Research Dinner
date: 2016-05-24
author: Carolyn Molina
tags: weekly links, java
status: published
summary: Aliquam erat volutpat. Nullam eu fringilla mi, in.
banner: images/banner/office-01.jpg
booking:
  startDate: 03/08/2016
  endDate: 03/12/2016
  ctyhocn: CVLMSHX
  groupCode: SRD
published: true
---
Maecenas consequat nisi felis, vitae malesuada urna consectetur vitae. Suspendisse varius lobortis velit, et hendrerit urna convallis vel. Aliquam in ligula quis mi pharetra egestas sed at mi. Nunc imperdiet id justo eget congue. Donec mattis tortor in quam malesuada pulvinar. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin eget gravida ipsum, consectetur semper dui. Morbi sed urna elit.
Donec vitae condimentum ante. Vestibulum at elementum diam. In eu nisi imperdiet odio sodales pulvinar. Fusce non vehicula enim, in varius sem. Aliquam erat volutpat. In faucibus, metus vitae accumsan suscipit, sapien nibh lacinia felis, ac convallis dolor nisl et nunc. Fusce imperdiet tempus euismod. Donec lobortis urna non quam varius, at dictum urna maximus. Aliquam id feugiat justo. Nulla est dui, feugiat ut ipsum non, aliquet viverra eros. Sed efficitur nibh dolor, ut tincidunt est cursus nec. Ut quis ultricies turpis, et porttitor felis.

1 Praesent scelerisque massa nec consectetur pretium
1 Pellentesque in neque nec ipsum ultricies ullamcorper
1 Nunc in magna et urna pretium commodo at quis nulla
1 Morbi consectetur risus vitae massa molestie elementum.

In feugiat lacus nec nulla maximus, quis ornare libero dictum. Aenean velit erat, posuere ac blandit et, hendrerit eget dui. Quisque vehicula pharetra rutrum. Morbi condimentum fringilla pretium. Curabitur sodales placerat convallis. Suspendisse cursus aliquet nisl egestas egestas. Proin dui lacus, aliquam ut pulvinar ut, vulputate vel nulla. Vivamus ullamcorper velit lorem, at eleifend purus laoreet sit amet. Ut vel arcu faucibus, tempor sapien nec, posuere erat. Praesent scelerisque vestibulum est eu fermentum. Curabitur blandit, ex eget semper aliquam, lectus tellus dictum odio, in lobortis sem ipsum in nibh. Nunc sagittis leo in sem sollicitudin ullamcorper in vitae odio. Etiam ac dui pharetra leo porta scelerisque.


text:
class UsersController < ApplicationController
# before_action :set_user, only: [:guchi, :jiman, :inori, :index, :show, :edit, :update, :destroy]
before_action :logged_in_user, only: [:guchi, :jiman, :inori, :index, :show, :edit, :update, :destroy]

  def list
    @msg = 'Users cont. list アクション'
    @user = User.find(params[:id])
  end

  def guchi
    @msg = 'Users cont. guchi アクション'
    @user = User.find(params[:id])
    @micropost = Micropost.new
  end

  def guchi_feedback
    @msg = 'Users cont. guchi_feedback アクション'
  end

  def jiman
    @msg = 'Users cont. jiman アクション'
    @user = User.find(params[:id])
    @micropost = Micropost.new
  end

  def jiman_feedback
    @msg = 'Users cont. jiman_feedback アクション'
  end

  def inori
    @msg = 'Users cont. inori アクション'
    @user = User.find(params[:id])
    @micropost = Micropost.new
  end

  def inori_feedback
    @msg = 'Users cont. inori_feedback アクション'
  end

  def index
    @msg = 'Users cont. index アクション'
    @user = User.find(params[:id])
  end

  def show
    @msg = 'Users cont. show アクション'
    @user = User.find(params[:id])
    @microposts = @user.microposts.find(params[:id])
  end

  def edit
  @msg = 'Users cont. edit アクション'
  @user = User.find(params[:id])
  end

  def new
    @msg = 'Users cont. new アクション'
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
       log_in @user
      flash[:success] = "Welcome to the SressShedder App!"
       redirect_to @user
      # Handle a successful save.
    else
      render 'new'
    end
  end

  private

    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
      @micropost = Micropost.find(params[:id])
    end

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

     # beforeフィルター

    # 正しいユーザーかどうかを確認
    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end
end


text:
package de.kaiserpfalzedv.ocp.groupsync.ocp.actions;

import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;

import de.kaiserpfalzedv.ocp.groupsync.ExecuterException;
import de.kaiserpfalzedv.ocp.groupsync.ocp.providers.OcpToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @author klenkes {@literal <rlichti@kaiserpfalz-edv.de>}
 * @version 1.0.0
 * @since 2017-09-10
 */
@Service
public class ExecuteRestCall {
    private static final Logger LOG = LoggerFactory.getLogger(ExecuteRestCall.class);

    @Inject
    private RestTemplate sender;

    @Value("${ocpServer:-}")
    private String masterUrl;

    @Inject
    private OcpToken token;

    @PostConstruct
    public void init() {
        if ("-".equals(masterUrl)) {
            masterUrl = "https://"
                + System.getenv("OCP_MASTER_SERVICE_HOST")
                + ":" + System.getenv("OCP_MASTER_SERVICE_PORT");
        }
    }

    public Optional<String> get(final String localPart) {
        HttpEntity<String> request = generateRequest();
        String requestUrl = masterUrl + localPart;

        return doRequest(request, requestUrl, HttpMethod.GET);
    }

    private Optional<String> doRequest(final HttpEntity<String> request, final String requestUrl, final HttpMethod method) {
        try {
            LOG.debug("Connecting to: server={}, method={}", requestUrl, method);
            LOG.trace("Request: {}", request);
            String result = sender.exchange(requestUrl, method, request, String.class).getBody();

            LOG.debug("Response: {}", result);
            return Optional.ofNullable(result);
        } catch (RestClientException e) {
            LOG.error(e.getClass().getSimpleName() + " caught: " + e.getMessage(), e);
        }

        return Optional.empty();
    }

    public Optional<String> post(final String localPart, String body) {
        HttpEntity<String> request = generateRequest(body);
        String requestUrl = masterUrl + localPart;

        return doRequest(request, requestUrl, HttpMethod.POST);
    }

    public Optional<String> put(final String localPart, final String body) throws ExecuterException {
        HttpEntity<String> request = generateRequest(body);
        String requestUrl = masterUrl + localPart;

        return doRequest(request, requestUrl, HttpMethod.PUT);
    }

    public Optional<String> delete(final String localPart) throws ExecuterException {
        HttpEntity<String> request = generateRequest();
        String requestUrl = masterUrl + localPart;

        return doRequest(request, requestUrl, HttpMethod.DELETE);
    }

    private HttpEntity<String> generateRequest() {
        HttpHeaders headers = generateHeaders();
        return new HttpEntity<>(headers);
    }

    private HttpEntity<String> generateRequest(@NotNull final String body) {
        HttpHeaders headers = generateHeaders();
        return new HttpEntity<>(body, headers);
    }

    private HttpHeaders generateHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + token.getToken());
        headers.add("Content-Type", "application/yaml");

        return headers;
    }
}


text:
<?php
/**
 * File containing the Convert Command which converts a URL to a single HTML resources
 *
 * @author Ron Rademaker
 * @since 1-jul-2015
 */
namespace RonRademaker\PagePacker\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use RonRademaker\PagePacker\Converter\URLConverter;

/**
 * ConvertCommand is a symfony based command to convert a URL to a single HTML resource, this is useful for errorpages that shouldn't depend on anything
 *
 * @author Ron Rademaker
 * @since 1-jul-2015
 */
class ConvertCommand extends Command
{
	/**
	 * configure
	 *
	 * Sets the command variables and it's inputs
	 *
	 * @since 1-jul-2015
	 * @access protected
	 * @return void
	 **/
	protected function configure() {
		$this->setName('convert:page');
		$this->addArgument('url', InputArgument::REQUIRED, 'The URL (use FQDN) to convert');
	}

	/**
	 * execute
	 *
	 * Describe here what the function should do
	 *
	 * @since 1-jul-2015
	 * @access protected
	 * @param InputInterface $input
	 * @param OutputInterface $output
	 * @return void
	 **/
	protected function execute(InputInterface $input, OutputInterface $output) {
		$url = $input->getArgument('url');

		$converter = new URLConverter($url);

		$output->writeln($converter->getPackedHTML() );

	}
}


text:
class Bank < ActiveRecord::Base

  REDIRECT_URI = 'http://dreamcast.local:3000/oauth_callback'

  def authorize_url(state)
    url + "/oauth/authorize?response_type=code&client_id=#{client_id}&redirect_uri=#{REDIRECT_URI}&state=#{state}"
  end

  def token_url
    url + "/oauth/token"
  end

  def account_url(account_number)
    url + "/accounts/#{account_number}.xml"
  end

  def token_post_body(code)
    {:client_id => client_id, :client_secret => client_secret, :code => code, :grant_type => 'authorization-code', :redirect_uri => REDIRECT_URI}
  end
end


text:
.PHONY: all build test integration-test unit-test

HOST_TMPDIR=test -n "$(TMPDIR)" && echo $(TMPDIR) || echo /tmp

all: test

build:
	docker build -t docker-py .

test: unit-test integration-test

unit-test: build
	docker run docker-py python tests/test.py

integration-test: build
	docker run -e NOT_ON_HOST=true -v `$(HOST_TMPDIR)`:/tmp -v /var/run/docker.sock:/var/run/docker.sock docker-py python tests/integration_test.py


text:
@import url('./reset.css');
@import url('./main.css');
@import url('./note-area.css');
@import url('./note-log.css');
@import url('./notebook-list.css');


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Br. mycol. Soc. 10(4): 249 (1926)

#### Original name
Botrytis brongniartii subsp. delacroixii Sacc.

### Remarks
null


text:
package com.faforever.client.fx.contextmenu;

import com.faforever.client.fx.Controller;
import javafx.scene.control.CustomMenuItem;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public abstract class AbstractCustomMenuItemController<T> implements Controller<CustomMenuItem> {

  public CustomMenuItem root;

  protected T object;

  public final void setObject(T object) {
    this.object = object;
    finalizeProperties();
    afterSetObject();
  }

  private void finalizeProperties() {
    if (!getRoot().visibleProperty().isBound()) {
      getRoot().setVisible(isItemVisible());
    }
  }

  public abstract void afterSetObject();

  protected boolean isItemVisible() {
    return true; // by-default;
  }

  @Override
  public CustomMenuItem getRoot() {
    return root;
  }
}


text:
/*
 * morphseq_reg.c
 *
 *    Simple regression test for binary morph sequence (interpreter),
 *    showing display mode and rejection of invalid sequence components.
 */

#include "allheaders.h"

#define  SEQUENCE1    "O1.3 + C3.1 + R22 + D2.2 + X4"
#define  SEQUENCE2    "O2.13 + C5.23 + R22 + X4"
#define  SEQUENCE3    "e3.3 + d3.3 + tw5.5"
#define  SEQUENCE4    "O3.3 + C3.3"
#define  SEQUENCE5    "O5.5 + C5.5"
#define  BAD_SEQUENCE  "O1.+D8 + E2.4 + e.4 + r25 + R + R.5 + X + x5 + y7.3"

#define  DISPLAY_SEPARATION   0   /* use 250 to get images displayed */

main(int    argc,
     char **argv)
{
char        *infile;
PIX         *pixs, *pixg, *pixc, *pixd;
static char  mainName[] = "morphseq_reg";

    if (argc != 1)
	return ERROR_INT(" Syntax:  morphseq_reg", mainName, 1);

    pixs = pixRead("feyn.tif");

        /* 1 bpp */
    pixd = pixMorphSequence(pixs, SEQUENCE1, -1);
    pixDestroy(&pixd);
    pixd = pixMorphSequence(pixs, SEQUENCE1, DISPLAY_SEPARATION);
    pixWrite("/tmp/morphseq1.png", pixd, IFF_PNG);
    pixDestroy(&pixd);

    pixd = pixMorphCompSequence(pixs, SEQUENCE2, -2);
    pixDestroy(&pixd);
    pixd = pixMorphCompSequence(pixs, SEQUENCE2, DISPLAY_SEPARATION);
    pixWrite("/tmp/morphseq2.png", pixd, IFF_PNG);
    pixDestroy(&pixd);

    pixd = pixMorphSequenceDwa(pixs, SEQUENCE2, -3);
    pixDestroy(&pixd);
    pixd = pixMorphSequenceDwa(pixs, SEQUENCE2, DISPLAY_SEPARATION);
    pixWrite("/tmp/morphseq3.png", pixd, IFF_PNG);
    pixDestroy(&pixd);

    pixd = pixMorphCompSequenceDwa(pixs, SEQUENCE2, -4);
    pixDestroy(&pixd);
    pixd = pixMorphCompSequenceDwa(pixs, SEQUENCE2, DISPLAY_SEPARATION);
    pixWrite("/tmp/morphseq4.png", pixd, IFF_PNG);
    pixDestroy(&pixd);

        /* 8 bpp */
    pixg = pixScaleToGray(pixs, 0.25);
    pixd = pixGrayMorphSequence(pixg, SEQUENCE3, -5, 150);
    pixDestroy(&pixd);
    pixd = pixGrayMorphSequence(pixg, SEQUENCE3, DISPLAY_SEPARATION, 150);
    pixWrite("/tmp/morphseq5.png", pixd, IFF_PNG);
    pixDestroy(&pixd);

    pixd = pixGrayMorphSequence(pixg, SEQUENCE4, -6, 300);
    pixWrite("/tmp/morphseq6.png", pixd, IFF_PNG);
    pixDestroy(&pixd);

        /* 32 bpp */
    pixc = pixRead("wyom.jpg");
    pixd = pixColorMorphSequence(pixc, SEQUENCE5, -7, 150);
    pixDestroy(&pixd);
    pixd = pixColorMorphSequence(pixc, SEQUENCE5, DISPLAY_SEPARATION, 450);
    pixWrite("/tmp/morphseq7.png", pixd, IFF_PNG);
    pixDestroy(&pixc);
    pixDestroy(&pixd);

        /* Syntax error handling */
    fprintf(stderr, " ------------ Error messages follow ------------------\n");
    pixd = pixMorphSequence(pixs, BAD_SEQUENCE, 50);  /* fails; returns null */
    pixd = pixGrayMorphSequence(pixg, BAD_SEQUENCE, 50, 0);  /* this fails */

    pixDestroy(&pixg);
    pixDestroy(&pixs);
    return 0;
}


text:
import { Component } from '@angular/core';

@Component({
  selector: 'app-bio',
  templateUrl: './section.bio.component.html'
})

export class SectionBioComponent { }


text:
package com.amazonaws.services.cloudhsm.model.transform;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.cloudhsm.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;

/**
 * CreateHapgRequest Marshaller
 */
public class CreateHapgRequestMarshaller implements
        Marshaller<Request<CreateHapgRequest>, CreateHapgRequest> {

    private final SdkJsonProtocolFactory protocolFactory;

    public CreateHapgRequestMarshaller(SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<CreateHapgRequest> marshall(
            CreateHapgRequest createHapgRequest) {

        if (createHapgRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<CreateHapgRequest> request = new DefaultRequest<CreateHapgRequest>(
                createHapgRequest, "AWSCloudHSM");
        request.addHeader("X-Amz-Target", "CloudHsmFrontendService.CreateHapg");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final StructuredJsonGenerator jsonGenerator = protocolFactory
                    .createGenerator();

            jsonGenerator.writeStartObject();

            if (createHapgRequest.getLabel() != null) {
                jsonGenerator.writeFieldName("Label").writeValue(
                        createHapgRequest.getLabel());
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", jsonGenerator.getContentType());
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
FROM golang:latest

# Google Cloud platform API libraries
RUN apt-get update && apt-get install -y python-pip && apt-get clean
RUN pip install --upgrade google-api-python-client

#====================
# Python dependencies

# Install dependencies

RUN apt-get update && apt-get install -y \
    python-all-dev \
    python3-all-dev \
    python-pip

# Install Python packages from PyPI
RUN pip install pip --upgrade
RUN pip install virtualenv
RUN pip install futures==2.2.0 enum34==1.0.4 protobuf==3.2.0 six==1.10.0

# Using login shell removes Go from path, so we add it.
RUN ln -s /usr/local/go/bin/go /usr/local/bin

# Define the default command.
CMD ["bash"]


text:
package it.sauronsoftware.ftp4j.listparsers;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import it.sauronsoftware.ftp4j.FTPFile;
import it.sauronsoftware.ftp4j.FTPListParseException;
import it.sauronsoftware.ftp4j.FTPListParser;

/**
 * This parser can handle the MSDOS-style LIST responses.
 *
 * @author Carlo Pelliccia
 */
public class DOSListParser implements FTPListParser {

	private static final Pattern PATTERN = Pattern
			.compile("^(\\d{2})-(\\d{2})-(\\d{2})\\s+(\\d{2}):(\\d{2})(AM|PM)\\s+"
					+ "(<DIR>|\\d+)\\s+([^\\\\/*?\"<>|]+)$");

	private static final DateFormat DATE_FORMAT = new SimpleDateFormat(
			"MM/dd/yy hh:mm a");

	public FTPFile[] parse(String[] lines) throws FTPListParseException {
		int size = lines.length;
		FTPFile[] ret = new FTPFile[size];
		for (int i = 0; i < size; i++) {
			Matcher m = PATTERN.matcher(lines[i]);
			if (m.matches()) {
				String month = m.group(1);
				String day = m.group(2);
				String year = m.group(3);
				String hour = m.group(4);
				String minute = m.group(5);
				String ampm = m.group(6);
				String dirOrSize = m.group(7);
				String name = m.group(8);
				ret[i] = new FTPFile();
				ret[i].setName(name);
				if (dirOrSize.equalsIgnoreCase("<DIR>")) {
					ret[i].setType(FTPFile.TYPE_DIRECTORY);
					ret[i].setSize(0);
				} else {
					long fileSize;
					try {
						fileSize = Long.parseLong(dirOrSize);
					} catch (Throwable t) {
						throw new FTPListParseException();
					}
					ret[i].setType(FTPFile.TYPE_FILE);
					ret[i].setSize(fileSize);
				}
				String mdString = month + "/" + day + "/" + year + " " + hour
						+ ":" + minute + " " + ampm;
				Date md;
				try {
					synchronized (DATE_FORMAT) {
						md = DATE_FORMAT.parse(mdString);
					}
				} catch (ParseException e) {
					throw new FTPListParseException();
				}
				ret[i].setModifiedDate(md);
			} else {
				throw new FTPListParseException();
			}
		}
		return ret;
	}

}


text:
<!doctype html>

	<meta charset="utf-8">
	<title>Multiple reload test</title>

	<link rel="stylesheet" href="../css/style.css" type="text/css"/>

		browse other examples

Multiple reload test

			<button ng-click="show = !show"> Do single reload</button>
			<button ng-click="doMultipleReload()"> Do multiple reload</button>
			Loading: {{adapter.isLoading}}

{{item}}


text:
package com.intellij.openapi.actionSystem;

import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.util.SystemInfo;
import javax.annotation.Nonnull;

import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

public class CommonShortcuts {

  private CommonShortcuts() {}

  public static final ShortcutSet ALT_ENTER = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.ALT_DOWN_MASK));
  public static final ShortcutSet ENTER = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
  public static final ShortcutSet CTRL_ENTER = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,
                                                                                SystemInfo.isMac
                                                                                ? InputEvent.META_DOWN_MASK
                                                                                : InputEvent.CTRL_DOWN_MASK));
  public static final ShortcutSet INSERT = new CustomShortcutSet(getInsertKeystroke());

  /**
   * @deprecated use getDelete() instead to support keymap-specific and user-configured shortcuts
   */
  public static final ShortcutSet DELETE = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
  public static final ShortcutSet ESCAPE = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));

  public static final ShortcutSet DOUBLE_CLICK_1 = new CustomShortcutSet(new MouseShortcut(MouseEvent.BUTTON1, 0, 2));

  public static final ShortcutSet MOVE_UP = CustomShortcutSet.fromString("alt UP");
  public static final ShortcutSet MOVE_DOWN = CustomShortcutSet.fromString("alt DOWN");

  public static ShortcutSet getNewForDialogs() {
    final ArrayList<Shortcut> shortcuts = new ArrayList<Shortcut>();
    for (Shortcut shortcut : getNew().getShortcuts()) {
      if (isCtrlEnter(shortcut)) continue;
      shortcuts.add(shortcut);
    }
    return new CustomShortcutSet(shortcuts.toArray(new Shortcut[shortcuts.size()]));
  }

  private static boolean isCtrlEnter(Shortcut shortcut) {
    if (shortcut instanceof KeyboardShortcut) {
      KeyStroke keyStroke = ((KeyboardShortcut)shortcut).getFirstKeyStroke();
      return keyStroke.getKeyCode() == KeyEvent.VK_ENTER && (keyStroke.getModifiers() & InputEvent.CTRL_MASK) != 0;
    }
    return false;
  }

  public static KeyStroke getInsertKeystroke() {
    return SystemInfo.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK)
                            : KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0);
  }

  public static ShortcutSet getCopy() {
    return shortcutsById(IdeActions.ACTION_COPY);
  }

  public static ShortcutSet getPaste() {
    return shortcutsById(IdeActions.ACTION_PASTE);
  }

  public static ShortcutSet getRerun() {
    return shortcutsById(IdeActions.ACTION_RERUN);
  }

  public static ShortcutSet getEditSource() {
    return shortcutsById(IdeActions.ACTION_EDIT_SOURCE);
  }

  public static ShortcutSet getViewSource() {
    return shortcutsById(IdeActions.ACTION_VIEW_SOURCE);
  }

  public static ShortcutSet getNew() {
    return shortcutsById(IdeActions.ACTION_NEW_ELEMENT);
  }

  public static ShortcutSet getDuplicate() {
    return shortcutsById(IdeActions.ACTION_EDITOR_DUPLICATE);
  }

  public static ShortcutSet getMove() {
    return shortcutsById(IdeActions.ACTION_MOVE);
  }

  public static ShortcutSet getRename() {
    return shortcutsById(IdeActions.ACTION_RENAME);
  }

  public static ShortcutSet getDiff() {
    return shortcutsById(IdeActions.ACTION_SHOW_DIFF_COMMON);
  }

  public static ShortcutSet getFind() {
    return shortcutsById(IdeActions.ACTION_FIND);
  }

  public static ShortcutSet getContextHelp() {
    return shortcutsById(IdeActions.ACTION_CONTEXT_HELP);
  }

  public static ShortcutSet getCloseActiveWindow() {
    return shortcutsById(IdeActions.ACTION_CLOSE);
  }

  public static ShortcutSet getMoveUp() {
    return shortcutsById(IdeActions.ACTION_EDITOR_MOVE_CARET_UP);
  }

  public static ShortcutSet getMoveDown() {
    return shortcutsById(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN);
  }

  public static ShortcutSet getMovePageUp() {
    return shortcutsById(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_UP);
  }

  public static ShortcutSet getMovePageDown() {
    return shortcutsById(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_DOWN);
  }

  public static ShortcutSet getMoveHome() {
    return shortcutsById(IdeActions.ACTION_EDITOR_MOVE_LINE_START);
  }

  public static ShortcutSet getMoveEnd() {
    return shortcutsById(IdeActions.ACTION_EDITOR_MOVE_LINE_END);
  }

  public static ShortcutSet getRecentFiles() {
    return shortcutsById(IdeActions.ACTION_RECENT_FILES);
  }

  public static ShortcutSet getDelete() {
    return shortcutsById(IdeActions.ACTION_DELETE);
  }

  @Nonnull
  private static CustomShortcutSet shortcutsById(String actionId) {
    Application application = ApplicationManager.getApplication();
    KeymapManager keymapManager = application == null ? null : application.getComponent(KeymapManager.class);
    if (keymapManager == null) {
      return new CustomShortcutSet(Shortcut.EMPTY_ARRAY);
    }
    return new CustomShortcutSet(keymapManager.getActiveKeymap().getShortcuts(actionId));
  }
}


text:
category: catalog
layout: catalog
show_products: true
spread: true
published: true
title: Everyday
slug: everyday
directory: everyday
pdf: Everyday_Catalog_No_Price.pdf
cover: Everyday_Catalog_No_Price.jpg
filebase: pages/Everyday_Catalog_No_Price
extension: jpg
numslides: '15'
---


text:
A PartType can be seen as a group that several parts fit in, e.g. `items`

## Importing the package
It might be required for you to import the package if you encounter any issues, so better be safe than sorry and add the import.
`import mods.contenttweaker.PartType;`

## Retrieving such an object
You can use the [MaterialSystem](/Mods/ContentTweaker/Materials/MaterialSystem/) to either retrieve an existing PartType object or create an entirely new one.
Check out below entry to learn how to create a new PartType.

	Following types are pre-registered:

item

block

ore

fluid

armor

minecart

## ZenMethods
You can retrieve the following information from a PartType:

| ZenMethod            | Return Type                            |
|----------------------|----------------------------------------|
| getName()            | string                                 |

You can set the following information on a PartType:

| ZenMethod                       | Parameter Type                         |
|---------------------------------|----------------------------------------|
| setData(IPartDataPiece[] data); | [IPartDataPiece](/Mods/ContentTweaker/Materials/Parts/PartDataPiece/)[] data |

## Create a new PartType
If you, for whatever reason would ever need to register a new PartType, you will need to know two things:

- What name the new partType will have
- How [MaterialParts](/Mods/ContentTweaker/Materials/Materials/MaterialPart/) created from [Parts](/Mods/ContentTweaker/Materials/Parts/Part/) that are of this type will be registered

The first is simple, it's a string.
The second is a bit trickier, it's a function that takes a MaterialPart as input:

```zenscript
#loader contenttweaker

import mods.contenttweaker.MaterialSystem;

val ourType = MaterialSystem.createPartType("cool_type", function(materialPart){

});

//Use the new type to create a Part
val ourPart = mods.contenttweaker.MaterialSystem.getPartBuilder().setName("cool_part").setPartType(ourType).build();

//Create a new Material and register the newly created part.
val ourMaterial = MaterialSystem.getMaterialBuilder().setName("Lawrencium").setColor(15426660).build();
ourMaterial.registerPart(ourPart);

```


text:
SYNONYM

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
J. Bot. Soc. Imp. Nat. St. -Petersb. 3: 124.

#### Original name
null

### Remarks
null


text:
```scala mdoc:invisible:reset-object
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.SparkSession
import frameless.functions.aggregate._
import frameless.TypedDataset

val conf = new SparkConf().setMaster("local[*]").setAppName("frameless repl").set("spark.ui.enabled", "false")
implicit val spark = SparkSession.builder().config(conf).appName("REPL").getOrCreate()
spark.sparkContext.setLogLevel("WARN")

import spark.implicits._
```
Injection lets us define encoders for types that do not have one by injecting `A` into an encodable type `B`.
This is the definition of the injection typeclass:
```scala
trait Injection[A, B] extends Serializable {
  def apply(a: A): B
  def invert(b: B): A
}
```

## Example

Let's define a simple case class:

```scala mdoc
case class Person(age: Int, birthday: java.util.Date)
val people = Seq(Person(42, new java.util.Date))
```

And an instance of a `TypedDataset`:

```scala mdoc:fail:nest
val personDS = TypedDataset.create(people)
```

Looks like we can't, a `TypedEncoder` instance of `Person` is not available, or more precisely for `java.util.Date`.
But we can define a injection from `java.util.Date` to an encodable type, like `Long`:

```scala mdoc
import frameless._
implicit val dateToLongInjection = new Injection[java.util.Date, Long] {
  def apply(d: java.util.Date): Long = d.getTime()
  def invert(l: Long): java.util.Date = new java.util.Date(l)
}
```

We can be less verbose using the `Injection.apply` function:

```scala mdoc:nest
import frameless._
implicit val dateToLongInjection = Injection((_: java.util.Date).getTime(), new java.util.Date((_: Long)))
```

Now we can create our `TypedDataset`:

```scala mdoc
val personDS = TypedDataset.create(people)
```

```scala mdoc:invisible
spark.stop()
```

## Another example

```scala mdoc:invisible:reset-object
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.SparkSession
import frameless.functions.aggregate._
import frameless.TypedDataset

val conf = new SparkConf().setMaster("local[*]").setAppName("frameless repl").set("spark.ui.enabled", "false")
implicit val spark = SparkSession.builder().config(conf).appName("REPL").getOrCreate()
spark.sparkContext.setLogLevel("WARN")

import spark.implicits._
```

Let's define a sealed family:

```scala mdoc
sealed trait Gender
case object Male extends Gender
case object Female extends Gender
case object Other extends Gender
```

And a simple case class:

```scala mdoc
case class Person(age: Int, gender: Gender)
val people = Seq(Person(42, Male))
```

Again if we try to create a `TypedDataset`, we get a compilation error.

```scala mdoc:fail:nest
val personDS = TypedDataset.create(people)
```

Let's define an injection instance for `Gender`:

```scala mdoc
import frameless._
implicit val genderToInt: Injection[Gender, Int] = Injection(
  {
    case Male   => 1
    case Female => 2
    case Other  => 3
  },
  {
    case 1 => Male
    case 2 => Female
    case 3 => Other
  })
```

And now we can create our `TypedDataset`:

```scala mdoc
val personDS = TypedDataset.create(people)
```

```scala mdoc:invisible
spark.stop()
```

Alternatively, an injection instance can be derived for sealed families such as `Gender` using the following
import, `import frameless.TypedEncoder.injections._`. This will encode the data constructors as strings.

**Known issue**: An invalid injection instance will be derived if there are data constructors with the same name.
For example, consider the following sealed family:

```scala mdoc
sealed trait Foo
object A { case object Bar extends Foo }
object B { case object Bar extends Foo }
```

`A.Bar` and `B.Bar` will both be encoded as `"Bar"` thereby breaking the law that `invert(apply(x)) == x`.


text:
using System;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
    [Export(typeof(FileChangeWatcherProvider))]
    internal sealed class FileChangeWatcherProvider
    {
        private readonly TaskCompletionSource<IVsFileChangeEx> _fileChangeService = new TaskCompletionSource<IVsFileChangeEx>(TaskCreationOptions.RunContinuationsAsynchronously);
        private readonly Lazy<FileChangeWatcher> _fileChangeWatcher;

        public FileChangeWatcherProvider()
        {
            _fileChangeWatcher = new Lazy<FileChangeWatcher>(() => new FileChangeWatcher(_fileChangeService.Task));
        }

        public FileChangeWatcher Watcher => _fileChangeWatcher.Value;

        internal void SetFileChangeService(IVsFileChangeEx fileChangeService)
        {
            _fileChangeService.TrySetResult(fileChangeService);
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Question extends Admin_panel
{
	public $data = array();

	public $per_page;

	public $page;

	public $query;

	public function __construct()
	{
		parent::__construct();

		$this->breadcrumbs->unshift(1, 'Polling', "index");

		$this->load->js(base_url("public/admin/app/main.js"));

		$this->per_page = (!$this->input->get('per_page')) ? 15 : $this->input->get('per_page');

		$this->page = $this->input->get('page');

		$this->query = $this->input->get('query');
	}

	public function index()
	{
		$this->page_title->push('Polling', 'Manajemen poliing berita');

		$config = $this->template->pagination_list();

		$config['base_url'] = site_url("
			administrator/question?per_page={$this->per_page}&query={$this->query}
		");

		$config['per_page'] = $this->per_page;
		$config['total_rows'] = $this->polling->get_question_pg(null, null, 'num');

		$this->pagination->initialize($config);

		$this->data = array(
			'title' => "Manajemen Polling",
			'questions' => $this->polling->get_question_pg($this->per_page, $this->page)
		);

		$this->template->admin('pquestion', $this->data);
	}

	public function create()
	{
		$this->page_title->push('Tambah', 'Manajemen polling berita');

		$this->breadcrumbs->unshift(2, 'Tambah Polling', "index");

		$this->form_validation->set_rules('question', 'Pertanyaan Polling', 'trim|required');

		if( $this->form_validation->run() == TRUE )
		{
			$this->polling->create_polling();

			redirect(current_url());
		}

		$this->data = array(
			'title' => "Tambah Polling"
		);

		$this->template->admin('createquestion', $this->data);
	}

	public function update($param = 0)
	{
		$question = $this->polling->get_question($param);

		if( $question == FALSE)
			show_404();

		$this->page_title->push('Update', 'Manajemen polling berita');

		$this->breadcrumbs->unshift(2, 'Update Polling', "index");

		$this->form_validation->set_rules('question', 'Pertanyaan Polling', 'trim|required');

		if( $this->form_validation->run() == TRUE )
		{
			$this->polling->update_polling( $param );

			redirect(current_url());
		}

		$this->data = array(
			'title' => "Update Polling",
			'question' => $question
		);

		$this->template->admin('updatequestion', $this->data);
	}

	public function delete($param = 0)
	{
		$this->polling->delete( $param );

		redirect(base_url("administrator/question"));
	}

	public function deleteanswer($param = 0)
	{
		$this->response = $this->polling->delete_answer($param);

		$this->output->set_content_type('application/json')->set_output(json_encode($this->response));
	}
}

/* End of file Question.php */
/* Location: ./application/controllers/administrator/Question.php */


text:
In courtesy of the Husky team. Special thanks to Yuzhen Huang. This repo serves as a demo for the course project. Please do not be limited to it and feel free to use or modify the codes to suit your own design. You may also choose a completely different design.

## Install & Run
Git clone this repository by
```sh
git clone https://github.com/TatianaJin/csci5570.git
cd csci5570
```
Create a directory for putting compiled files, and configure cmake.
```
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Debug
```
See the make list by `make help`, and make anything in the list by `make ${ANYTHING}`

```
cd build/     # cd to the build directory
make -j4      # build all the targets
./HuskyUnitTest  # run all unit tests
./HuskyUnitTest --gtest_filter=TestServerThread.RegisterModel  # run a specific test
```
### Some tools:
* [glog](http://rpg.ifi.uzh.ch/docs/glog.html). You may use `GLOG_logtostderr=1 ./HuskyUnitTest` to print the `LOG(INFO)` information to the console.
* [gtest](https://github.com/google/googletest/blob/master/googletest/docs/Primer.md).
* Actor model
* cmake
* C++ (C++11, multi-threading, std::move, rvalue reference, classes...)

## Overview

![Mind map](mindmap.svg)

Below are the milestones for each week.

## Milestone 1: Get familiar with the communication module and actor abstraction
* The mailbox is provided as a bottom layer communication module
* The prototypes of server threads, worker threads, and communication threads are also provided for your reference
* There are some utility files for compilation and testing for your reference

## Milestone 2: Create server threads and their model storage
* Check the overall picture about the worker and server in `test/test_worker.cpp` and `test/test_server.cpp`.
* Understand how the modules on the server side work together.
* Implement `server_thread.cpp` according to the information given in `server_thread_test.cpp`.
* Implement `map_storage.hpp` according to the information given in `map_storage_test.cpp`.

## Milestone 3: Distribute the model to servers
* Check `base/abstract_partition_manager.hpp` and implement your parititoning strategies
* You should have tried implementing MapStorage in the previous milestone. You may try other storage method such as using vector.
* Write a small program to link the paritition manager with the storages and to initialize storages associated with different server threads

## Milestone 4: Now the workers come into play
* Check `worker/kv_client_table_test.cpp`. Understand how `AbstractCallbackRunner` and `AbstractPartitionManager` functions and how the modules on the worker side work together
* Understand how model parameters are rendered to users in the process from mailbox receiving messages, to worker threads invoking callbacks, and finally to KVClientTable returning with completed requests
* Implement a callback runner to handle reply messages
* Implement [KVClientTable](worker/kv_client_table.hpp) according to the information given in `worker/kv_client_table_test.cpp`

## Milestone 5: Feed the training data
* Check the io folder and understand how to connect to HDFS and coordinate data loading among workers
* Take a look at test/test_hdfs_read.cpp and see how the connector may be used to load data
* Check the lib folder for the abstraction of data loaders and labeled sample
* Implement the data loaders and parsers. Understanding the producer-consumer paradigm may help

## Milestone 6: Orders are to be established
* Check the tests for the three consistency models and understand the expected behaviors
* Check the pending buffer and progress tracker interface
* Implement ASP, BSP, and SSP models

## Milestone 7: Put together and run
* Check the tests and complete engine.cpp, info.hpp, simple_id_mapper.cpp, and worker_spec.cpp
* Write a script to launch the system on the cluster

### Hints for the driver part
Here I highlight some hints for the driver of the user program

#### Worker threads in Engine, SimpleIdMapper, Info
There are two kinds of worker threads:
1. User worker thread (spawned in `Engine::Run`, corresponding to `SimpleIdMapper::node2worker_` and user thread in the mind map). User worker threads run the UDF specified in tasks, i.e. carry out the main computation. The `worker_id` and `thread_id` of each user worker thread is allocated via `Engine::AllocateWorkers` and can be fetched from the returned `WorkerSpec` instance. The `worker_id` and `thread_id` should be put into an `Info` instance and passed to the UDF.
2. Worker helper thread (corresponding to `Engine::worker_thread_`, `SimpleIdMapper::kWorkerHelperThreadId`, `SimpleIdMapper::node2worker_helper_`, and WorkerThread in the mind map). This thread is responsible to invoke the callbacks registered by `KVClientTable` through an `AbstractCallbackRunner` instance. Namely, this thread works in the background to help handle the reponses to the get requests issued by the user worker threads. Please notice that the `AbstractCallbackRunner` should contain the callbacks for each `KVClientTable` instance owned by the user workers. Do not just copy the `FakeCallbackRunner` I implemented in the test files, which has only two callbacks.

#### The constants in SimpleIdMapper
There are four constants: `kMaxNodeId`, `kMaxThreadsPerNode`, `kMaxBgThreadsPerNode`, and `kWorkerHelperThreadId`.
1. The id range for each node i is [i * `kMaxThreadsPerNode`, (i+1) * `kMaxThreadsPerNode`).
2. The server threads use the range [i * `kMaxThreadsPerNode`, i * `kMaxThreadsPerNode` + `kWorkerHelperThreadId`), and server ids are allocated using `SimpleIdMapper::Init`.
3. The worker threads (in the background, also referred as worker helper threads) use the range [i * `kMaxThreadsPerNode` + `kWorkerHelperThreadId`, i * `kMaxThreadsPerNode` + `kMaxBgThreadsPerNode`), also allocated using `SimpleIdMapper::Init`.
4. The user worker threads created when running the task use the range [i * `kMaxThreadsPerNode` + `kMaxBgThreadsPerNode`, i * `kMaxThreadsPerNode` + `kMaxThreadsPerNode`). The user worker ids are manipulated by `SimpleIdMapper::AllocateWorkerThread` and `SimpleIdMapper::DeallocateWorkerThread`.


text:
/*
 * server.js is Express middleware that handles HTTP requests for OSLC resources.
 */

var express = require('express');
var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var rdflib = require('rdflib')
var media = require('./media.js'); // media types

var	appBase = null; // Used to formlate the full URI for absolute URLs in the database

/*
 * Middleware to set the full URI for the request for use in
 * storage identifiers.
 */
var fullURL = function fullURL(req, res, next) {
	req.fullURL = appBase + req.originalUrl;
	next();
}

/*
 * Middleware to create a UTF8 encoded copy of the original request body
 * used in JSON and N3 parsers.
 */
var rawBody = function rawBody(req, res, next) {
	req.rawBody = '';
	req.setEncoding('utf8');

	req.on('data', function(chunk) {
		req.rawBody += chunk;
	});

	req.on('end', function() {
		next();
	});
}

/*
 * Middleware to handle all OSLC requests
 */
var oslcRoutes = function(env) {
	// some useful global variables added to exports
	var ldp = require('./vocab/ldp.js'); // LDP vocabulary
	var rdf = require('./vocab/rdf.js'); // RDF vocabulary
	var oslc = require('./vocab/oslc.js');
	var ldpService = require('./ldp');
	ldpService.init(env);

	var oslcApp = express();
	oslcApp.use(fullURL);
	oslcApp.use(rawBody);

	// anything not previously handled will be handled by oslcApp
	var oslcRoute = oslcApp.route(env.context+'*');

	// route any requests matching the LDP context (defaults to /r/*)
	oslcRoute.all(function(req, res, next) {
		// all responses should have Link: <ldp:Resource> rel=type
		var links = {
			type: ldp.Resource
		}
		// also include implementation constraints
		links[ldp.constrainedBy] = env.appBase + '/constraints.html'
		res.links(links)
		next()
	});

	oslcRoute.options(function(req, res, next) {
		ldpService.options(req, res, (status) => {
			res.status(status).end();
		});
	});

	// Also handles head
	oslcRoute.get(function(req, res, next) {
		// look for Accept=application/x-oslc-compact+xml for Compact representation
		// Handle selective properties
		ldpService.get(req, res, (status, document) => {
			if (status !== 200) {
				res.status(status).send(`Cannot get resource ${req.originalUrl}: ${status}\n`);
				return;
			}
			// determine what format to serialize using the Accept header
			var serialize
			if (req.accepts(media.turtle)) {
				serialize = media.turtle
			} else if (req.accepts(media.jsonld) || req.accepts(media.json)) {
				serialize = media.jsonld
			} else if (req.accepts(media.rdfxml)) {
				serialize = media.rdfxml
			} else {
				res.status(406).send('Not allowed\n');
				return;
			}
			// Serialize the resource
			// target must be undefined, and base set to an unused prefix to get the proper namespaces and URIs
			rdflib.serialize(document.sym(req.fullURL), document, "none:", serialize, function(err, content) {
				if (err) {
					console.log(err.stack);
					res.status(500).send(`Error searializing ${req.fullURL}\n`);
					return;
				}
				// generate an ETag for the content
				var eTag = ldpService.getETag(content);
				if (req.get('If-None-Match') === eTag) {
					res.status(304).send(`ETag did not match on ${req.fullURL}\n`);
					return;
				}

				res.setHeader('ETag', eTag);
				res.setHeader('Content-Type', serialize);
				res.status(200).send(new Buffer(content));
			});
		});
	});

	oslcRoute.post(function(req, res, next) {
		// handled by ldp-service
		next();
	});

	oslcRoute.put(function(req, res, next) {
		// handled by ldp-service
		next();
	});

	oslcRoute.delete(function(req, res, next) {
		// handled by ldp-service
		next();
	});
	return oslcApp;
}

module.exports = function(env) {
	appBase = env.appBase
	// TODO: initialize the database from the ServiceProviderCatalog provided in the env.services
	return oslcRoutes(env);
}


text:
// Dreem/Dali server
require = require('./system/base/define') // support define.js modules

// load up math core and make it global
require('$system/base/math')

if(process.argv.indexOf('-nomoni') != -1){
	define.atRequire = function(filename){
		process.stderr.write('\x0F' + filename + '\n', function(){})
	}
}

var fs = require('fs')
var path = require('path')

// ok now we can require components
var ansicolor = require('$system/debug/ansicolor')
console.color = ansicolor(function(v){
	process.stdout.write(v)
})

console.clear = function(){
	process.stdout.write("\033[2J");
}

console.setposition = function(x, y){
	process.stdout.write("\033[" + y.toString() + ";" + x.toString() + "f")
}

// make a nice console.dump function
var dump = require('$system/debug/dump')
console.dump = function(){
	// lets grab where we are called
	console.log(new Error().stack)
	console.color(dump(Array.prototype.slice.apply(arguments), 1000000, dump.colors))
}

function main(){
	var argv = process.argv
	var args = {}
	for(var lastkey = '', arg, i = 0; i<argv.length; i++){
		arg = argv[i]
		if(arg.charAt(0) == '-') lastkey = arg, args[lastkey] = true
		else {
			if(lastkey in args && args[lastkey] !== true){
				if(!Array.isArray(args[lastkey])) args[lastkey] = [args[lastkey]]
				args[lastkey].push(arg)
			}
			else args[lastkey] = arg
		}
	}

	if(args['-nomoni'] && args['-trace']){
		var trace = require('$system/debug/trace')
		define.atModule = function(module){
			module.exports = trace(module.exports, module.filename, args['-trace'])
		}
	}

	if(args['-h'] || args['-help'] || args['--h'] || args['--help']){
		console.color('~by~Teem~~ Server ~bm~2.0~~\n')
		console.color('commandline: node server.js <flags>\n')
		console.color('~bc~-port ~br~[port]~~ Server port\n')
		console.color('~bc~-nomoni ~~ Start process without monitor\n')
		console.color('~bc~-iface ~br~[interface]~~ Server interface\n')
		console.color('~bc~-restart~~ Auto restarts after crash (Handy for client dev, not server dev)\n')
		console.color('~bc~-path~~ [name]:~br~[directory]~~ add a path to the server under name $name\n')
		console.color('~bc~-dali~~ run a composition in DALi\n')
		console.color('~bc~-dalilib~~ can be used to point to the DALi node-addon installation folder on Ubuntu (only to be used in combination with the ~bc~-dali~~ flag)\n')
		console.color('~bc~-writefile ~~ Allow server to write files to disk\n')
		return process.exit(0)
	}

	// our default pathmap
	// NOTE: if you change this, also update /docs/guides/dreem_in_10/README.md
	define.paths = {
		'system':'$root/system',
		'resources':'$root/resources',
		'3d':'$root/classes/3d',
		'behaviors':'$root/classes/behaviors',
		'server':'$root/classes/server',
		'ui':'$root/classes/ui',
		'flow':'$root/classes/flow',
		'testing':'$root/classes/testing',
		'widgets':'$root/classes/widgets',
		'sensors':'$root/classes/sensors',
		'iot':'$root/classes/iot',
		'examples':'$root/examples',
		'apps':'$root/apps',
		'docs':'$root/docs',
		'test':'$root/test'
	}

	if(args['-writefile']){
		Object.defineProperty(define, "$writefile", {
		    value: true,
		    writable: false
		});
	}
	else{
		Object.defineProperty(define, "$writefile", {
		    value: false,
		    writable: false
		});
	}

	if(args['-unsafeorigin']){
		Object.defineProperty(define, "$unsafeorigin", {
			value: true,
			writable: false
		});
	}
	else{
		Object.defineProperty(define, "$unsafeorigin", {
			value: false,
			writable: false
		});
	}

	if(args['-nomoni']){
		var paths = Array.isArray(args['-path'])?args['-path']:[args['-path']]
		for(var i = 0; i < paths.length; i++){
			if(!paths[i]) continue
			var parts = paths[i].split(':')
			var mypath =	parts[1].charAt(0) === '/'? parts[1]: define.joinPath(define.$root, parts[1])
			console.log('Mapping '+parts[0]+' to ' + mypath)
			define.paths[parts[0]] = mypath
		}
		// put them on the define
		for(var key in define.paths){
			define['$'+key] = define.paths[key]
		}
	}

	define.$platform = 'headless'

	if (args['-jsduckgen']) {
		define.$platform = 'nodejs'
		for(var key in define.paths){
			define['$'+key] = define.paths[key]
		}

		var DocBuilder = require('$system/server/docbuilder')
		new DocBuilder(args)

	} else if(args['-nodegl']){
		// lets do an async require on our UI
		define.$platform = 'nodegl'
		var NodeGL = require('$system/platform/nodegl/bootnodegl')
		new NodeGL(args)
	}
	else if(args['-nomoni']){
		if(args['-sync']){
			var GitSync = require('$system/server/gitsync')

			new GitSync(args)
		}
		else if(args['-headless']){
				var composition = args['-headless'];
				define.$platform = 'headless'
				define.$environment = 'headless' // Otherwise it is nodejs

			//TODO
			// Store the path from the root to the specified directory.
			// There is a mismatch between headless and dreem server.
			var index = composition.lastIndexOf('/');
			if (index < 0) index = composition.lastIndexOf('\\');
			define.$example = (index >= 0) ? composition.substring(0,index+1) : './'
			try {
				// The images are relative to ths specified directory
				if (fs.statSync(composition).isDirectory())
					define.$example = './' + composition + '/'
			}
			catch (e) {
			}

			var BootHeadless = require('$system/platform/headless/bootheadless')
			new BootHeadless(args, composition);
		}
		else if(args['-dali']){
			// Place the dali/nodejs package at the root of dreemgl

				var composition = args['-dali'];
				if (composition === true)
					composition = 'examples/rendertest'

				define.$platform = 'dali'
				define.$environment = 'dali' // Otherwise it is nodejs

			//TODO
			// Store the path from the root to the specified directory.
			// There is a mismatch between dali and dreem server.
			var index = composition.lastIndexOf('/');
			define.$example = (index >= 0) ? composition.substring(0,index+1) : './'
			try {
				// The images are relative to ths specified directory
				if (fs.statSync(composition).isDirectory())
					define.$example = './' + composition + '/'
			}
			catch (e) {
			}

				var BootDali = require('$system/platform/dali/bootdali')
				new BootDali(args, composition);
		}
		else if(args['-test']){
			require('$system/server/test.js')

		}
		else{
			define.$platform = 'nodejs'
			var RootServer = require('$system/server/rootserver')
			new RootServer(args)
		}

	}
	else{
		var RunMonitor = require('$system/server/runmonitor')
		new RunMonitor(args)
	}
}

main()


text:
package com.erm.controller;

import com.erm.ejb.UndMedidaFacadeLocal;
import com.erm.model.UndMedida;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@ViewScoped
public class UndMedidaController implements Serializable{

    @EJB
    private UndMedidaFacadeLocal UndMedidaEJB;
    private List<UndMedida> lstundmedida;

    @Inject
    private UndMedida undmedida;

    @PostConstruct
    public void init(){
        lstundmedida = UndMedidaEJB.findAll();
    }

    //Getter & Setter

    public UndMedidaFacadeLocal getUndMedidaEJB() {
        return UndMedidaEJB;
    }

    public void setUndMedidaEJB(UndMedidaFacadeLocal UndMedidaEJB) {
        this.UndMedidaEJB = UndMedidaEJB;
    }

    public List<UndMedida> getLstundmedida() {
        return lstundmedida;
    }

    public void setLstundmedida(List<UndMedida> lstundmedida) {
        this.lstundmedida = lstundmedida;
    }

    public UndMedida getUndmedida() {
        return undmedida;
    }

    public void setUndmedida(UndMedida undmedida) {
        this.undmedida = undmedida;
    }

    public void registrar(){
        try{
            UndMedidaEJB.create(undmedida);
            lstundmedida = UndMedidaEJB.findAll();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "Registro Exitoso."));
        }catch(Exception e){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Registro Falló."));
        }
    }

}


text:
import * as GeoJSON from 'geojson';

interface PolygonConfig {
    earthRadius?: number;
    numberOfEdges?: number;
    bearing?: number;
    rightHandRule?: boolean;
}

declare function circleToPolygon(
    center: GeoJSON.Position,
    radius: number,
    numberOfSegments?: number | PolygonConfig,
): GeoJSON.Polygon;

export = circleToPolygon;


text:
/*
 * jQuery UI Virtual Keyboard Navigation v1.2 for Keyboard v1.8.14+ only
 *
 * By Rob Garrison (aka Mottie & Fudgey)
 * Licensed under the MIT License
 *
 * Use this extension with the Virtual Keyboard to navigate
 * the virtual keyboard keys using the arrow, page, home and end keys
 * Using this extension WILL prevent keyboard navigation inside of all
 * input and textareas
 *
 * Requires:
 *  jQuery
 *  Keyboard plugin : https://github.com/Mottie/Keyboard
 *
 * Setup:
 *  $('.ui-keyboard-input')
 *   .keyboard(options)
 *   .addNavigation();
 *
 *  // or if targeting a specific keyboard
 *  $('#keyboard1')
 *   .keyboard(options)     // keyboard plugin
 *   .addNavigation();    // this keyboard extension
 *
 */
/*jshint browser:true, jquery:true, unused:false */
(function($){
"use strict";
$.keyboard = $.keyboard || {};

$.keyboard.navigationKeys = {
	// all keys
	toggle     : 112, // toggle key; F1 = 112 (event.which value for function 1 key)
	enter      : 13,
	pageup     : 33,
	pagedown   : 34,
	end        : 35,
	home       : 36,
	left       : 37,
	up         : 38,
	right      : 39,
	down       : 40
};

$.fn.addNavigation = function(options){

	return this.each(function(){
		// make sure a keyboard is attached
		var o, k, base = $(this).data('keyboard'),
			defaults = {
				position   : [0,0],     // set start position [row-number, key-index]
				toggleMode : false,     // true = navigate the virtual keyboard, false = navigate in input/textarea

				focusClass : 'hasFocus' // css class added when toggle mode is on
			};
		if (!base) { return; }

		base.navigation_options = o = $.extend({}, defaults, options);
		base.navigation_keys = k = $.extend({}, $.keyboard.navigationKeys);
		// save navigation settings - disabled when the toggled
		base.saveNav = [ base.options.tabNavigation, base.options.enterNavigation ];
		base.allNavKeys = $.map(k, function(v,i){ return v; });

		// Setup
		base.navigation_init = function(){

			base.$keyboard[(o.toggleMode) ? 'addClass' : 'removeClass'](o.focusClass)
				.find('.ui-keyboard-keyset:visible')
				.find('.ui-keyboard-button[data-pos="' + o.position[0] + ',' + o.position[1] + '"]')
				.addClass('ui-state-hover');

			base.$preview
			.unbind('keydown.keyboardNav')
			.bind('keydown.keyboardNav',function(e){
				return base.checkKeys(e.which);
			});

		};

		base.checkKeys = function(key, disable){
			var k = base.navigation_keys;
			if (key === k.toggle || disable) {
				o.toggleMode = (disable) ? false : !o.toggleMode;
				base.options.tabNavigation = (o.toggleMode) ? false : base.saveNav[0];
				base.options.enterNavigation = (o.toggleMode) ? false : base.saveNav[1];
			}
			base.$keyboard[(o.toggleMode) ? 'addClass' : 'removeClass'](o.focusClass);
			if ( o.toggleMode && key === k.enter ) {
				base.$keyboard
					.find('.ui-keyboard-keyset:visible')
					.find('.ui-keyboard-button[data-pos="' + o.position[0] + ',' + o.position[1] + '"]')
					.trigger('repeater.keyboard');
				return false;
			}
			if ( o.toggleMode && $.inArray(key, base.allNavKeys) >= 0 ) {
				base.navigateKeys(key);
				return false;
			}
		};

		base.navigateKeys = function(key, row, indx){
			indx = indx || o.position[1];
			row = row || o.position[0];
			var vis = base.$keyboard.find('.ui-keyboard-keyset:visible'),
				maxRow = vis.find('.ui-keyboard-button-endrow').length - 1,
				maxIndx = vis.find('.ui-keyboard-button[data-pos^="' + row + ',"]').length - 1,
				k = base.navigation_keys;

			switch(key){
				case k.pageup   : row = 0; break; // pageUp
				case k.pagedown : row = maxRow; break; // pageDown
				case k.end      : indx = maxIndx; break; // End
				case k.home     : indx = 0; break; // Home
				case k.left     : indx += (indx > 0) ? -1 : 0; break; // Left
				case k.up       : row += (row > 0) ? -1 : 0; break; // Up
				case k.right    : indx += 1; break; // Right
				case k.down     : row += (row + 1 > maxRow) ? 0 : 1; break; // Down
			}

			// get max index of new row
			maxIndx = vis.find('.ui-keyboard-button[data-pos^="' + row + ',"]').length - 1;
			if (indx > maxIndx) { indx = maxIndx; }

			vis.find('.ui-state-hover').removeClass('ui-state-hover');
			vis.find('.ui-keyboard-button[data-pos="' + row + ',' + indx + '"]').addClass('ui-state-hover');
			o.position = [ row, indx ];
		};

		// visible event is fired before this extension is initialized, so check!
		if (base.options.alwaysOpen && base.isVisible) {
			base.$keyboard.find('.ui-state-hover').removeClass('ui-state-hover');
			base.navigation_init();
		}
		// capture and simulate typing
		base.$el
			.bind('visible.keyboard', function(e){
				base.$keyboard.find('.ui-state-hover').removeClass('ui-state-hover');
				base.navigation_init();
			})
			.bind('inactive.keyboard hidden.keyboard', function(e){
				base.checkKeys(e.which, true); // disable toggle mode & revert navigation options
			})
			.bind('navigate navigateTo', function(e, row, indx){
				// no row given, check if it's a key name
				row = isNaN(row) ? row.toLowerCase() : row;
				if (base.navigation_keys.hasOwnProperty(row)) {
					base.checkKeys( base.navigation_keys[row] );
				} else {
					base.navigateKeys(null, row, indx);
				}
			});

	});
};
})(jQuery);


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp" >

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginTop="20dp"
        android:padding="5dp"
        android:gravity="center"
        android:singleLine="true"
        android:text="周杰伦"
        android:textColor="#696969"
        android:textSize="15sp" />

</RelativeLayout>


text:
layout: toiminta
title: Vuosijuhlat
permalink: /toiminta/vuosijuhlat/
---


text:
Suggest database names on bash completion

## Synopsis

Hit `<TAB>` to autocomplete database name

```
$ mysql te<TAB>
test
```

## Description

Autocompletes databases' names on the command line.

## Installation

```
$ git clone https://github.com/san650/mysql_bash_completion.git
```

And add the following script in your `~/.bash_profile` or `~/.bashrc` file.

```
source /path/to/folder/mysql_bash_completion.sh
```

## License

`mysql_bash_completion` is licensed under the MIT license.

See LICENSE for the full license text.


text:
[![Jupyter protocol][protocol-img]][protocol] [![License][license-img]][license] [![CI](https://github.com/akabe/ocaml-jupyter/actions/workflows/ci.yaml/badge.svg)](https://github.com/akabe/ocaml-jupyter/actions/workflows/ci.yaml) [![Sponsor](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=ff69b4&link=https://github.com/sponsors/srz-zumix
)](https://github.com/sponsors/akabe)

[license]:      https://github.com/akabe/ocaml-jupyter/blob/master/LICENSE
[license-img]:  https://img.shields.io/badge/license-MIT-blue.svg
[protocol]:     https://jupyter-client.readthedocs.io/en/stable/messaging.html
[protocol-img]: https://img.shields.io/badge/Jupyter%20protocol-5.2-blue.svg
[travis]:       https://travis-ci.org/akabe/ocaml-jupyter
[travis-img]:   https://img.shields.io/travis/akabe/ocaml-jupyter/master.svg?label=travis
[jupyter]:      https://jupyter.org/
[opam]:         https://opam.ocaml.org/

An OCaml kernel for [Jupyter notebook][jupyter].

This provides an OCaml REPL with a great user interface such as markdown/HTML documentation, LaTeX formula by MathJax, and image embedding.

![Screenshot](https://akabe.github.io/ocaml-jupyter/images/screenshot.png)

## Getting started

OCaml Jupyter requires the libraries zlib, libffi, libgmp, libzmq 5+. Type one of the following commands suitable for your environment.

```shell
# For Debian or Ubuntu:
sudo apt-get install -y zlib1g-dev libffi-dev libgmp-dev libzmq5-dev
# For REHL or CentOS:
sudo yum install -y epel-release
sudo yum install -y zlib-devel libffi-dev gmp-devel zeromq-devel
# For Mac OS X:
brew install zlib libffi gmp zeromq
```

OCaml Jupyter can be installed by [OPAM][opam] as follows:

``` shell
pip install jupyter
opam install jupyter
grep topfind ~/.ocamlinit || echo '#use "topfind";;' >> ~/.ocamlinit  # For using '#require' directive
grep Topfind.log ~/.ocamlinit || echo 'Topfind.log:=ignore;;' >> ~/.ocamlinit  # Suppress logging of topfind (recommended but not necessary)
ocaml-jupyter-opam-genspec
jupyter kernelspec install [ --user ] --name "ocaml-jupyter-$(opam var switch)" "$(opam var share)/jupyter"
```

If the last command fails due to permission, `--user` option or `sudo` is required. You can use `ocaml-jupyter` kernel by launching Jupyter notebook server:

```shell
jupyter notebook
```

### Development version

```shell
opam pin add jupyter https://github.com/akabe/ocaml-jupyter.git
```

## Usage

### Examples

- [Introduction](https://github.com/akabe/ocaml-jupyter/blob/master/notebooks/introduction.ipynb):
  a very simple example for use of OCaml Jupyter and sub-packages.
- [Get a description of a word from DuckDuckGo API](https://github.com/akabe/ocaml-jupyter/blob/master/notebooks/word_description_from_DuckDuckGoAPI.ipynb):
  request to DuckDuckGo API server by `cohttp.lwt`, and parse a response JSON by `yojson` and `ppx_yojson_conv`.

In addition, many examples (e.g, image processing, voice analysis, etc.) are available at
[docker-ocaml-jupyter-datascience/notebooks](https://github.com/akabe/docker-ocaml-jupyter-datascience/tree/master/notebooks).

These examples are placed in the **public domain**, e.g., you can edit, copy, and re-distribute with no copyright messages.

### Code completion

OCaml Jupyter kernel supports [merlin](https://ocaml.github.io/merlin/)-based code completion. Candidates are shown by Tab key like

![Code completion](https://akabe.github.io/ocaml-jupyter/images/completion.png)

The kernel uses [.merlin](https://github.com/ocaml/merlin/wiki/project-configuration) file at a notebook directory for completion.

### Inspection

_Inspection_ in Jupyter is also achieved by merlin. You can see documentation and type of an identifier by Shift+Tab key like

![Inspection](https://akabe.github.io/ocaml-jupyter/images/inspect.png)

### API documentation

OCaml Jupyter includes some sub-packages:

- [jupyter][jupyter-core] is a core library of OCaml Jupyter. This package is internally used. You don't need it directly.
- [jupyter.notebook][jupyter-notebook] is a library to control Jupyter from OCaml REPL in notebooks. This provides dynamic generation of HTML/markdown, and image embedding.
- [jupyter.comm][jupyter-comm] is a library for communication between OCaml notebooks and Jupyter/Web frontend.

[jupyter-core]:       https://akabe.github.io/ocaml-jupyter/api/jupyter/
[jupyter-notebook]:   https://akabe.github.io/ocaml-jupyter/api/jupyter/Jupyter_notebook/
[jupyter-comm]:       https://akabe.github.io/ocaml-jupyter/api/jupyter/Jupyter_comm/

### NBConvert

OCaml notebooks can be converted to HTML, Markdown, LaTeX, `.ml` files, etc. using the `jupyter nbconvert` command.
For example, a `.ipynb` file is converted into a `.html` file as follows:

```console
$ jupyter nbconvert --to html notebooks/introduction.ipynb
[NbConvertApp] Converting notebook notebooks/introduction.ipynb to html
[NbConvertApp] Writing 463004 bytes to notebooks/introduction.html
```

For exporting `.ml` files, we recommend [Jupyter-NBConvert-OCaml][Jupyter-NBConvert-OCaml]. It outputs `.ml` files with Markdown cells as comments. After installation of Jupyter-NBConvert-OCaml, you can use `--to ocaml` option to export a `.ml` file:

```console
$ jupyter nbconvert --to ocaml notebooks/introduction.ipynb
[NbConvertApp] Converting notebook notebooks/introduction.ipynb to ocaml
[NbConvertApp] Writing 2271 bytes to notebooks/introduction.ml
```

[Jupyter-NBConvert-OCaml]: https://github.com/Naereen/Jupyter-NBConvert-OCaml

### Customize kernel parameters

`ocaml-jupyter-opam-genspec` generates a configuration file like:

```console
$ cat "$(opam var share)/jupyter/kernel.json"
{
  "display_name": "OCaml 4.08.1",
  "language": "OCaml",
  "argv": [
    "/bin/sh",
    "-c",
    "eval $(opam env --switch=4.08.1) && /home/xxxx/.opam/4.08.1/bin/ocaml-jupyter-kernel \"$@\"",
    "-init", "/home/xxxx/.ocamlinit",
    "--merlin", "/home/xxxx/.opam/4.08.1/bin/ocamlmerlin",
    "--verbosity", "app",
    "--connection-file", "{connection_file}"
  ]
}
```

See `ocaml-jupyter-kernel --help` for details of command-line parameters in `argv`. After you edit the file, re-register the kernel:

```shell
jupyter kernelspec install --name ocaml-jupyter "$(opam var share)/jupyter"
```

### Installation without OPAM

`ocaml-jupyter-opam-genspec` depends on OPAM. If you use an other package manager, you need to write `kernel.json` by hand or use provided suitable way for registering a new kernel (e.g., [jupyter module](https://nixos.org/nixos/options.html#jupyter.kernels) on  [Nix](https://nixos.org/nix/)).

## Running OCaml Jupyter on other environments

### Binder

OCaml Jupyter can be run on [Binder](https://www.mybinder.org).  Click
the button to get started:
[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/edmcman/ocaml-jupyter-binder-environment/master?urlpath=git-pull%3Frepo%3Dhttps%253A%252F%252Fgithub.com%252Fakabe%252Fdocker-ocaml-jupyter-datascience%26urlpath%3Dtree%252Fdocker-ocaml-jupyter-datascience%252Fnotebooks%252Fintroduction.ipynb%26branch%3Dmaster)

For more information, see this [repository](https://github.com/edmcman/ocaml-jupyter-binder-environment).

### Google Colab

OCaml Jupyter can be run on Google Colab. In order to do this you first have to run
[this Python notebook](http://colab.research.google.com/github/akabe/ocaml-jupyter/blob/master/notebooks/install_ocaml_colab.ipynb)
in your Colab instance. This will install the kernel and after that OCaml notebooks can be used on the same instance.

## Sponsors

If you like this project, please support by becoming a sponsor via [GitHub Sponsors](https://github.com/sponsors/akabe).

[<img width=200 src="https://raw.githubusercontent.com/akabe/ocaml-jupyter/gh-pages/images/sponsors/ahrefs.svg"/>](https://ahrefs.com/)

## Related work

Many Jupyter kernels for functional programming languages are available such as [IHaskell][ihaskell], [Jupyter Scala][jupyter-scala], and [Jupyter Rust][jupyter-rs]. [IOCaml][iocaml] is another practical OCaml kernel that inspires us, but it seems no longer maintained. OCaml Jupyter kernel differs from IOCaml in

|                        | OCaml Jupyter | IOCaml v0.4.8 |
| ---------------------- | ------------- | ------------- |
| Jupyter protocol       | v5.2          | v3.2          |
| OCaml PPX support      | Yes           | No            |
| Session key support    | Yes           | No            |
| Code completion        | Yes           | Yes           |
| Introspection          | Yes           | Yes           |
| User-defined messages  | Yes           | No            |
| Stdin                  | Yes           | No            |

Another OCaml kernel [simple_jucaml][simple_jucaml] seems too simple to use in practice.
[jupyter-kernel][jupyter-kernel] is a library to write OCaml kernels (*not a kernel*), but OCaml Jupyter kernel does not use this library.

[ihaskell]:      https://github.com/gibiansky/IHaskell
[jupyter-scala]: https://github.com/alexarchambault/jupyter-scala
[jupyter-rs]:    https://github.com/pwoolcoc/jupyter-rs
[iocaml]:        https://github.com/andrewray/iocaml
[simple_jucaml]: https://github.com/KKostya/simple_jucaml
[jupyter-kernel]:https://github.com/ocaml-jupyter/jupyter-kernel


text:
package org.carlspring.strongbox.jtwig.extensions;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import org.jtwig.functions.FunctionRequest;
import org.jtwig.functions.JtwigFunction;

/**
 *
 * @author ankit.tomar
 *
 */
public class HumanReadableSizeConversionFunction implements JtwigFunction
{

    @Override
    public String name()
    {
        return "humanReadableSize";
    }

    @Override
    public Collection<String> aliases()
    {
        return Collections.unmodifiableList(Arrays.asList("readableSize"));
    }

    @Override
    public Object execute(FunctionRequest request)
    {
        request.minimumNumberOfArguments(1);
        request.maximumNumberOfArguments(1);
        String byteSize = request.getEnvironment().getValueEnvironment().getStringConverter().convert(request.get(0));
        try
        {
            return getHumanReadableSize(Long.parseLong(byteSize));
        }
        catch (NumberFormatException nfe)
        {
            // Need to return same value of bytes
        }
        return byteSize;
    }

    private String getHumanReadableSize(long bytes)
    {
        int unit = 1000;
        if (bytes < unit)
        {
            return bytes + " B";
        }
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = "" + "KMGTPE".charAt(exp - 1);
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }

}