text:
function compileDoc(p,a){
  var doc = {
    plain: "",
    markdown: "",
    html: ""
  };
  // create the temporary values
  var tempPolicy = [];
  var tempGeneralA = [];
  var tempReviewA = [];
  var tempTipsA = [];

  var contextP = [];
  var deviceP = [];
  var commsP = [];
  var acctsP = [];
  var incResP = [];
  var travelP = [];
  var envP = [];
  var networkP = [];
  var appContent = {
    general: [],
    review: [],
    tips: [],
    links: []
  };
  var routineDoc = [];

  // what is the first q in the answers array?
  var prevQ = 0;

  // for each of the answer references
  for (var i = 0; i < currentState.answers.length; i++){
    // get quick ref for answers
    aRef = currentState.answers[i].a;
    // get quick ref for question number
    qRef = currentState.answers[i].q;
    // set up question name
    var thisQ = 'q'+qRef;
    // search for the relevant data using the answer reference
    for (var j = 0; j < sections.length; j++){
      // store if the data is found
      var found = sections[j].find(ans => ans.id === thisQ);
      // if there's data
      if (found){
        switch (true) {
          // questions 0-5 are for context
          case qRef < 6:
            contextP = getPolicyContent(qRef, prevQ, aRef, contextP, found);
            // if we need the appendix and routines too
            if (a) {
              appContent = getAppendixContent(qRef, prevQ, aRef, appContent, found); // TODO: instead of repeating this is should just be a function call each time
              routineDoc = getRoutineEntry(qRef, prevQ, aRef, routineDoc, found);
            }
            break;
          // add case for teaming name & pos @ 9
          // questions 6-8 are for devices
          case qRef < 9:
            deviceP = getPolicyContent(qRef, prevQ, aRef, deviceP, found);
            // if we need the appendix and routines too
            if (a) {
              appContent = getAppendixContent(qRef, prevQ, aRef, appContent, found);
              routineDoc = getRoutineEntry(qRef, prevQ, aRef, routineDoc, found);
            }
            break;
          // questions 9-12 are for comms
          case qRef < 13:
            commsP = getPolicyContent(qRef, prevQ, aRef, commsP, found);
            // if we need the appendix and routines too
            if (a) {
              appContent = getAppendixContent(qRef, prevQ, aRef, appContent, found);
              routineDoc = getRoutineEntry(qRef, prevQ, aRef, routineDoc, found);
            }
            break;
          // question 13 is inc resp
          case qRef < 14:
            incResP = getPolicyContent(qRef, prevQ, aRef, incResP, found);
            break;
          // questions 14-19 are for accounts
          case qRef < 20:
            acctsP = getPolicyContent(qRef, prevQ, aRef, acctsP, found);
            // if we need the appendix and routines too
            if (a) {
              appContent = getAppendixContent(qRef, prevQ, aRef, appContent, found);
              routineDoc = getRoutineEntry(qRef, prevQ, aRef, routineDoc, found);
            }
            break;
          // question 20 is for inc resp
          case qRef < 21:
            incResP = getPolicyContent(qRef, prevQ, aRef, incResP, found);
            break;
          // add case for inserting Backups heading @ 22
          // questions 22-26 are for devices
          case qRef < 27:
            deviceP = getPolicyContent(qRef, prevQ, aRef, deviceP, found);
            // if we need the appendix and routines too
            if (a) {
              appContent = getAppendixContent(qRef, prevQ, aRef, appContent, found);
              routineDoc = getRoutineEntry(qRef, prevQ, aRef, routineDoc, found);
            }
            break;
          // question 27 is for inc resp
          case qRef < 28:
            incResP = getPolicyContent(qRef, prevQ, aRef, incResP, found);
            break;
          // add case for teaming name & pos @ 33
          // questions 28-33 are for travel
          case qRef < 34:
            travelP = getPolicyContent(qRef, prevQ, aRef, travelP, found);
            // if we need the appendix and routines too
            if (a) {
              appContent = getAppendixContent(qRef, prevQ, aRef, appContent, found);
              routineDoc = getRoutineEntry(qRef, prevQ, aRef, routineDoc, found);
            }
            break;
          // question 34 is for inc resp
          case qRef < 35:
            incResP = getPolicyContent(qRef, prevQ, aRef, incResP, found);
            break;
          // questions 35-41 are for environmental security
          case qRef < 42:
            envP = getPolicyContent(qRef, prevQ, aRef, envP, found);
            // if we need appendix and routines
            if (a){
              appContent = getAppendixContent(qRef, prevQ, aRef, appContent, found);
              routineDoc = getRoutineEntry(qRef, prevQ, aRef, routineDoc, found);
            }
            break;
          // question 42 is for inc resp
          case qRef < 43:
            incResP = getPolicyContent(qRef, prevQ, aRef, incResP, found);
            break;
          // questions 43-47 are for network security
          case qRef < 48:
            networkP = getPolicyContent(qRef, prevQ, aRef, networkP, found);
            // if we need appendix and routines
            if (a){
              appContent = getAppendixContent(qRef, prevQ, aRef, appContent, found);
              routineDoc = getRoutineEntry(qRef, prevQ, aRef, routineDoc, found);
            }
            break;
          // question 48 is for inc resp
          case qRef <49:
            incResP = getPolicyContent(qRef, prevQ, aRef, incResP, found);
            break;
          default:
            console.log(qRef + ' not found');
        }
      }
    }
    // store this question's ID for comparison in the next loop
    prevQ = qRef;
  }

  doc.plain = 'Organizational Security Policy\n\nCreated '+dateStamp()+'\n\n'+contextP.join('\n');
  doc.markdown = '# Organizational Security Policy \n#### Created '+dateStamp()+'\n\n'+contextP.join('\n');
  doc.html = '<!DOCTYPE html><title>Organizational Security Policy '+dateStamp()+'</title>
Organizational Security Policy

Created '+dateStamp()+'

'+contextP.join('

')+'
';

  if (deviceP.length > 0){
    doc.plain += '\n\nDevice Security\n' + deviceP.join('\n');
    doc.markdown += '\n\n### Device Security \n' + deviceP.join('\n');
    doc.html += '
Device Security

' + deviceP.join('

')+'
';
  }
  if (commsP.length > 0){
    doc.plain += '\n\nCommunications Security\n' + commsP.join('\n');
    doc.markdown += '\n\n### Communications Security \n' + commsP.join('\n');
    doc.html += '
Communications Security

' + commsP.join('

')+'
';
  }
  if (acctsP.length > 0){
    doc.plain += '\n\nAccounts Security\n' + acctsP.join('\n');
    doc.markdown += '\n\n### Accounts Security \n' + acctsP.join('\n');
    doc.html += '
Accounts Security

' + acctsP.join('

')+'
';
  }
  if (travelP.length > 0){
    doc.plain += '\n\nTravel Security\n' + travelP.join('\n');
    doc.markdown += '\n\n### Travel Security \n' + travelP.join('\n');
    doc.html += '
Travel Security

' + travelP.join('

')+'
';
  }
  if (envP.length > 0){
    doc.plain += '\n\nEnvironmental Security\n' + envP.join('\n');
    doc.markdown += '\n\n### Environmental Security \n' + envP.join('\n');
    doc.html += '
Environmental Security

' + envP.join('

')+'
';
  }
  if (networkP.length > 0){
    doc.plain += '\n\nNetwork Security\n' + networkP.join('\n');
    doc.markdown += '\n\n### Network Security \n' + networkP.join('\n');
    doc.html += '
Network Security

' + networkP.join('

')+'
';
  }
  if (incResP.length > 0){
    doc.plain += '\n\nWhat to do if...\n' + incResP.join('\n\n');
    doc.markdown += '\n\n### What to do if...\n' + incResP.join('\n\n');
    doc.html += '
What to do if...

' + incResP.join('

')+'
';
  }

  // if appendix is requested, join the policy, appendix and routines arrays together, and add the team-specific policies
  if (a) {
    doc.plain += '\n\nAppendix\n';
    doc.markdown += '\n\n## Appendix\n';
    doc.html += '
Appendix
';
    if (appContent.general.length > 0){
      doc.plain += '\n\nGeneral Advice\n- ' + appContent.general.join('\n- ');
      doc.markdown += '\n\n### General Advice \n\n* ' + appContent.general.join('\n* ');
      doc.html += '
General Advice

' + appContent.general.join('

')+'

';
    }
    if (appContent.review.length > 0){
      doc.plain += '\n\nReview Checklist\n- ' + appContent.review.join('\n- ');
      doc.markdown += '\n\n### Review Checklist \n\n- [ ] ' + appContent.review.join('\n- [ ] ');
      doc.html += '
Review Checklist

' + appContent.review.join('

')+'

';
    }
    if (appContent.tips.length > 0){
      doc.plain += '\n\nImplementation Tips\n- ' + appContent.tips.join('\n- ');
      doc.markdown += '\n\n### Implementation Tips \n\n* ' + appContent.tips.join('\n* ');
      doc.html += '
Implementation Tips

' + appContent.tips.join('

')+'

';
    }
    if (appContent.links.length > 0){
      doc.plain += '\n\nUseful Links \n- ' + appContent.links.join('\n- ');
      doc.markdown += '\n\n### Useful Links \n\n* ' + appContent.links.join('\n* ');
      doc.html += '
Useful Links

' + appContent.links.join('

')+'

';
    }
    if (routineDoc.length > 0){
      doc.plain += '\n\nEveryday practices \n+ ' + routineDoc.join('\n+ ');
      doc.markdown += '\n\n## Everyday practices \n\n* ' + routineDoc.join('\n* ');
      doc.html += '
Everyday practices

' + routineDoc.join('

')+'

';
    }
  }
  doc.plain += '\n\nPlease note: it is recommended that this policy undergoes a legal review prior to being implemented in your organization. \n\nBuilt with SOAP v.'+soapv;
  doc.markdown += '\n\n#### *Please note: it is recommended that this policy undergoes a legal review prior to being implemented in your organization.* \n\n##### Built with SOAP v.'+soapv;
  doc.html += '
Please note: it is recommended that this policy undergoes a legal review prior to being implemented in your organization.

Built with SOAP v. '+soapv+'
';

  var teamPolicies = [];
  // for each of the teams in teamContent
  for (var t=0; t<teamContent.length; t++){
    // if there are selected areas for this team
    if (teamContent[t].areas.length > 0){

      // get the area numbers
      areas = teamContent[t].areas;

      // add the contextP
      pText = '\n\n'+teamContent[t].name + '\n\nOrganizational Security Policy\n\nCreated '+dateStamp()+'\n\n'+contextP.join('\n');
      mText = '\n\n# '+teamContent[t].name + '\n## Organizational Security Policy \n#### Created '+dateStamp()+'\n\n'+contextP.join('\n');
      hText = '<!DOCTYPE html><title>Organizational Security Policy '+dateStamp()+'</title>
'+teamContent[t].name+'

Organizational Security Policy

Created '+dateStamp()+'

'+contextP.join('

')+'
';

      // for each of the optional areas
      for (var a = 0; a< areas.length; a++){
        // add the area title
        // add the corresponding policy text in each format
        switch (areas[a]) {
          case 0:
            pText += '\n\nDevice Security\n' + deviceP.join('\n');
            mText += '\n\n### Device Security \n' + deviceP.join('\n');
            hText += '
Device Security

' + deviceP.join('

')+'
';
            break;
          case 1:
            pText += '\n\nCommunications Security\n' + commsP.join('\n');
            mText += '\n\n### Communications Security \n' + commsP.join('\n');
            hText += '
Communications Security

' + commsP.join('

')+'
';
            break;
          case 2:
            pText += '\n\nAccounts Security\n' + acctsP.join('\n');
            mText += '\n\n### Accounts Security \n' + acctsP.join('\n');
            hText += '
Accounts Security

' + acctsP.join('

')+'
';
            break;
          case 3:
            pText += '\n\nTravel Security\n' + travelP.join('\n');
            mText += '\n\n### Travel Security \n' + travelP.join('\n');
            hText += '
Travel Security

' + travelP.join('

')+'
';
            break;
          case 4:
            pText += '\n\nEnvironmental Security\n' + envP.join('\n');
            mText += '\n\n### Environmental Security \n' + envP.join('\n');
            hText += '
Environmental Security

' + envP.join('

')+'
';
            break;
          case 5:
            pText += '\n\nNetwork Security\n' + networkP.join('\n');
            mText += '\n\n### Network Security \n' + networkP.join('\n');
            hText += '
Network Security

' + networkP.join('

')+'
';
            break;
          default:
          console.log(areas[a]);
        }

      }
      // then add any other default content
      if (incResP.length > 0){
        pText += '\n\nWhat to do if...\n' + incResP.join('\n\n');
        mText += '\n\n### What to do if...\n' + incResP.join('\n\n');
        hText += '
What to do if...

' + incResP.join('

')+'
';
      }
      // and push the team policies to the array
      teamPolicies.push({
        "team":teamContent[t].name,
        "plain": pText,
        "markdown": mText,
        "html": hText,
      });
    }
  }
  for (var tm=0; tm<teamPolicies.length; tm++){
    // get the content of each team pushed
    doc.plain += teamPolicies[tm].plain;
    doc.markdown += teamPolicies[tm].markdown;
    doc.html += teamPolicies[tm].html;
  }

  output = doc;
  return doc;
}

// function to replace temporary placeholder text in policy
function replaceStr(string) {
  var editedStr = string;
  // for each of the stored keys
  for (var key in dict){
    // if it's a list of things and the last item does not start with an " and "
    if ((Array.isArray(dict[key])) && (!dict[key][dict[key].length-1].startsWith(" and "))){
      last = dict[key][dict[key].length-1];
      // add "and" plus a full stop to the last item
      dict[key][dict[key].length-1] = "and " + last;
      // prepend each item in the array with a space
      for (var i = 0; i < dict[key].length; i++){
        dict[key][i] = " " + dict[key][i];
      }
    }
    var regexKey = key.replace('[', '\\[').replace(']', '\\]');
    var regex = new RegExp(regexKey, 'gi');
    // check if that key exists in the string and replace it with value from dict
    editedStr = editedStr.replace(regex, dict[key]);
  }
  // if string contains items that start [date+
  if (editedStr.match(/\[date\+[\.\d]+\]/g)){
    // grab all instances in this string
    dates = editedStr.match(/\[date\+[\.\d]+\]/g);
    // for each instance
    for (var d = 0; d < dates.length; d++){
      // take the number after the +
      num = dates[d].split('+');
      num = num[1].split(']');
      num = num[0];

      // get the current date
      start = new Date();
      // add the appropriate number of months/years to it
      start.setMonth(start.getMonth()+parseInt(num, 10));

      future = start.getDate();
      var options = {month:'long'};
      future += ' ' + new Intl.DateTimeFormat('en-UK', options).format(start);
      future += ' ' + start.getFullYear();

      // update the edited string
      editedStr = editedStr.replace(dates[d], future);
    }
  }
  return editedStr;
}

function dateStamp(){
  // get the current date
  var today = new Date();
  // start creating the date stamp
  var fullDate = today.getDate();
  var options = {month:'long'};
  fullDate += ' ' + new Intl.DateTimeFormat('en-UK', options).format(today);
  fullDate += ' ' + today.getFullYear();
  return fullDate; // is there a way to return date + 3 months (no day)?
}

function clearData(){
  currentState = null;
  dates  = null;
  dict = null;
  output = null;
  qRef = null;
  tmpContent = null;
  window.location.reload(true);
}

// function to download data to a file
function downloadPolicy(type, edit) {
  var data;
  // if we're looking to download an edited policy
  if (edit === true){
    // grab the edited textcontent
    var editedPolicy = document.querySelector('.policyHolder').value;
    // store it in data
    if (editedPolicy !== ""){
      data = editedPolicy;
    } else {
      data = output[type];
    }
  } else {
    // else grab the content from output as usual
    data = output[type];
  }

  var format = 'text/'+type;
  var filename = "SOAP-policy";
  if (type === 'markdown'){
    filename += '.md';
  } else if (type === 'plain'){
    filename += '.txt';
  } else {
    filename += '.'+type;
  }

  var file = makeFile(data, filename, format);

  if (window.navigator.msSaveOrOpenBlob){ // IE10+
      window.navigator.msSaveOrOpenBlob(file, filename);
  } else { // Others
      var a = document.createElement("a"),
              url = URL.createObjectURL(file);
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      setTimeout(function() {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
      }, 1000);
  }
}

function makeFile(d, n, f){
  try {
    return new File([d], n,{type: f});
  } catch (exception) {
    const blob = new Blob([d], {type: f, name: n});
    return blob;
  }
}

function getPolicyContent(question, previous, answer, policy, content){
  // if it's a new question and there's policyEntry
  if ((question !== previous) && (content.policyEntry !== "")) {
    // edit the policyEntry and push it to the policy
    thisContent = replaceStr(content.policyEntry);
    policy.push(thisContent);
  } else {
    console.log(question + ' is not a new question');
  }

  // TODO: add a case that deals with the first question
  // if q1 isn't answered then the next answered question is being skipped over because it's the same as previous
  // need to check (one-time) if the question is same as previous but has not been processed before

  // if the answer has a policyEntry
  if (content.answers[answer].policyEntry !== ""){
    // edit the policyEntry and push it to the policy
    thisContent = replaceStr(content.answers[answer].policyEntry);
    policy.push(thisContent);
  } else {
    console.log(question + ' does not have an answer-specific entry');
  }
  return policy;
}

function getAppendixContent(question, previous, answer, appDoc, content){
  if ((question !== previous) && (content.appendixEntry !== "")) {
    thisContent = replaceStr(content.appendixEntry);
    appDoc.general.push(thisContent);
  }
  appEntry = content.answers[answer].appendixEntry[0];
  if (appEntry.reviewList.length > 0){
    thisContent = replaceStr(appEntry.reviewList);
    appDoc.review.push(thisContent);
  }
  if (appEntry.tipList.length > 0){
    thisContent = replaceStr(appEntry.tipList);
    appDoc.tips.push(thisContent);
  }
  if (appEntry.linksList.length > 0){
    thisContent = replaceStr(appEntry.linksList);
    appDoc.links.push(thisContent);
  }
  return appDoc;
}

function getRoutineEntry(question, previous, answer, routines, content){
  // if it's a new question and there's a general routine entry
  if ((question !== previous) && (content.routineEntry !== "")) {
    // edit the entry and push it to the doc
    thisContent = replaceStr(content.routineEntry);
    routines.push(thisContent);
  }
  // if the answer has a specific routine entry
  if (content.answers[answer].routineEntry !== ""){
    // edit that entry and push it to the doc
    thisContent = replaceStr(content.answers[answer].routineEntry);
    routines.push(thisContent);
  }
  return routines;
}

function resetChanges(){
  // could also use textContent instead of output here
  document.querySelector('.policyHolder').value = output.plain;
}


text:
package grpc

// This file provides server-side bindings for the gRPC transport. It utilizes
// the transport/grpc.Server.

import (
	"github.com/cdwlabs/armor/pb"
	"github.com/cdwlabs/armor/pkg/proxy/endpoints"
	"github.com/cdwlabs/armor/pkg/proxy/service"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/tracing/opentracing"
	grpctransport "github.com/go-kit/kit/transport/grpc"
	stdopentracing "github.com/opentracing/opentracing-go"
	"golang.org/x/net/context"
)

type grpcServer struct {
	initstatus grpctransport.Handler
	init       grpctransport.Handler
	sealstatus grpctransport.Handler
	unseal     grpctransport.Handler
	configure  grpctransport.Handler
}

// NewHandler makes a set of endpoints available as a gRPC Server.
// NOTE: At some point, request tracing support needs to be added. And since
// much of this service used example code from go-kit, the place to start for
// tracing support is probably here:
// https://github.com/go-kit/kit/blob/master/examples/addsvc/transport_grpc.go
func NewHandler(ctx context.Context, endpoints endpoints.Endpoints, tracer stdopentracing.Tracer, logger log.Logger) pb.VaultServer {
	options := []grpctransport.ServerOption{
		grpctransport.ServerErrorLogger(logger),
	}
	return &grpcServer{
		initstatus: grpctransport.NewServer(
			ctx,
			endpoints.InitStatusEndpoint,
			DecodeInitStatusRequest,
			EncodeInitStatusResponse,
			append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "InitStatus", logger)))...,
		),
		init: grpctransport.NewServer(
			ctx,
			endpoints.InitEndpoint,
			DecodeInitRequest,
			EncodeInitResponse,
			append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "Init", logger)))...,
		),
		sealstatus: grpctransport.NewServer(
			ctx,
			endpoints.SealStatusEndpoint,
			DecodeSealStatusRequest,
			EncodeSealStatusResponse,
			append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "SealStatus", logger)))...,
		),
		unseal: grpctransport.NewServer(
			ctx,
			endpoints.UnsealEndpoint,
			DecodeUnsealRequest,
			EncodeUnsealResponse,
			append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "Unseal", logger)))...,
		),
		configure: grpctransport.NewServer(
			ctx,
			endpoints.ConfigureEndpoint,
			DecodeConfigureRequest,
			EncodeConfigureResponse,
			append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "Configure", logger)))...,
		),
	}
}

func (s *grpcServer) InitStatus(ctx context.Context, req *pb.InitStatusRequest) (*pb.InitStatusResponse, error) {
	_, rep, err := s.initstatus.ServeGRPC(ctx, req)
	if err != nil {
		return nil, err
	}
	return rep.(*pb.InitStatusResponse), nil
}

func (s *grpcServer) Init(ctx context.Context, req *pb.InitRequest) (*pb.InitResponse, error) {
	_, rep, err := s.init.ServeGRPC(ctx, req)
	if err != nil {
		return nil, err
	}
	return rep.(*pb.InitResponse), nil
}

func (s *grpcServer) SealStatus(ctx context.Context, req *pb.SealStatusRequest) (*pb.SealStatusResponse, error) {
	_, rep, err := s.sealstatus.ServeGRPC(ctx, req)
	if err != nil {
		return nil, err
	}
	return rep.(*pb.SealStatusResponse), nil
}

func (s *grpcServer) Unseal(ctx context.Context, req *pb.UnsealRequest) (*pb.UnsealResponse, error) {
	_, rep, err := s.unseal.ServeGRPC(ctx, req)
	if err != nil {
		return nil, err
	}
	return rep.(*pb.UnsealResponse), nil
}

func (s *grpcServer) Configure(ctx context.Context, req *pb.ConfigureRequest) (*pb.ConfigureResponse, error) {
	_, rep, err := s.configure.ServeGRPC(ctx, req)
	if err != nil {
		return nil, err
	}
	return rep.(*pb.ConfigureResponse), nil
}

// DecodeInitStatusRequest is a transport/grpc.DecodeRequestFunc that
// converts a gRPC initstatus request to a user-domain initstatus request. Primarily useful
// in a server.
func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
	return endpoints.InitStatusRequest{}, nil
}

// DecodeInitStatusResponse is a transport/grpc.DecodeResponseFunc that
// converts a gRPC initstatus reply to a user-domain initstatus response. Primarily useful in
// a client.
func DecodeInitStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {
	reply := grpcReply.(*pb.InitStatusResponse)
	return endpoints.InitStatusResponse{Initialized: bool(reply.Status.Initialized), Err: service.String2Error(reply.Err)}, nil
}

// EncodeInitStatusResponse is a transport/grpc.EncodeResponseFunc that
// converts a user-domain initstatus response to a gRPC initstatus reply. Primarily useful in
// a server.
func EncodeInitStatusResponse(_ context.Context, response interface{}) (interface{}, error) {
	resp := response.(endpoints.InitStatusResponse)
	status := &pb.Status{Initialized: bool(resp.Initialized)}
	return &pb.InitStatusResponse{Status: status, Err: service.Error2String(resp.Err)}, nil
}

// EncodeInitStatusRequest is a transport/grpc.EncodeRequestFunc that
// converts a user-domain initstatus request to a gRPC initstatus request. Primarily useful
// in a client.
func EncodeInitStatusRequest(_ context.Context, request interface{}) (interface{}, error) {
	return &pb.InitStatusRequest{}, nil
}

// DecodeInitRequest is a transport/grpc.DecodeRequestFunc that
// converts a gRPC init request to a user-domain init request. Primarily useful
// in a server.
func DecodeInitRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
	req := grpcReq.(*pb.InitRequest)
	opts := service.InitOptions{
		SecretShares:          int(req.SecretShares),
		SecretThreshold:       int(req.SecretThreshold),
		StoredShares:          int(req.StoredShares),
		PGPKeys:               req.PgpKeys,
		RecoveryShares:        int(req.RecoveryShares),
		RecoveryThreshold:     int(req.RecoveryThreshold),
		RecoveryPGPKeys:       req.RecoveryPgpKeys,
		RootTokenPGPKey:       req.RootTokenPgpKey,
		RootTokenHolderEmail:  req.RootTokenHolderEmail,
		SecretKeyHolderEmails: req.SecretKeyHolderEmails,
	}
	return &endpoints.InitRequest{Opts: opts}, nil
}

// DecodeInitResponse is a transport/grpc.DecodeResponseFunc that
// converts a gRPC init reply to a user-domain init response. Primarily useful in
// a client.
func DecodeInitResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {
	reply := grpcReply.(*pb.InitResponse)
	init := service.InitKeys{
		Keys:            reply.Keys,
		KeysB64:         reply.KeysBase64,
		RecoveryKeys:    reply.RecoveryKeys,
		RecoveryKeysB64: reply.RecoveryKeysBase64,
		RootToken:       reply.RootToken,
	}
	return endpoints.InitResponse{Init: init, Err: service.String2Error(reply.Err)}, nil
}

// EncodeInitResponse is a transport/grpc.EncodeResponseFunc that
// converts a user-domain init response to a gRPC init reply. Primarily useful in
// a server.
func EncodeInitResponse(_ context.Context, response interface{}) (interface{}, error) {
	resp := response.(endpoints.InitResponse)

	return &pb.InitResponse{
		Keys:               resp.Init.Keys,
		KeysBase64:         resp.Init.KeysB64,
		RecoveryKeys:       resp.Init.RecoveryKeys,
		RecoveryKeysBase64: resp.Init.RecoveryKeysB64,
		RootToken:          resp.Init.RootToken,
		Err:                service.Error2String(resp.Err),
	}, nil
}

// EncodeInitRequest is a transport/grpc.EncodeRequestFunc that
// converts a user-domain init request to a gRPC init request. Primarily useful
// in a client.
func EncodeInitRequest(_ context.Context, request interface{}) (interface{}, error) {
	req := request.(endpoints.InitRequest)
	return &pb.InitRequest{
		SecretShares:          uint32(req.Opts.SecretShares),
		SecretThreshold:       uint32(req.Opts.SecretThreshold),
		StoredShares:          uint32(req.Opts.StoredShares),
		PgpKeys:               req.Opts.PGPKeys,
		RecoveryShares:        uint32(req.Opts.RecoveryShares),
		RecoveryThreshold:     uint32(req.Opts.RecoveryThreshold),
		RecoveryPgpKeys:       req.Opts.RecoveryPGPKeys,
		RootTokenPgpKey:       req.Opts.RootTokenPGPKey,
		RootTokenHolderEmail:  req.Opts.RootTokenHolderEmail,
		SecretKeyHolderEmails: req.Opts.SecretKeyHolderEmails,
	}, nil
}

// DecodeSealStatusRequest is a transport/grpc.DecodeRequestFunc that
// converts a gRPC sealstatus request to a user-domain sealstatus request. Primarily useful
// in a server.
func DecodeSealStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
	return endpoints.SealStatusRequest{}, nil
}

// DecodeSealStatusResponse is a transport/grpc.DecodeResponseFunc that
// converts a gRPC sealstatus reply to a user-domain sealstatus response. Primarily useful in
// a client.
func DecodeSealStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {
	reply := grpcReply.(*pb.SealStatusResponse)
	status := endpoints.SealStatusResponse{
		Sealed:      reply.SealStatus.Sealed,
		T:           int(reply.SealStatus.T),
		N:           int(reply.SealStatus.N),
		Progress:    int(reply.SealStatus.Progress),
		Version:     reply.SealStatus.Version,
		ClusterName: reply.SealStatus.ClusterName,
		ClusterID:   reply.SealStatus.ClusterId,
		Err:         service.String2Error(reply.Err),
	}

	return status, nil
}

// EncodeSealStatusResponse is a transport/grpc.EncodeResponseFunc that
// converts a user-domain sealstatus response to a gRPC sealstatus reply. Primarily useful in
// a server.
func EncodeSealStatusResponse(_ context.Context, response interface{}) (interface{}, error) {
	resp := response.(endpoints.SealStatusResponse)

	status := &pb.SealStatus{
		Sealed:      resp.Sealed,
		T:           uint32(resp.T),
		N:           uint32(resp.N),
		Progress:    uint32(resp.Progress),
		Version:     resp.Version,
		ClusterName: resp.ClusterName,
		ClusterId:   resp.ClusterID,
	}
	return &pb.SealStatusResponse{
		SealStatus: status,
		Err:        service.Error2String(resp.Err),
	}, nil
}

// EncodeSealStatusRequest is a transport/grpc.EncodeRequestFunc that
// converts a user-domain sealstatus request to a gRPC sealstatus request. Primarily useful
// in a client.
func EncodeSealStatusRequest(_ context.Context, request interface{}) (interface{}, error) {
	return &pb.SealStatusRequest{}, nil
}

// DecodeUnsealRequest is a transport/grpc.DecodeRequestFunc that
// converts a gRPC unseal request to a user-domain unseal request. Primarily useful
// in a server.
func DecodeUnsealRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
	req := grpcReq.(*pb.UnsealRequest)
	return &endpoints.UnsealRequest{Key: req.Key, Reset: req.Reset_}, nil
}

// DecodeUnsealResponse is a transport/grpc.DecodeResponseFunc that
// converts a gRPC unseal reply to a user-domain unseal response. Primarily useful in
// a client.
func DecodeUnsealResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {
	reply := grpcReply.(*pb.UnsealResponse)
	status := endpoints.UnsealResponse{
		Sealed:      reply.SealStatus.Sealed,
		T:           int(reply.SealStatus.T),
		N:           int(reply.SealStatus.N),
		Progress:    int(reply.SealStatus.Progress),
		Version:     reply.SealStatus.Version,
		ClusterName: reply.SealStatus.ClusterName,
		ClusterID:   reply.SealStatus.ClusterId,
		Err:         service.String2Error(reply.Err),
	}

	return status, nil
}

// EncodeUnsealResponse is a transport/grpc.EncodeResponseFunc that
// converts a user-domain unseal response to a gRPC sealstatus reply. Primarily useful in
// a server.
func EncodeUnsealResponse(_ context.Context, response interface{}) (interface{}, error) {
	resp := response.(endpoints.UnsealResponse)

	status := &pb.SealStatus{
		Sealed:      resp.Sealed,
		T:           uint32(resp.T),
		N:           uint32(resp.N),
		Progress:    uint32(resp.Progress),
		Version:     resp.Version,
		ClusterName: resp.ClusterName,
		ClusterId:   resp.ClusterID,
	}
	return &pb.UnsealResponse{
		SealStatus: status,
		Err:        service.Error2String(resp.Err),
	}, nil
}

// EncodeUnsealRequest is a transport/grpc.EncodeRequestFunc that
// converts a user-domain unseal request to a gRPC unseal request. Primarily useful
// in a client.
func EncodeUnsealRequest(_ context.Context, request interface{}) (interface{}, error) {
	req := request.(endpoints.UnsealRequest)
	return &pb.UnsealRequest{
		Key:    req.Key,
		Reset_: req.Reset,
	}, nil
}

// DecodeConfigureRequest is a transport/grpc.DecodeRequestFunc that
// converts a gRPC configure request to a user-domain configure request. Primarily useful
// in a server.
func DecodeConfigureRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
	req := grpcReq.(*pb.ConfigureRequest)
	return &endpoints.ConfigureRequest{URL: req.Url, Token: req.Token}, nil
}

// DecodeConfigureResponse is a transport/grpc.DecodeResponseFunc that
// converts a gRPC configure reply to a user-domain configure response. Primarily useful in
// a client.
func DecodeConfigureResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {
	reply := grpcReply.(*pb.ConfigureResponse)

	var mounts map[string]endpoints.MountOutput
	var auths map[string]endpoints.AuthMountOutput
	var policies []string

	if reply.ConfigStatus != nil {
		// mounts
		if (reply.ConfigStatus.Mounts != nil) && (len(reply.ConfigStatus.Mounts) > 0) {
			mounts = make(map[string]endpoints.MountOutput)
			for k, v := range reply.ConfigStatus.Mounts {

				mountCfgOut := endpoints.MountConfigOutput{
					DefaultLeaseTTL: int(v.Config.DefaultLeaseTtl),
					MaxLeaseTTL:     int(v.Config.MaxLeaseTtl),
				}

				mountOut := endpoints.MountOutput{
					Type:        v.Type,
					Description: v.Description,
					Config:      mountCfgOut,
				}

				mounts[k] = mountOut
			}
		}

		// auths
		if (reply.ConfigStatus.Auths != nil) && (len(reply.ConfigStatus.Auths) > 0) {
			auths = make(map[string]endpoints.AuthMountOutput)
			for k, v := range reply.ConfigStatus.Auths {

				authCfgOut := endpoints.AuthConfigOutput{
					DefaultLeaseTTL: int(v.Config.DefaultLeaseTtl),
					MaxLeaseTTL:     int(v.Config.MaxLeaseTtl),
				}

				authMountOut := endpoints.AuthMountOutput{
					Type:        v.Type,
					Description: v.Description,
					Config:      authCfgOut,
				}

				auths[k] = authMountOut
			}
		}
	}

	// policies
	if (reply.ConfigStatus.Policies != nil) && (len(reply.ConfigStatus.Policies) > 0) {
		policies = reply.ConfigStatus.Policies
	}

	status := endpoints.ConfigureResponse{
		ConfigID: reply.ConfigStatus.ConfigId,
		Mounts:   mounts,
		Auths:    auths,
		Policies: policies,
		Err:      service.String2Error(reply.Err),
	}

	return status, nil
}

// EncodeConfigureResponse is a transport/grpc.EncodeResponseFunc that
// converts a user-domain configure response to a gRPC configstatus reply. Primarily useful in
// a server.
func EncodeConfigureResponse(_ context.Context, response interface{}) (interface{}, error) {
	resp := response.(endpoints.ConfigureResponse)

	// mounts
	var mounts map[string]*pb.MountOutput
	if (resp.Mounts != nil) && (len(resp.Mounts) > 0) {
		mounts = make(map[string]*pb.MountOutput)
		for k, v := range resp.Mounts {
			mountCfgOut := &pb.MountConfigOutput{
				DefaultLeaseTtl: uint32(v.Config.DefaultLeaseTTL),
				MaxLeaseTtl:     uint32(v.Config.MaxLeaseTTL),
			}

			mountOut := &pb.MountOutput{
				Type:        v.Type,
				Description: v.Description,
				Config:      mountCfgOut,
			}

			mounts[k] = mountOut
		}
	}

	// auths
	var auths map[string]*pb.AuthMountOutput
	if (resp.Auths != nil) && (len(resp.Auths) > 0) {
		auths = make(map[string]*pb.AuthMountOutput)
		for k, v := range resp.Auths {
			authCfgOut := &pb.AuthConfigOutput{
				DefaultLeaseTtl: uint32(v.Config.DefaultLeaseTTL),
				MaxLeaseTtl:     uint32(v.Config.MaxLeaseTTL),
			}

			authMountOut := &pb.AuthMountOutput{
				Type:        v.Type,
				Description: v.Description,
				Config:      authCfgOut,
			}

			auths[k] = authMountOut
		}
	}

	// policies
	var policies []string
	if (resp.Policies != nil) && (len(resp.Policies) > 0) {
		policies = resp.Policies
	}

	status := &pb.ConfigStatus{
		ConfigId: resp.ConfigID,
		Mounts:   mounts,
		Auths:    auths,
		Policies: policies,
	}
	return &pb.ConfigureResponse{
		ConfigStatus: status,
		Err:          service.Error2String(resp.Err),
	}, nil
}

// EncodeConfigureRequest is a transport/grpc.EncodeRequestFunc that
// converts a user-domain configure request to a gRPC configure request. Primarily useful
// in a client.
func EncodeConfigureRequest(_ context.Context, request interface{}) (interface{}, error) {
	req := request.(endpoints.ConfigureRequest)
	return &pb.ConfigureRequest{
		Url:   req.URL,
		Token: req.Token,
	}, nil
}

redpajama_set_name: RedPajamaGithub


text:
""" Utilities to read namelist file

Originally adapted from
https://github.com/leifdenby/namelist_python
"""
from __future__ import print_function
import re
import warnings
from itertools import groupby
from .parameters import Param, Params

CONVERT_LOWERCASE = True

class Namelist(Params):
    """ Parse / Format method specific to Namelist
    """
    @classmethod
    def parse(cls, string):
        try:
            params = _parse_nml(string)
        except:
            warnings.warn("some characters in the comments (likely / or \) namelist parsing, discard all comments")
            params = _parse_nml(string)
        return cls(params)

    def format(self):
        return _format_nml(self)

    # Handy method to get/set param
    def get_value(self, group, name):
        """ access like a dict
        """
        i = self.index(Param(name, group=group))
        return self[i].value

    def set_value(self, group, name, value):
        """ access like a dict
        """
        i = self.index(Param(name, group=group))
        self[i].value = value

#
# Work for Namelist parsing and conversion
#
def _parse_nml(string, ignore_comments=False):
    """ parse a string namelist, and returns a list of params
    with four keys: name, value, help, group
    """
    group_re = re.compile(r'&([^&]+)/', re.DOTALL)  # allow blocks to span multiple lines
    array_re = re.compile(r'(\w+)\((\d+)\)')
    # string_re = re.compile(r"\'\s*\w[^']*\'")
    string_re = re.compile(r"[\'\"]*[\'\"]")
    # self._complex_re = re.compile(r'^\((\d+.?\d*),(\d+.?\d*)\)$')

    # list of parameters
    params = Params()
    # groups = odict()

    filtered_lines = []
    for line in string.split('\n'):
        line = line.strip()
        if line == "":
            continue
        # remove comments, since they may have forward-slashes
        # set ignore_comments to True is you want to keep them.
        if line.startswith('!'):
            continue
        if ignore_comments and '!' in line:
            line = line[:line.index('!')]

        filtered_lines.append(line)

    group_blocks = re.findall(group_re, "\n".join(filtered_lines))

    for i, group_block in enumerate(group_blocks):
        group_lines = group_block.split('\n')
        group_name = group_lines.pop(0).strip()
        # check for comments
        if "!" in group_name:
            i = group_name.index("!")
            group_name = group_name[:i].strip()
            group_help = group_name[i+1:].strip()

        # some lines are continuation of previous lines: filter
        joined_lines = []
        for line in group_lines:
            line = line.strip()
            if '=' in line:
                joined_lines.append(line)
            else:
                # continuation of previous line
                joined_lines[-1] += line
        group_lines = joined_lines

        for line in group_lines:
            name, value, comment = _parse_line(line)

            param = {
                "name": name,
                "value": value,
                "help": comment,
                "group": group_name,
            }
            param = Param(**param)
            # group[variable_name] = parsed_value
            params.append(param)

        # groups[group_name] = group
    return params

def _parse_line(line):
    "parse a line within a block"
    # commas at the end of lines seem to be optional
    comment = ""
    if '!' in line:
        sep = line.index("!")
        comment = line[sep+1:].strip()
        line = line[:sep].strip()

    if line.endswith(','):
        line = line[:-1]

    k, v = line.split('=')
    name = k.strip()
    value = _parse_value(v.strip())
    return name, value, comment

def _parse_value(variable_value):
    """
    Tries to parse a single value, raises an exception if no single value is matched
    """
    try:
        parsed_value = int(variable_value)
    except ValueError:
        try:
            parsed_value = float(variable_value)
        except ValueError:
            if variable_value.lower() in ['.true.', 't', 'true']:
                # boolean
                parsed_value = True
            elif variable_value.lower() in ['.false.', 'f', 'false']:
                parsed_value = False
            elif variable_value.startswith("'") \
                and variable_value.endswith("'") \
                and variable_value.count("'") == 2 \
            or variable_value.startswith('"') \
                and variable_value.endswith('"') \
                and variable_value.count('"') == 2:
                parsed_value = variable_value[1:-1]
            elif variable_value.startswith("/") and variable_value.endswith("/"):
                # array /3,4,5/
                parsed_value = _parse_array(variable_value[1:-1].split(','))
            elif "," in variable_value:
                # array 3, 4, 5
                parsed_value = _parse_array(variable_value.split(','))
            elif '*' in variable_value:
                # 3*4  means [4, 4, 4, 4] ==> this is handled in _parse_array
                parsed_value = _parse_array([variable_value])
            elif len(variable_value.split()) > 1:
                # array 3 4 5
                parsed_value = _parse_array(variable_value.split())
            else:
                print("Parsing ERROR: >>>{}<<<".format(variable_value))
                raise ValueError(variable_value)
    return parsed_value

def _parse_array(values):
    """ parse a list of (string) values representing a fortran array
    and return a python list
    """
    assert type(values) is list
    parsed_value = []
    for v in values:
        if '*' in v:
            # 3* "a" === "a", "a", "a"
            mult, val = v.split('*')
            parsed_value.extend(int(mult) * [ _parse_value(val.strip())  ])
        else:
            parsed_value.append(_parse_value(v))
    return parsed_value

def _format_nml(params):
    """ format a flat parameter list to be written in the namelist
    """
    lines = []
    for group_name, group_params in groupby(params, lambda x: x.group):
        if group_name == "":
            print(list(group_params))
            raise ValueError("Group not defined. Cannot write to namelist.")
        lines.append("&%s" % group_name)
        for param in group_params:
            if isinstance(param.value, list):
                line = "  %s = %s" % (param.name, " ".join([_format_value(v) for v in param.value]))
            else:
                line = "  %s = %s" % (param.name, _format_value(param.value))
            if param.help:
                line += ' ! '+param.help
            lines.append(line)
        lines.append("/\n")
    return "\n".join(lines)

def _format_value(value):
    """ Format a value into fortran's namelist format (return a string)
    """
    if isinstance(value, bool):
        return value and '.true.' or '.false.'
    elif isinstance(value, int):
        return "%d" % value
    elif isinstance(value, float):
        # return "{:.3e}".format(value) # use exp. notation after 3 digits
        return "{}".format(value) # use exp. notation after 3 digits
    elif isinstance(value, basestring):
        return "'%s'" % value
    elif isinstance(value, complex):
        return "(%s,%s)" % (_format_value(value.real), _format_value(value.imag))
    else:
        raise Exception("Variable type not understood: %s" % type(value))


text:
namespace content {
class WebContents;
}

namespace views {
class BoundsAnimator;
class ViewModel;
}

namespace app_list {

class AppsGridView;
class ApplicationDragAndDropHost;
class AppListFolderItem;
class AppListMainView;
class AppListModel;
class AppListViewDelegate;
class AppsContainerView;
class PaginationModel;

// A view to manage sub views under the search box (apps grid view + page
// switcher and search results). The two sets of sub views are mutually
// exclusive. ContentsView manages a show state to choose one set to show
// and animates the transition between show states.
class ContentsView : public views::View {
 public:
  ContentsView(AppListMainView* app_list_main_view,
               PaginationModel* pagination_model,
               AppListModel* model,
               AppListViewDelegate* view_delegate);
  virtual ~ContentsView();

  // The app list gets closed and drag and drop operations need to be cancelled.
  void CancelDrag();

  // If |drag_and_drop| is not NULL it will be called upon drag and drop
  // operations outside the application list.
  void SetDragAndDropHostOfCurrentAppList(
      ApplicationDragAndDropHost* drag_and_drop_host);

  void ShowSearchResults(bool show);
  void ShowFolderContent(AppListFolderItem* folder);

  void Prerender();

  AppsContainerView* apps_container_view() { return apps_container_view_; }

  // Overridden from views::View:
  virtual gfx::Size GetPreferredSize() OVERRIDE;
  virtual void Layout() OVERRIDE;
  virtual bool OnKeyPressed(const ui::KeyEvent& event) OVERRIDE;
  virtual bool OnMouseWheel(const ui::MouseWheelEvent& event) OVERRIDE;

 private:
  enum ShowState {
    SHOW_APPS,
    SHOW_SEARCH_RESULTS,
  };

  // Sets show state.
  void SetShowState(ShowState show_state);

  // Invoked when show state is changed.
  void ShowStateChanged();

  void CalculateIdealBounds();
  void AnimateToIdealBounds();

  // Overridden from ui::EventHandler:
  virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
  virtual void OnScrollEvent(ui::ScrollEvent* event) OVERRIDE;

  ShowState show_state_;
  PaginationModel* pagination_model_;  // Owned by AppListController.

  AppsContainerView* apps_container_view_;  // Owned by the views hierarchy.

  scoped_ptr<views::ViewModel> view_model_;
  scoped_ptr<views::BoundsAnimator> bounds_animator_;

  DISALLOW_COPY_AND_ASSIGN(ContentsView);
};

}  // namespace app_list

#endif  // UI_APP_LIST_VIEWS_CONTENTS_VIEW_H_


text:
/*jquerypp@2.0.2#event/default/default*/
var $ = require('jquery');
$.fn.triggerAsync = function (type, data, success, prevented) {
    if (typeof data == 'function') {
        prevented = success;
        success = data;
        data = undefined;
    }
    if (this.length) {
        var el = this;
        setTimeout(function () {
            el.trigger({
                type: type,
                _success: success,
                _prevented: prevented
            }, data);
        }, 0);
    } else {
        if (success)
            success.call(this);
    }
    return this;
};
var types = {}, rnamespaces = /\.(.*)$/, $event = $.event;
$event.special['default'] = {
    add: function (handleObj) {
        types[handleObj.namespace.replace(rnamespaces, '')] = true;
    },
    setup: function () {
        return true;
    }
};
var oldTrigger = $event.trigger;
$event.trigger = function defaultTriggerer(event, data, elem, onlyHandlers) {
    var type = event.type || event, event = typeof event === 'object' ? event[$.expando] ? event : new $.Event(type, event) : new $.Event(type), res = oldTrigger.call($.event, event, data, elem, onlyHandlers), paused = event.isPaused && event.isPaused();
    if (!onlyHandlers && !event.isDefaultPrevented() && event.type.indexOf('default') !== 0) {
        oldTrigger('default.' + event.type, data, elem);
        if (event._success) {
            event._success(event);
        }
    }
    if (!onlyHandlers && event.isDefaultPrevented() && event.type.indexOf('default') !== 0 && !paused) {
        if (event._prevented) {
            event._prevented(event);
        }
    }
    if (paused) {
        event.isDefaultPrevented = event.pausedState.isDefaultPrevented;
        event.isPropagationStopped = event.pausedState.isPropagationStopped;
    }
    return res;
};
module.exports = $;


text:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

        Python For Data Science

This course shall cater to data exploration, manipulation and visualization

        Why
        

        Market-Need
        

            Facebook

            Whatsapp


text:
package org.jaudiotagger.audio.asf.io;

import org.jaudiotagger.audio.asf.data.GUID;
import org.jaudiotagger.audio.asf.util.Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * This modifier manipulates an ASF header extension object.
 *
 * @author Christian Laireiter
 */
public class AsfExtHeaderModifier implements ChunkModifier
{

    /**
     * List of modifiers which are to be applied to contained chunks.
     */
    private final List<ChunkModifier> modifierList;

    /**
     * Creates an instance.

     *
     * @param modifiers modifiers to apply.
     */
    public AsfExtHeaderModifier(final List<ChunkModifier> modifiers)
    {
        assert modifiers != null;
        this.modifierList = new ArrayList<ChunkModifier>(modifiers);
    }

    /**
     * Simply copies a chunk from source to
     * destination.

     * The method assumes, that the GUID has already been read and will write
     * the provided one to the destination.

     * The chunk length however will be read and used to determine the amount of
     * bytes to copy.
     *
     * @param guid        GUID of the current CHUNK.
     * @param source      source of an ASF chunk, which is to be located at the chunk
     *                    length field.
     * @param destination the destination to copy the chunk to.
     * @throws IOException on I/O errors.
     */
    private void copyChunk(final GUID guid, final InputStream source, final OutputStream destination) throws IOException
    {
        final long chunkSize = Utils.readUINT64(source);
        destination.write(guid.getBytes());
        Utils.writeUINT64(chunkSize, destination);
        Utils.copy(source, destination, chunkSize - 24);
    }

    /**
     * {@inheritDoc}
     */
    public boolean isApplicable(final GUID guid)
    {
        return GUID.GUID_HEADER_EXTENSION.equals(guid);
    }

    /**
     * {@inheritDoc}
     */
    public ModificationResult modify(final GUID guid, final InputStream source, final OutputStream destination) throws IOException
    {
        assert GUID.GUID_HEADER_EXTENSION.equals(guid);

        long difference = 0;
        final List<ChunkModifier> modders = new ArrayList<ChunkModifier>(this.modifierList);
        final Set<GUID> occuredGuids = new HashSet<GUID>();
        occuredGuids.add(guid);

        final BigInteger chunkLen = Utils.readBig64(source);
        final GUID reserved1 = Utils.readGUID(source);
        final int reserved2 = Utils.readUINT16(source);
        final long dataSize = Utils.readUINT32(source);

        assert dataSize == 0 || dataSize >= 24;
        assert chunkLen.subtract(BigInteger.valueOf(46)).longValue() == dataSize;

        /*
         * Stream buffer for the chunk list
         */
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        /*
         * Stream which counts read bytes. Dirty but quick way of implementing
         * this.
         */
        final CountingInputStream cis = new CountingInputStream(source);

        while (cis.getReadCount() < dataSize)
        {
            // read GUID
            final GUID curr = Utils.readGUID(cis);
            boolean handled = false;
            for (int i = 0; i < modders.size() && !handled; i++)
            {
                if (modders.get(i).isApplicable(curr))
                {
                    final ModificationResult modRes = modders.get(i).modify(curr, cis, bos);
                    difference += modRes.getByteDifference();
                    occuredGuids.addAll(modRes.getOccuredGUIDs());
                    modders.remove(i);
                    handled = true;
                }
            }
            if (!handled)
            {
                occuredGuids.add(curr);
                copyChunk(curr, cis, bos);
            }
        }
        // Now apply the left modifiers.
        for (final ChunkModifier curr : modders)
        {
            // chunks, which were not in the source file, will be added to the
            // destination
            final ModificationResult result = curr.modify(null, null, bos);
            difference += result.getByteDifference();
            occuredGuids.addAll(result.getOccuredGUIDs());
        }
        destination.write(GUID.GUID_HEADER_EXTENSION.getBytes());
        Utils.writeUINT64(chunkLen.add(BigInteger.valueOf(difference)).longValue(), destination);
        destination.write(reserved1.getBytes());
        Utils.writeUINT16(reserved2, destination);
        Utils.writeUINT32(dataSize + difference, destination);
        destination.write(bos.toByteArray());
        return new ModificationResult(0, difference, occuredGuids);
    }

}


text:
(function (twoFactorAuthenticator) {

    'use strict';

    var HTTPStatus = require('http-status'),
        messageConfig = require('../configs/api.message.config'),
        Promise = require("bluebird"),
        twoFactorAuthHelper = require('../helpers/two.factor.authentication.helper'),
        errorHelper = require('../helpers/error.helper'),
        userController = require('../controllers/user.server.controller'),
        requestIp = require('request-ip'),
        userAgent = require('useragent'),
        utilityHelper = require('../helpers/utilities.helper'),
        authorizationTokenController = require('../controllers/authorization.token.management.server.controller'),
        tokenConfigs = require('../configs/token.config'),
        jwtTokenGeneratorHelper = require('../helpers/jwt.token.generator.helper');

    twoFactorAuthenticator.validateTOTPToken = function (req, res, next) {
        if (req.body.totpToken && req.params) {
            userController.getUserByID(req)
                .then(function (userInfo) {
                    if (userInfo) {
                        return [userInfo, twoFactorAuthHelper.verifyMultiFactorAuthCode(req, userInfo.twoFactorAuthSharedSecret)];

                    } else {
                        throw new Promise.CancellationError('{ "statusCode":"' + HTTPStatus.UNAUTHORIZED + '", "message": "' + messageConfig.twoFactorAuthentication.notVerified + '"}');
                    }
                })
                .spread(function (userInfo, verified) {
                    if (verified) {
                        req.loginStatusMessage = jwtTokenGeneratorHelper.generateJWTToken(req, userInfo);

                        var userAgentDetail= userAgent.lookup(req.headers['user-agent']);
                        var ipAddress = requestIp.getClientIp(req);
                        var _hours = utilityHelper.removeCharFromString(tokenConfigs.expires, 'h');
                        var tokenExpiryDate = new Date(new Date().getTime() + (parseInt(_hours) * 60 * 60 * 1000));
                        req.loginStatusMessage.tokenExpiryDate = tokenExpiryDate;

                        return [req.loginStatusMessage, authorizationTokenController.postAuthorizationTokenInfo(req.loginStatusMessage.token, userAgentDetail, userAgentDetail.family, ipAddress, tokenExpiryDate, req.loginStatusMessage.userInfo._id)];

                    } else {
                        throw new Promise.CancellationError('{ "statusCode":"' + HTTPStatus.UNAUTHORIZED + '", "message": "' + messageConfig.twoFactorAuthentication.notVerified + '"}');
                    }
                })
                .spread(function (loginStatusMessage) {
                    res.status(HTTPStatus.OK);
                    res.json(loginStatusMessage);
                })
                .catch(Promise.CancellationError, function (cancellationErr) {
                    errorHelper.customErrorResponse(res, cancellationErr, next);
                })
                .catch(function (err) {
                    return next(err);
                });
        } else {
            res.status(HTTPStatus.UNAUTHORIZED);
            res.json({
                success: false,
                status: HTTPStatus.UNAUTHORIZED,
                message: messageConfig.twoFactorAuthentication.notVerified
            });
        }
    };

})(module.exports);


text:
using Xunit;

namespace CoreTests.Bootstrap.Mocks
{
    public class ServiceRegistrationTests
    {
        [Fact]
        public void DefaultServices_OverridenBy_OtherPlugins()
        {

        }

        [Fact]
        public void CoreServices_OverridenBy_ApplicationPlugins()
        {

        }

        [Fact]
        public void ApplicationServices_OverridenBy_HostServices()
        {

        }

        [Fact]
        public void RegisteredServices_Overriden_WhenComposing()
        {

        }
    }
}


text:
package io.cdap.delta.mysql;

import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.annotation.Plugin;
import io.cdap.cdap.api.plugin.PluginProperties;
import io.cdap.delta.api.Configurer;
import io.cdap.delta.api.DeltaSource;
import io.cdap.delta.api.DeltaSourceContext;
import io.cdap.delta.api.EventEmitter;
import io.cdap.delta.api.EventReader;
import io.cdap.delta.api.EventReaderDefinition;
import io.cdap.delta.api.SourceConfigurer;
import io.cdap.delta.api.assessment.TableAssessor;
import io.cdap.delta.api.assessment.TableDetail;
import io.cdap.delta.api.assessment.TableRegistry;
import io.cdap.delta.plugin.common.DriverCleanup;

import java.sql.Driver;
import java.util.UUID;

/**
 * Mysql origin.
 */
@Plugin(type = DeltaSource.PLUGIN_TYPE)
@Name(MySqlDeltaSource.NAME)
@Description("Delta source for MySQL.")
public class MySqlDeltaSource implements DeltaSource {
  public static final String NAME = "mysql";
  private final MySqlConfig conf;

  public MySqlDeltaSource(MySqlConfig conf) {
    this.conf = conf;
  }

  @Override
  public void configure(SourceConfigurer configurer) {
    // add MySql JDBC Plugin usage at configure time
    configurer.usePluginClass("jdbc", conf.getJdbcPluginName(), conf.getJDBCPluginId(),
                              PluginProperties.builder().build());
  }

  @Override
  public EventReader createReader(EventReaderDefinition definition, DeltaSourceContext context,
                                  EventEmitter eventEmitter) {
    return new MySqlEventReader(definition.getTables(), conf, context, eventEmitter);
  }

  @Override
  public TableRegistry createTableRegistry(Configurer configurer) throws Exception {
    return new MySqlTableRegistry(conf, getDriverCleanup(configurer));
  }

  @Override
  public TableAssessor<TableDetail> createTableAssessor(Configurer configurer) throws Exception {
    return new MySqlTableAssessor(conf, getDriverCleanup(configurer));
  }

  private DriverCleanup getDriverCleanup(Configurer configurer) throws Exception {
    Class<? extends Driver> jdbcDriverClass = configurer.usePluginClass("jdbc", conf.getJdbcPluginName(),
                                                                        conf.getJDBCPluginId() + "." +
                                                                          UUID.randomUUID().toString(),
                                                                        PluginProperties.builder().build());
    if (jdbcDriverClass == null) {
      throw new IllegalArgumentException("JDBC plugin " + conf.getJdbcPluginName() + " not found.");
    }

    return DriverCleanup.ensureJDBCDriverIsAvailable(jdbcDriverClass, conf.getJdbcURL());
  }
}


text:
package com.solersoft.fpvr.fpvrlib;

/**
 * Created by jbienz on 5/20/2015.
 */
public class Attitude
{
    //region Constructors

    /**
     * Initializes a new Attitude instance where all angles are zero.
     */
    public Attitude(){}

    /**
     * Initializes a new Attitude instance.
     * @param pitch The pitch in degrees.
     * @param roll The roll in degrees.
     * @param yaw The yaw in degrees.
     */
    public Attitude(double pitch, double roll, double yaw)
    {
        this.pitch = pitch;
        this.roll = roll;
        this.yaw = yaw;
    }
    //endregion

    //region Public Members
    /**
     * The yaw in degrees.
     */
    public double yaw=0;

    /**
     * The pitch in degrees.
     */
    public double pitch=0;

    /**
     * The roll in degrees.
     */
    public double roll=0;
    //endregion

}


text:
using Moq;
using MScResearchTool.Server.BusinessLogic.Businesses;
using MScResearchTool.Server.Core.Models;
using MScResearchTool.Server.Core.Repositories;
using MScResearchTool.Server.Tests.Core.Core;
using MScResearchTool.Server.Tests.Core.Units;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MScResearchTool.Server.Tests.Core.BusinessTests
{
    public abstract class CrackingDistributionsBusinessTestsBase : MockBase<TestingUnit<CrackingDistributionsBusiness>>
    {
        protected int CrackingId { get; private set; }
        protected int DistributionFirstId { get; private set; }
        protected int DistributionSecondId { get; private set; }
        protected int NotExistingId { get; private set; }

        protected IList<CrackingDistribution> DistributionsDatabase { get; set; }

        public CrackingDistributionsBusinessTestsBase()
        {
            CrackingId = 42;
            DistributionFirstId = 10;
            DistributionSecondId = 11;

            var random = new Random();
            NotExistingId = random.Next(1, 1000);

            DistributionsDatabase = CreateDistributions();

            while (NotExistingId == DistributionFirstId && NotExistingId == DistributionSecondId)
                NotExistingId = random.Next(1, 1000);
        }

        protected override TestingUnit<CrackingDistributionsBusiness> GetUnit()
        {
            var unit = new TestingUnit<CrackingDistributionsBusiness>();

            unit.AddDependency(new Mock<ICrackingDistributionsRepository>(MockBehavior.Strict));

            return unit;
        }

        protected CrackingDistributionsBusiness GetUniversalMockedUnit()
        {
            TestingUnit<CrackingDistributionsBusiness> testingUnit = GetUnit();

            var mockDistributionsRepository = testingUnit.GetDependency<Mock<ICrackingDistributionsRepository>>();

            mockDistributionsRepository.Setup(r => r.Read()).Returns(() =>
            {
                var ret = DistributionsDatabase;

                foreach (var item in ret)
                {
                    item.Task = null;
                }

                return ret;
            });

            mockDistributionsRepository.Setup(re => re.ReadEager()).Returns(DistributionsDatabase);

            mockDistributionsRepository.Setup(c => c.Create(It.IsAny<CrackingDistribution>())).Callback((CrackingDistribution freshDistribution) =>
            {
                DistributionsDatabase.Add(freshDistribution);
            }).Verifiable();

            mockDistributionsRepository.Setup(u => u.Update(It.IsAny<CrackingDistribution>())).Callback((CrackingDistribution updatedDistribution) =>
            {
                var oldItem = DistributionsDatabase.First(x => x.Id == updatedDistribution.Id);
                var index = DistributionsDatabase.IndexOf(oldItem);
                DistributionsDatabase[index] = updatedDistribution;
            });

            mockDistributionsRepository.Setup(d => d.Delete(It.IsAny<int>())).Callback((int id) =>
            {
                var item = DistributionsDatabase.First(x => x.Id == id);
                DistributionsDatabase.Remove(item);
            }).Verifiable();

            return testingUnit.GetResolvedTestingUnit();
        }

        private IList<CrackingDistribution> CreateDistributions()
        {
            var task = CreateTask();

            var list = new List<CrackingDistribution>()
            {
                new CrackingDistribution()
                {
                    FileName = "file.zip",
                    ArchivePassword = "passw0rd",
                    CreationDate = new DateTime(2017, 10, 1),
                    DeviceCPU = "arm 900MHz",
                    DeviceRAM = 512,
                    DeviceResult = null,
                    DeviceTime = 2.37,
                    Id = 10,
                    IsAvailable = false,
                    IsFinished = true,
                    Task = task
                },

                new CrackingDistribution()
                {
                    FileName = "file.zip",
                    ArchivePassword = "passw0rd",
                    CreationDate = new DateTime(2017, 10, 1),
                    DeviceCPU = "arm 900MHz",
                    DeviceRAM = 512,
                    DeviceResult = null,
                    DeviceTime = 2.37,
                    Id = 11,
                    IsAvailable = false,
                    IsFinished = false,
                    Task = task
                }
            };

            return list;
        }

        private Cracking CreateTask()
        {
            var integration = new Cracking()
            {
                FileName = "file.zip",
                ArchivePassword = "passw0rd",
                CreationDate = new DateTime(2017, 9, 30),
                DesktopCPU = "X6 1000MHz",
                DesktopRAM = 1024,
                DroidRanges = 2,
                FullResult = "passw0rd",
                FullTime = 4.19,
                Id = CrackingId,
                IsAvailable = false,
                IsFinished = true,
                PartialResult = "passw0rd",
                PartialTime = 5.37
            };

            return integration;
        }
    }
}


text:
KEYNAME=yantisec2
SUBNETID=subnet-d260adb7

# USER DEFINABLE (OPTIONAL)
REGION=us-west-2
IMAGEID=ami-e7527ed7

# Exit the script if any statements returns a non true (0) value.
set -e

# Exit the script on any uninitialized variables.
set -u

# Create our new instance
ID=$(aws ec2 run-instances \
  --image-id ${IMAGEID} \
  --key-name ${KEYNAME} \
  --instance-type t2.micro \
  --region ${REGION} \
  --subnet-id ${SUBNETID} | \
    grep InstanceId | awk -F\" '{print $4}')

# Sleep 10 seconds here. Just to give it time to be created.
sleep 10
echo "Instance ID: $ID"

# Query every second until we get our IP.
while [ 1 ]; do
  IP=$(aws ec2 describe-instances --instance-ids $ID | \
    grep PublicIpAddress | \
    awk -F\" '{print $4}')

  if [ -n "$IP" ]; then
    echo "IP Address: $IP"
    break
  fi

  sleep 1
done

# Connect to the server and launch our container.
ssh -o ConnectionAttempts=255 \
    -o StrictHostKeyChecking=no \
    -i $HOME/.ssh/${KEYNAME}.pem\
    ec2-user@$IP -tt << EOF
  sudo yum update -y;
  sudo yum install docker -y
  sudo service docker start
  sudo docker run \
    -v /home/ec2-user/.ssh/authorized_keys:/authorized_keys:ro \
    -d \
    -h docker \
    -p 49158:22 \
    yantis/ssh-hpn-x
  exit
EOF

# Now that is is launched go ahead and connect to our new server.
ssh -Y \
    -o ConnectionAttempts=255 \
    -o StrictHostKeyChecking=no \
     docker@$IP -p 49158

aws ec2 terminate-instances  --instance-ids $ID


text:
"""AppVersioning
Module for app tracking using both app versioning and appetite versioning.

Many applications have their own application version.  This is module modifies
the application version with the commit id of the application pull.  This helps
verify that applications actually got to their source.
"""

import re
import os

import consts
import helpers

def is_stanza(line):
    """Searches string to see if it is a stanza"""
    return re.search(r"^\[.*\] *", line)

def has_version_key(line):
    """Checks to see if line has version key"""
    keyvalue = line.split('=')
    if len(keyvalue) == 2:
        # Looks for version key in file, will return the first found
        if keyvalue[0].strip().lower() == consts.VERSION_KEY:
            return True
    return False

def create_version(version, commit_id):
    """Create a version based on the version provided and the commit id"""
    return "%s_%s" % (version, commit_id)

def get_version(line, commit_id):
    """Get Version based on either default or """
    if not commit_id:
        return consts.DEFAULT_VERSION

    keyvalue = line.split('=')
    if len(keyvalue) == 2:
        # Looks for version key in file, will return the first found
        if keyvalue[0].strip().lower() == consts.VERSION_KEY:
            return create_version(keyvalue[1].strip(), commit_id)
    return create_version(consts.DEFAULT_VERSION, commit_id)

def create_version_line(new_version):
    """Create a version line to be used in configuration file"""
    return str("%s = %s\n" % (consts.VERSION_KEY, new_version))

def add_version_to_content(file_content, commit_id, version=None, remove_version=False):
    """Add version to provided configuration

    Function will search for and replace version, if version is not found it
    will add the version to the config
    """
    updated_content = []
    current_version = None
    launcher_found = False
    app_version = None
    default_version = version if version else get_version("", commit_id)

    while len(file_content) > 0:
        line = file_content.pop(0)

        # Looks for launcher stanza to add version information
        if is_stanza(line):
            launcher_found = consts.LAUNCHER_STANZA in line

            if launcher_found:
                # Look ahead for version
                for stanza_line in file_content:
                    # break if next stanza is found
                    if is_stanza(stanza_line):
                        break

                    # Look for version key and get value with commit id
                    if has_version_key(stanza_line):
                        app_version = get_version(stanza_line, commit_id)
                        break

            # Do not need stanza after this, add and skip
            if len(file_content) > 0:
                updated_content.append(line)
                line = file_content.pop(0)

        if launcher_found:
            if not remove_version:
                if not current_version:
                    # From look ahead, replace version value since it exists
                    if app_version:
                        if has_version_key(line):
                            current_version = version if version else app_version
                            updated_content.append(create_version_line(current_version))
                    else:
                        # Since version does not exist in stanza, add version
                        current_version = default_version
                        updated_content.append(create_version_line(current_version))

            # Version updates should already be done or skipped,
            # ignoring version from content
            if has_version_key(line):
                continue

        updated_content.append(line)

    if not current_version and not remove_version:
        # Launcher stanza is not found, appends to end of file
        include_nl = '\n' if len(updated_content) > 0 else ''
        current_version = default_version

        # Create basic stanza with version number
        app_config = "\r\n[%s]\r\n%s = %s" % (consts.LAUNCHER_STANZA,
                                              consts.VERSION_KEY,
                                              current_version)

        # need to add newline after since writeline does not include them
        updated_content += ['%s\n' % config_line for config_line in
                            (str(include_nl + app_config)).
                            splitlines()]

    file_content += updated_content

    return current_version

def create_app_version(app_path, commit_id):
    """Looks in application path and finds version file to update.

    Looks for valid application version and updates with commit id.
    """
    # Get the paths for the apps.conf in both locations
    default_app_path = os.path.join(app_path, consts.LOCATION_DEFAULT)
    default_local_path = os.path.join(app_path, consts.LOCATION_LOCAL)

    # Tries to get the content from both confs
    default_content = helpers.get_contents(default_app_path)
    local_content = helpers.get_contents(default_local_path)

    # update default apps.conf with new version number
    default_content = default_content if default_content else []
    add_version_to_content(default_content, commit_id)
    helpers.write_contents(default_app_path, default_content)

    # If local found, remove versions
    if local_content:
        add_version_to_content(local_content, commit_id, None, True)
        helpers.write_contents(default_local_path, local_content)


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

namespace Microsoft.Recognizers.Text.Choice
{
    public class BooleanModel : ChoiceModel
    {
        public BooleanModel(IParser parser, IExtractor extractor) : base(parser,extractor)
        {

        }

        public override string ModelTypeName => Constants.MODEL_BOOLEAN;

        protected override SortedDictionary<string, object> GetResolution(ParseResult parseResult)
        {
            var data = parseResult.Data as OptionsParseDataResult;
            var results = new SortedDictionary<string, object>()
            {
                { "value", parseResult.Value },
                { "score", data.Score },
                { "otherResults", data.OtherMatches.Select(l => new
                    {
                        Text = l.Text,
                        Value = l.Value,
                        Score = l.Score
                    }
                )},

            };

            return results;
        }
    }
}


text:
package plugin

import (
	"context"

	"github.com/docker/cli/cli"
	"github.com/docker/cli/cli/command"
	"github.com/docker/cli/cli/command/inspect"
	flagsHelper "github.com/docker/cli/cli/flags"
	"github.com/spf13/cobra"
)

type inspectOptions struct {
	pluginNames []string
	format      string
}

func newInspectCommand(dockerCli command.Cli) *cobra.Command {
	var opts inspectOptions

	cmd := &cobra.Command{
		Use:   "inspect [OPTIONS] PLUGIN [PLUGIN...]",
		Short: "Display detailed information on one or more plugins",
		Args:  cli.RequiresMinArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.pluginNames = args
			return runInspect(dockerCli, opts)
		},
	}

	flags := cmd.Flags()
	flags.StringVarP(&opts.format, "format", "f", "", flagsHelper.InspectFormatHelp)
	return cmd
}

func runInspect(dockerCli command.Cli, opts inspectOptions) error {
	client := dockerCli.Client()
	ctx := context.Background()
	getRef := func(ref string) (interface{}, []byte, error) {
		return client.PluginInspectWithRaw(ctx, ref)
	}

	return inspect.Inspect(dockerCli.Out(), opts.pluginNames, opts.format, getRef)
}


text:
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Hike } from './hike';

@Component({
	moduleId: module.id,
	selector: 'hike-summary',
	templateUrl: 'hike-summary.component.html',
	styles: ['a { text-decoration: none } a:hover { color: #999}']
})
export class HikeSummaryComponent {
	@Input() hike: Hike;
	@Output() addHikeAsFavorite = new EventEmitter<Hike>();

	toggleAsTodoHike(isAdded:any){
		console.log("checked : ", isAdded)
		if(isAdded){
				this.addHikeAsFavorite.emit(this.hike);
		}
	}
}


text:
/**
 *
 */
package org.apache.eagle.jpm.util.resourcefetch;

import org.apache.eagle.jpm.util.Constants;
import org.apache.eagle.jpm.util.resourcefetch.connection.InputStreamUtils;
import org.apache.eagle.jpm.util.resourcefetch.ha.HAURLSelector;
import org.apache.eagle.jpm.util.resourcefetch.ha.HAURLSelectorImpl;
import org.apache.eagle.jpm.util.resourcefetch.model.AppInfo;
import org.apache.eagle.jpm.util.resourcefetch.model.AppsWrapper;
import org.apache.eagle.jpm.util.resourcefetch.model.ClusterInfo;
import org.apache.eagle.jpm.util.resourcefetch.model.ClusterInfoWrapper;
import org.apache.eagle.jpm.util.resourcefetch.url.JobListServiceURLBuilderImpl;
import org.apache.eagle.jpm.util.resourcefetch.url.ServiceURLBuilder;
import org.apache.eagle.jpm.util.resourcefetch.url.SparkCompleteJobServiceURLBuilderImpl;
import org.apache.eagle.jpm.util.resourcefetch.url.URLUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class RMResourceFetcher implements ResourceFetcher<AppInfo> {

    private static final Logger LOG = LoggerFactory.getLogger(RMResourceFetcher.class);
    private final HAURLSelector selector;
    private final ServiceURLBuilder jobListServiceURLBuilder;
    private final ServiceURLBuilder sparkCompleteJobServiceURLBuilder;
    private static final ObjectMapper OBJ_MAPPER = new ObjectMapper();

    static {
        OBJ_MAPPER.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
    }

    public RMResourceFetcher(String[] rmBasePaths) {
        this.jobListServiceURLBuilder = new JobListServiceURLBuilderImpl();
        this.sparkCompleteJobServiceURLBuilder = new SparkCompleteJobServiceURLBuilderImpl();

        this.selector = new HAURLSelectorImpl(rmBasePaths, jobListServiceURLBuilder, Constants.CompressionType.GZIP);
    }

    private void checkUrl() throws IOException {
        if (!selector.checkUrl(jobListServiceURLBuilder.build(selector.getSelectedUrl(), Constants.JobState.RUNNING.name()))) {
            selector.reSelectUrl();
        }
    }

    private List<AppInfo> doFetchFinishApplicationsList(String urlString, Constants.CompressionType compressionType) throws Exception {
        List<AppInfo> result;
        InputStream is = null;
        try {
            checkUrl();
            LOG.info("Going to call yarn api to fetch finished application list: " + urlString);
            is = InputStreamUtils.getInputStream(urlString, null, compressionType);
            final AppsWrapper appWrapper = OBJ_MAPPER.readValue(is, AppsWrapper.class);
            if (appWrapper != null && appWrapper.getApps() != null
                && appWrapper.getApps().getApp() != null) {
                result = appWrapper.getApps().getApp();
                return result;
            }
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    LOG.warn("{}", e);
                }
            }
        }
    }

    private String getSparkRunningJobURL() {
        return selector.getSelectedUrl()
                + "/"
                + Constants.V2_APPS_URL
                + "?applicationTypes=SPARK&state=RUNNING&"
                + Constants.ANONYMOUS_PARAMETER;
    }

    private String getMRRunningJobURL() {
        return String.format("%s/%s?applicationTypes=MAPREDUCE&state=RUNNING&%s",
            selector.getSelectedUrl(),
            Constants.V2_APPS_URL,
            Constants.ANONYMOUS_PARAMETER);
    }

    private String getMRFinishedJobURL(String lastFinishedTime) {
        String url = URLUtil.removeTrailingSlash(selector.getSelectedUrl());
        return url + "/" + Constants.V2_APPS_URL
                + "?applicationTypes=MAPREDUCE&state=FINISHED&finishedTimeBegin="
                + lastFinishedTime + "&" + Constants.ANONYMOUS_PARAMETER;
    }

    private List<AppInfo> doFetchRunningApplicationsList(String urlString, Constants.CompressionType compressionType) throws Exception {
        List<AppInfo> result;
        InputStream is = null;
        try {
            checkUrl();
            LOG.info("Going to call yarn api to fetch running application list: " + urlString);
            is = InputStreamUtils.getInputStream(urlString, null, compressionType);
            final AppsWrapper appWrapper = OBJ_MAPPER.readValue(is, AppsWrapper.class);
            if (appWrapper != null && appWrapper.getApps() != null && appWrapper.getApps().getApp() != null) {
                result = appWrapper.getApps().getApp();
                return result;
            }
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    LOG.warn("{}", e);
                }
            }
        }
    }

    private List<AppInfo> getResource(Constants.ResourceType resourceType, Constants.CompressionType compressionType, Object... parameter) throws Exception {
        switch (resourceType) {
            case COMPLETE_SPARK_JOB:
                final String urlString = sparkCompleteJobServiceURLBuilder.build(selector.getSelectedUrl(), (String) parameter[0]);
                return doFetchFinishApplicationsList(urlString, compressionType);
            case RUNNING_SPARK_JOB:
                return doFetchRunningApplicationsList(getSparkRunningJobURL(), compressionType);
            case RUNNING_MR_JOB:
                return doFetchRunningApplicationsList(getMRRunningJobURL(), compressionType);
            case COMPLETE_MR_JOB:
                return doFetchFinishApplicationsList(getMRFinishedJobURL((String) parameter[0]), compressionType);
            default:
                throw new Exception("Not support resourceType :" + resourceType);
        }
    }

    public List<AppInfo> getResource(Constants.ResourceType resourceType, Object... parameter) throws Exception {
        try {
            return getResource(resourceType, Constants.CompressionType.GZIP, parameter);
        } catch (java.util.zip.ZipException ex) {
            return getResource(resourceType, Constants.CompressionType.NONE, parameter);
        }
    }

    private String getClusterInfoURL() {
        return selector.getSelectedUrl() + "/" + Constants.YARN_API_CLUSTER_INFO + "?" + Constants.ANONYMOUS_PARAMETER;
    }

    public ClusterInfo getClusterInfo() throws Exception {
        InputStream is = null;
        try {
            checkUrl();
            final String urlString = getClusterInfoURL();
            LOG.info("Calling yarn api to fetch cluster info: " + urlString);
            is = InputStreamUtils.getInputStream(urlString, null, Constants.CompressionType.GZIP);
            final ClusterInfoWrapper clusterInfoWrapper = OBJ_MAPPER.readValue(is, ClusterInfoWrapper.class);
            if (clusterInfoWrapper != null && clusterInfoWrapper.getClusterInfo() != null) {
                return clusterInfoWrapper.getClusterInfo();
            }
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    LOG.warn("{}", e);
                }
            }
        }
    }
}


text:
$(document).ready(function()
{
	$(".nav").accessibleDropDown();
});

$.fn.accessibleDropDown = function ()
{
	var el = $(this);

	/* Setup dropdown menus for IE 6 */

	$("li", el).mouseover(function() {
		$(this).addClass("hover");
	}).mouseout(function() {
		$(this).removeClass("hover");
	});

	/* Make dropdown menus keyboard accessible */

	$("a", el).focus(function() {
		$(this).parents("li").addClass("hover");
	}).blur(function() {
		$(this).parents("li").removeClass("hover");
	});
}


text:
/* Ê×Ò³Ñùʽ*/
body,td,th{font-size:12px; font-family:"ËÎÌå"}
body{margin:0 0 0 0}
.ceng {	border: 1px solid #FFFFFF;}
#navigation a{color:#0768B7; text-decoration:underline; margin-right:30px; font-size:14px; font-weight:bold}
#navigation a:hover{color:#ff0000; text-decoration:underline; margin-right:30px; font-size:14px; font-weight:bold}
#toplink div{color:#FFA200; font-size:10px}
#toplink a{color:#FFA200; text-decoration:none; font-size:12px}
#toplink a:hover{color:#FFA200; text-decoration:underline; font-size:12px}
.biaoti{color:#0768B7; font-weight:bold}
#neirong a{color:#0768B7; text-decoration:none; line-height:20px; font-weight:normal}
#neirong a:hover{color:#ff0000; text-decoration:none; line-height:20px; font-weight:normal}
#neirong {font-weight:bold; color:#999999}
#banquan {color:#9B9B9B; line-height:20px}
#banquan a{color:#9B9B9B; line-height:20px; text-decoration:none}
#banquan a:hover{color:#ff0000; line-height:20px; text-decoration:underline}
/*ËÑË÷½á¹ûÒ³Ñùʽ*/
.bk{border-bottom:1px solid #74ADDC; border-top:1px solid #74ADDC}
.biaoti2{color:#000000; font-weight:bold}
.biaoti3{color:#000000; font-weight:bold; font-size:14px}
#leftlink {color:#999999;border-top:1px solid #E4E4E4}
#leftlink ul {list-style:none; margin:0; padding:0; padding-left:3px}
#leftlink li {background:url(img3.gif) left no-repeat; padding-left:10px}
#leftlink a { color:#000000; text-decoration:none; line-height:22px}
#leftlink a:hover { color:#ff0000; text-decoration:underline; line-height:22px}
#rightlink {color:#000000;border-top:1px solid #E4E4E4; line-height:20px}
#rightlink ul {list-style:none; margin:0; padding:0; padding-left:3px}
#rightlink li {background:url(img4.gif) left top no-repeat; padding-left:10px}
#rightlink a { color:#000000; text-decoration:none; line-height:20px}
#rightlink a:hover { color:#ff0000; text-decoration:underline; line-height:20px}
#rightlink span a { color:#999999; text-decoration:none; line-height:20px}
#rightlink span a:hover { color:#ff0000; text-decoration:underline; line-height:20px}
#rightlink span { color:#999999; line-height:20px; padding-left:5px}
#centerlink {color:#000000; line-height:18px; font-size:13px}
#centerlink ul {list-style:none; margin:0; padding:0; padding-left:3px; padding-bottom:20px}
#centerlink a { color:#0768B7; text-decoration:underline; font-size:16px; line-height:20px}
#centerlink a:hover { color:#ff0000; text-decoration:underline; font-size:16px; line-height:20px}
#centerlink span a { color:#999999; text-decoration:none; line-height:18px;}
#centerlink span a:hover { color:#ff0000; text-decoration:underline; line-height:18px}
#centerlink span { color:#03922B; line-height:18px; padding-left:5px; font-size:13px}
#more  a { color:#0768B7; text-decoration:underline; line-height:18px; font-size:13px}
#more  a:hover { color:#ff0000; text-decoration:underline; line-height:18px; font-size:13px}
#more  { color:#000000; line-height:18px; padding-left:5px; font-size:13px}
/*¾ÍÒ½Ö¸ÄÏÒ³Ñùʽ*/
#biaoti4{font-size:16px; font-weight:bold;}
#biaoti4 span{font-size:16px; font-weight:bold; color:#FF0000}
.luxianbiaoti{color:#666666; font-weight:bold}
.luxianneirong td{padding:20px 10px 20px 10px}
/*¾ÍÒ½Ö¸ÄϵØÇøÒ³Ñùʽ*/
#rightlink2 {color:#000000;border-top:1px solid #E4E4E4; line-height:20px}
#rightlink2 ul {list-style:none; margin:0; padding:0; padding-left:3px; padding-bottom:10px}
#rightlink2 li {background:url(img4.gif) left top no-repeat; padding-left:10px}
#rightlink2 a { color:#000000; text-decoration:none; line-height:20px}
#rightlink2 a:hover { color:#ff0000; text-decoration:underline; line-height:20px}
#rightlink2 span a { color:#999999; text-decoration:underline; line-height:20px}
#rightlink2 span a:hover { color:#ff0000; text-decoration:underline; line-height:20px}
#rightlink2 span { color:#999999; line-height:20px; padding-left:5px}
#neirong2 a{color:#000000; text-decoration:none; line-height:20px; font-weight:normal}
#neirong2 a:hover{color:#ff0000; text-decoration:underline; line-height:20px; font-weight:normal}
#neirong2 {color:#999999}
#neirong2 span{font-weight:bold}
/*¾ÍÒ½³öÕïʱ¼äÁбí½çÃæ*/
#wenben {line-height:18px; padding-left:10px; padding-right:10px}
#wenben a{font-weight:bold; color:#666666}
#wenben a:hover{font-weight:bold; color:#FF0000}
#keshiliebiao a{color:#666666; line-height:20px}
#keshiliebiao a:hover{color:#FF0000;line-height:20px}
.doctor_list td{padding:5px 5px 5px 5px}
#doctor_list a{ color:#FF3333; font-weight:bold; text-decoration:underline}
#doctor_list a:hover{ color:#FF0000; font-weight:bold; text-decoration:none}
#doctor_list { color:#666666}
/*Ò½Éú¸öÈËÐÅÏ¢Ò³Ãæ*/
#wenben2 span {line-height:18px; font-weight:bold}
#wenben2 {line-height:18px; padding-left:10px}
/*ÇøÓòÒ½Ôº²éѯ*/
#quyucx a{color:#000000; text-decoration:none; margin-right:20px; line-height:20px}
#quyucx a:hover{color:#000000; text-decoration:underline; margin-right:20px; line-height:20px}
#quyuyy a{color:#000000; text-decoration:none; margin-right:40px; line-height:20px}
#quyuyy a:hover{color:#000000; text-decoration:underline; margin-right:40px; line-height:20px}


text:
package protorpc

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/gorilla/rpc"
)

var null = json.RawMessage([]byte("null"))

// ----------------------------------------------------------------------------
// Request and Response
// ----------------------------------------------------------------------------

// serverRequest represents a ProtoRPC request received by the server.
type serverRequest struct {
	// A String containing the name of the method to be invoked.
	Method string `json:"method"`
	// An Array of objects to pass as arguments to the method.
	Params *json.RawMessage `json:"params"`
	// The request id. This can be of any type. It is used to match the
	// response with the request that it is replying to.
	Id *json.RawMessage `json:"id"`
}

// serverResponse represents a ProtoRPC response returned by the server.
type serverResponse struct {
	// The Object that was returned by the invoked method. This must be null
	// in case there was an error invoking the method.
	Result interface{} `json:"result"`
	// An Error object if there was an error invoking the method. It must be
	// null if there was no error.
	Error interface{} `json:"error"`
	// This must be the same id as the request it is responding to.
	Id *json.RawMessage `json:"id"`
}

// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------

// NewCodec returns a new ProtoRPC Codec.
func NewCodec() *Codec {
	return &Codec{}
}

// Codec creates a CodecRequest to process each request.
type Codec struct {
}

// NewRequest returns a CodecRequest.
func (c *Codec) NewRequest(r *http.Request) rpc.CodecRequest {
	return newCodecRequest(r)
}

// ----------------------------------------------------------------------------
// CodecRequest
// ----------------------------------------------------------------------------

// newCodecRequest returns a new CodecRequest.
func newCodecRequest(r *http.Request) rpc.CodecRequest {
	// Decode the request body and check if RPC method is valid.
	req := new(serverRequest)
	path := r.URL.Path
	index := strings.LastIndex(path, "/")
	if index < 0 {
		return &CodecRequest{request: req, err: fmt.Errorf("rpc: no method: %s", path)}
	}
	req.Method = path[index+1:]
	err := json.NewDecoder(r.Body).Decode(&req.Params)
	r.Body.Close()
	var errr error
	if err != io.EOF {
		errr = err
	}
	return &CodecRequest{request: req, err: errr}
}

// CodecRequest decodes and encodes a single request.
type CodecRequest struct {
	request *serverRequest
	err     error
}

// Method returns the RPC method for the current request.
//
// The method uses a dotted notation as in "Service.Method".
func (c *CodecRequest) Method() (string, error) {
	if c.err == nil {
		return c.request.Method, nil
	}
	return "", c.err
}

// ReadRequest fills the request object for the RPC method.
func (c *CodecRequest) ReadRequest(args interface{}) error {
	if c.err == nil {
		if c.request.Params != nil {
			c.err = json.Unmarshal(*c.request.Params, args)
		} else {
			c.err = errors.New("rpc: method request ill-formed: missing params field")
		}
	}
	return c.err
}

// WriteResponse encodes the response and writes it to the ResponseWriter.
//
// The err parameter is the error resulted from calling the RPC method,
// or nil if there was no error.
func (c *CodecRequest) WriteResponse(w http.ResponseWriter, reply interface{}, methodErr error) error {
	if c.err != nil {
		return c.err
	}
	res := &serverResponse{
		Result: reply,
		Error:  &null,
		Id:     c.request.Id,
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if methodErr != nil {
		// Propagate error message as string.
		res.Error = methodErr.Error()
		// Result must be null if there was an error invoking the method.
		res.Result = &struct {
			ErrorMessage interface{} `json:"error_message"`
		}{res.Error}
		w.WriteHeader(500)
	}
	encoder := json.NewEncoder(w)
	encoder.Encode(res.Result)
	return nil
}


text:
/* Automatically generated code, don't edit ! */

package org.urish.gwtit.titanium.ui;

/**
 * A TableView row object created by the method
 * {@link org.urish.gwtit.titanium.ui.createTableViewRow}.
 * <p>
 * Notes: Make sure you set the tableClass on each row instance if using more
 * than one type of row layout. You can use the same value for each instance of
 * a row where the layout is the same - even if the value of the elements inside
 * the row have different values. For example, if the text is the only thing
 * different between two cells but the layout is the same, both row instances
 * should have the same value for tableClass.
 *
 * You can listen for table row events on all rows by adding an event listener
 * to the table view instance. Events automatically propagate to parent views.
 *
 * @since 0.9
 */
public class TableViewRow extends org.urish.gwtit.titanium.ui.View {
	protected TableViewRow() {
	}

	/**
	 * @return The class name of the table. each table view cell must have a
	 *         unique class name if the cell layout is different. however, use
	 *         the same name for rows that have the same structural layout (even
	 *         if the content is different) to provide maximum rendering
	 *         performance.
	 */
	public final native String getClassName()
	/*-{
		return this.className;
	}-*/;

	public final native void setClassName(String value)
	/*-{
		this.className = value;
	}-*/;

	/**
	 * @return Default color of the row when not selected
	 */
	public final native String getColor()
	/*-{
		return this.color;
	}-*/;

	public final native void setColor(String value)
	/*-{
		this.color = value;
	}-*/;

	/**
	 * @return The text displayed on the red delete button when swiping the row
	 *         in edit mode
	 */
	public final native String getDeleteButtonTitle()
	/*-{
		return this.deleteButtonTitle;
	}-*/;

	public final native void setDeleteButtonTitle(String value)
	/*-{
		this.deleteButtonTitle = value;
	}-*/;

	/**
	 * @return Whether or not the row can be deleted
	 * @platforms iphone, ipad
	 */
	public final native boolean getEditable()
	/*-{
		return this.editable;
	}-*/;

	public final native void setEditable(boolean value)
	/*-{
		this.editable = value;
	}-*/;

	/**
	 * @return Render a system provided check mark in the right image area of
	 *         the row cell
	 */
	public final native boolean getHasCheck()
	/*-{
		return this.hasCheck;
	}-*/;

	public final native void setHasCheck(boolean value)
	/*-{
		this.hasCheck = value;
	}-*/;

	/**
	 * @return Render a system provided right arrow in the right image area of
	 *         the row cell
	 */
	public final native boolean getHasChild()
	/*-{
		return this.hasChild;
	}-*/;

	public final native void setHasChild(boolean value)
	/*-{
		this.hasChild = value;
	}-*/;

	/**
	 * @return Render a system provided blue indicator icon in the right image
	 *         area of the row cell
	 */
	public final native boolean getHasDetail()
	/*-{
		return this.hasDetail;
	}-*/;

	public final native void setHasDetail(boolean value)
	/*-{
		this.hasDetail = value;
	}-*/;

	/**
	 * @return If set, displays the given string above the cell as a group
	 *         header
	 */
	public final native String getHeader()
	/*-{
		return this.header;
	}-*/;

	public final native void setHeader(String value)
	/*-{
		this.header = value;
	}-*/;

	/**
	 * @return The indention level for the cell (defaults to 0)
	 */
	public final native int getIndentionLevel()
	/*-{
		return this.indentionLevel;
	}-*/;

	public final native void setIndentionLevel(int value)
	/*-{
		this.indentionLevel = value;
	}-*/;

	/**
	 * @return Image url to render in the left image area of the row cell
	 */
	public final native String getLeftImage()
	/*-{
		return this.leftImage;
	}-*/;

	public final native void setLeftImage(String value)
	/*-{
		this.leftImage = value;
	}-*/;

	/**
	 * @return Image url to render in the right image area of the row cell
	 */
	public final native String getRightImage()
	/*-{
		return this.rightImage;
	}-*/;

	public final native void setRightImage(String value)
	/*-{
		this.rightImage = value;
	}-*/;

	/**
	 * @return The background color to render when the row cell is selected
	 */
	public final native String getSelectedBackgroundColor()
	/*-{
		return this.selectedBackgroundColor;
	}-*/;

	public final native void setSelectedBackgroundColor(String value)
	/*-{
		this.selectedBackgroundColor = value;
	}-*/;

	/**
	 * @return The background image to render when the row cell is selected
	 */
	public final native String getSelectedBackgroundImage()
	/*-{
		return this.selectedBackgroundImage;
	}-*/;

	public final native void setSelectedBackgroundImage(String value)
	/*-{
		this.selectedBackgroundImage = value;
	}-*/;

	/**
	 * @return Color of the row during selection
	 */
	public final native String getSelectedColor()
	/*-{
		return this.selectedColor;
	}-*/;

	public final native void setSelectedColor(String value)
	/*-{
		this.selectedColor = value;
	}-*/;

	/**
	 * @return A selection style constant to control the selection color. For
	 *         iPhone, use the constants from
	 *         Titanium.UI.iPhone.TableViewCellSelectionStyle
	 */
	public final native int getSelectionStyle()
	/*-{
		return this.selectionStyle;
	}-*/;

	public final native void setSelectionStyle(int value)
	/*-{
		this.selectionStyle = value;
	}-*/;

	/**
	 * @return The title cell value. do not specify if using views as children
	 *         of the row
	 */
	public final native String getTitle()
	/*-{
		return this.title;
	}-*/;

	public final native void setTitle(String value)
	/*-{
		this.title = value;
	}-*/;

}