text:
<?php

namespace Cradle\Handlebars;

use PHPUnit_Framework_TestCase;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2016-07-27 at 02:11:00.
 */
class Cradle_Handlebars_HandlebarsException_Test extends PHPUnit_Framework_TestCase
{
    /**
     * @var HandlebarsException
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new HandlebarsException;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers Cradle\Handlebars\HandlebarsException::forMissingClosing
     */
    public function testForMissingClosing()
    {
		$actual = null;
		$open = [
			[
				'value' => 'foo',
				'line' => 1
			],
			[
				'value' => 'bar',
				'line' => 2
			]
		];

        try {
			throw HandlebarsException::forMissingClosing($open);
		} catch(HandlebarsException $e) {
			$actual = $e->getMessage();
		}

		$expected = 'Missing closing tags for: "foo" on line 1 AND "bar" on line 2';

		$this->assertEquals($expected, $actual);
    }

    /**
     * @covers Cradle\Handlebars\HandlebarsException::forUnknownEnd
     */
    public function testForUnknownEnd()
    {
		$actual = null;
        try {
			throw HandlebarsException::forUnknownEnd('foo', 12);
		} catch(HandlebarsException $e) {
			$actual = $e->getMessage();
		}

		$expected = 'Unknown close tag: "foo" on line 12';

		$this->assertEquals($expected, $actual);
    }

    /**
     * @covers Cradle\Handlebars\HandlebarsException::forCompileError
     */
    public function testForCompileError()
    {
        $actual = null;
		$code = "Line 1\nLine 2\nLine 3\nLine 4\n";
		$error = [
			'line' => 2,
			'message' => 'foobar'
		];

        try {
			throw HandlebarsException::forCompileError($error, $code, 1);
		} catch(HandlebarsException $e) {
			$actual = $e->getMessage();
		}

		$expected = "foobar on line 2 \n```\n2: Line 2\n3: Line 3\n```\n";

		$this->assertEquals($expected, $actual);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package vsb.fou.kladd.diverse;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public class VsbDataA implements Comparable<VsbDataA>, Cloneable {

    private String s;
    private int k;

    @Override
    public VsbDataA clone() {
        try {
            return (VsbDataA) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException("Skal ikke skje!!!", e);
        }
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    public String toStringX() {

        ToStringBuilder toStringBuilder = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);
        toStringBuilder.append("s", s);
        toStringBuilder.append("k", k);
        return toStringBuilder.toString();
    }

    @Override
    public boolean equals(Object annen) {
        return EqualsBuilder.reflectionEquals(this, annen);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    public int compareTo(VsbDataA that) {
        return CompareToBuilder.reflectionCompare(this, that);
    }

    public void setS(String a) {
        this.s = a;
    }

    public String getS() {
        return s;
    }

    public void setK(int k) {
        this.k = k;
    }

    public int getK() {
        return k;
    }

}


text:
  describe('credstore suite', function(){

	  it('should be array', function(){
        //make sure there is no credentials for testplatform and test@test.com
		  var x = [2];
		  expect(x).to.exist;
		  expect(x).to.have.length(1);
      });

      it('should read existing creds', function(){
    	  var creds = {
			  username: 'test@test.com',
			  password: 'test123'
		  };

    	  expect(creds).to.exist;
    	  expect(creds).to.have.ownProperty('username');
    	  expect(creds).to.have.ownProperty('password');
    	  expect(creds.username).to.equal('test@test.com');
    	  expect(creds.password).to.equal('test123');
      });

      it('should be null', function(){

    	  var x = null;
    	  expect(x).to.be.a('null');
      });

  });


text:
'use strict';

angular
    .module('hawk')
    /* Setup Layout Part - Header */
    .controller('HeaderController', ['$scope', '$rootScope', '$state', 'profileService', 'loginService', function ($scope, $rootScope, $state, profileService, loginService) {
        $scope.$on('$includeContentLoaded', function () {
            Layout.initHeader(); // init header
        });

        $rootScope.logout = function () {
            loginService.logout();
        };

        $scope.myProfile = 'My profile';
  }]);


text:
This module is still very much a work in progress.

## Developer Notes

WHMCS Documentation: http://docs.whmcs.com/Registrar_Module_Developer_Docs

### Logging

http://docs.whmcs.com/Provisioning_Module_Developer_Docs#Module_Logging


text:
package describe

import (
	"fmt"
	"io"
	"sort"
	"strconv"
	"strings"
	"text/tabwriter"

	kapi "k8s.io/kubernetes/pkg/api"
	kapierrors "k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/apis/extensions"
	kclient "k8s.io/kubernetes/pkg/client/unversioned"
	utilerrors "k8s.io/kubernetes/pkg/util/errors"
	"k8s.io/kubernetes/pkg/util/sets"

	osgraph "github.com/openshift/origin/pkg/api/graph"
	"github.com/openshift/origin/pkg/api/graph/graphview"
	kubeedges "github.com/openshift/origin/pkg/api/kubegraph"
	kubeanalysis "github.com/openshift/origin/pkg/api/kubegraph/analysis"
	kubegraph "github.com/openshift/origin/pkg/api/kubegraph/nodes"
	buildapi "github.com/openshift/origin/pkg/build/api"
	buildedges "github.com/openshift/origin/pkg/build/graph"
	buildanalysis "github.com/openshift/origin/pkg/build/graph/analysis"
	buildgraph "github.com/openshift/origin/pkg/build/graph/nodes"
	"github.com/openshift/origin/pkg/client"
	deployapi "github.com/openshift/origin/pkg/deploy/api"
	deployedges "github.com/openshift/origin/pkg/deploy/graph"
	deployanalysis "github.com/openshift/origin/pkg/deploy/graph/analysis"
	deploygraph "github.com/openshift/origin/pkg/deploy/graph/nodes"
	deployutil "github.com/openshift/origin/pkg/deploy/util"
	imageapi "github.com/openshift/origin/pkg/image/api"
	imageedges "github.com/openshift/origin/pkg/image/graph"
	imagegraph "github.com/openshift/origin/pkg/image/graph/nodes"
	projectapi "github.com/openshift/origin/pkg/project/api"
	routeapi "github.com/openshift/origin/pkg/route/api"
	routeedges "github.com/openshift/origin/pkg/route/graph"
	routeanalysis "github.com/openshift/origin/pkg/route/graph/analysis"
	routegraph "github.com/openshift/origin/pkg/route/graph/nodes"
	"github.com/openshift/origin/pkg/util/errors"
	"github.com/openshift/origin/pkg/util/parallel"
)

const ForbiddenListWarning = "Forbidden"

// ProjectStatusDescriber generates extended information about a Project
type ProjectStatusDescriber struct {
	K       kclient.Interface
	C       client.Interface
	Server  string
	Suggest bool

	LogsCommandName             string
	SecurityPolicyCommandFormat string
	SetProbeCommandName         string
}

func (d *ProjectStatusDescriber) MakeGraph(namespace string) (osgraph.Graph, sets.String, error) {
	g := osgraph.New()

	loaders := []GraphLoader{
		&serviceLoader{namespace: namespace, lister: d.K},
		&serviceAccountLoader{namespace: namespace, lister: d.K},
		&secretLoader{namespace: namespace, lister: d.K},
		&rcLoader{namespace: namespace, lister: d.K},
		&podLoader{namespace: namespace, lister: d.K},
		&horizontalPodAutoscalerLoader{namespace: namespace, lister: d.K.Extensions()},
		// TODO check swagger for feature enablement and selectively add bcLoader and buildLoader
		// then remove errors.TolerateNotFoundError method.
		&bcLoader{namespace: namespace, lister: d.C},
		&buildLoader{namespace: namespace, lister: d.C},
		&isLoader{namespace: namespace, lister: d.C},
		&dcLoader{namespace: namespace, lister: d.C},
		&routeLoader{namespace: namespace, lister: d.C},
	}
	loadingFuncs := []func() error{}
	for _, loader := range loaders {
		loadingFuncs = append(loadingFuncs, loader.Load)
	}

	forbiddenResources := sets.String{}
	if errs := parallel.Run(loadingFuncs...); len(errs) > 0 {
		actualErrors := []error{}
		for _, err := range errs {
			if kapierrors.IsForbidden(err) {
				forbiddenErr := err.(*kapierrors.StatusError)
				if (forbiddenErr.Status().Details != nil) && (len(forbiddenErr.Status().Details.Kind) > 0) {
					forbiddenResources.Insert(forbiddenErr.Status().Details.Kind)
				}
				continue
			}
			actualErrors = append(actualErrors, err)
		}

		if len(actualErrors) > 0 {
			return g, forbiddenResources, utilerrors.NewAggregate(actualErrors)
		}
	}

	for _, loader := range loaders {
		loader.AddToGraph(g)
	}

	kubeedges.AddAllExposedPodTemplateSpecEdges(g)
	kubeedges.AddAllExposedPodEdges(g)
	kubeedges.AddAllManagedByRCPodEdges(g)
	kubeedges.AddAllRequestedServiceAccountEdges(g)
	kubeedges.AddAllMountableSecretEdges(g)
	kubeedges.AddAllMountedSecretEdges(g)
	kubeedges.AddHPAScaleRefEdges(g)
	buildedges.AddAllInputOutputEdges(g)
	buildedges.AddAllBuildEdges(g)
	deployedges.AddAllTriggerEdges(g)
	deployedges.AddAllDeploymentEdges(g)
	imageedges.AddAllImageStreamRefEdges(g)
	imageedges.AddAllImageStreamImageRefEdges(g)
	routeedges.AddAllRouteEdges(g)

	return g, forbiddenResources, nil
}

// Describe returns the description of a project
func (d *ProjectStatusDescriber) Describe(namespace, name string) (string, error) {
	var f formatter = namespacedFormatter{}

	g, forbiddenResources, err := d.MakeGraph(namespace)
	if err != nil {
		return "", err
	}

	allNamespaces := namespace == kapi.NamespaceAll
	var project *projectapi.Project
	if !allNamespaces {
		p, err := d.C.Projects().Get(namespace)
		if err != nil {
			return "", err
		}
		project = p
		f = namespacedFormatter{currentNamespace: namespace}
	}

	coveredNodes := graphview.IntSet{}

	services, coveredByServices := graphview.AllServiceGroups(g, coveredNodes)
	coveredNodes.Insert(coveredByServices.List()...)

	standaloneDCs, coveredByDCs := graphview.AllDeploymentConfigPipelines(g, coveredNodes)
	coveredNodes.Insert(coveredByDCs.List()...)

	standaloneRCs, coveredByRCs := graphview.AllReplicationControllers(g, coveredNodes)
	coveredNodes.Insert(coveredByRCs.List()...)

	standaloneImages, coveredByImages := graphview.AllImagePipelinesFromBuildConfig(g, coveredNodes)
	coveredNodes.Insert(coveredByImages.List()...)

	return tabbedString(func(out *tabwriter.Writer) error {
		indent := "  "
		if allNamespaces {
			fmt.Fprintf(out, describeAllProjectsOnServer(f, d.Server))
		} else {
			fmt.Fprintf(out, describeProjectAndServer(f, project, d.Server))
		}

		for _, service := range services {
			if !service.Service.Found() {
				continue
			}
			local := namespacedFormatter{currentNamespace: service.Service.Namespace}

			var exposes []string
			for _, routeNode := range service.ExposingRoutes {
				exposes = append(exposes, describeRouteInServiceGroup(local, routeNode)...)
			}
			sort.Sort(exposedRoutes(exposes))

			fmt.Fprintln(out)
			printLines(out, "", 0, describeServiceInServiceGroup(f, service, exposes...)...)

			for _, dcPipeline := range service.DeploymentConfigPipelines {
				printLines(out, indent, 1, describeDeploymentInServiceGroup(local, dcPipeline)...)
			}

		rcNode:
			for _, rcNode := range service.FulfillingRCs {
				for _, coveredDC := range service.FulfillingDCs {
					if deployedges.BelongsToDeploymentConfig(coveredDC.DeploymentConfig, rcNode.ReplicationController) {
						continue rcNode
					}
				}
				printLines(out, indent, 1, describeRCInServiceGroup(local, rcNode)...)
			}

		pod:
			for _, podNode := range service.FulfillingPods {
				// skip pods that have been displayed in a roll-up of RCs and DCs (by implicit usage of RCs)
				for _, coveredRC := range service.FulfillingRCs {
					if g.Edge(podNode, coveredRC) != nil {
						continue pod
					}
				}
				printLines(out, indent, 1, describePodInServiceGroup(local, podNode)...)
			}
		}

		for _, standaloneDC := range standaloneDCs {
			fmt.Fprintln(out)
			printLines(out, indent, 0, describeDeploymentInServiceGroup(f, standaloneDC)...)
		}

		for _, standaloneImage := range standaloneImages {
			fmt.Fprintln(out)
			lines := describeStandaloneBuildGroup(f, standaloneImage, namespace)
			lines = append(lines, describeAdditionalBuildDetail(standaloneImage.Build, standaloneImage.LastSuccessfulBuild, standaloneImage.LastUnsuccessfulBuild, standaloneImage.ActiveBuilds, standaloneImage.DestinationResolved, true)...)
			printLines(out, indent, 0, lines...)
		}

		for _, standaloneRC := range standaloneRCs {
			fmt.Fprintln(out)
			printLines(out, indent, 0, describeRCInServiceGroup(f, standaloneRC.RC)...)
		}

		allMarkers := osgraph.Markers{}
		allMarkers = append(allMarkers, createForbiddenMarkers(forbiddenResources)...)
		for _, scanner := range getMarkerScanners(d.LogsCommandName, d.SecurityPolicyCommandFormat, d.SetProbeCommandName) {
			allMarkers = append(allMarkers, scanner(g, f)...)
		}

		// TODO: Provide an option to chase these hidden markers.
		allMarkers = allMarkers.FilterByNamespace(namespace)

		fmt.Fprintln(out)

		sort.Stable(osgraph.ByKey(allMarkers))
		sort.Stable(osgraph.ByNodeID(allMarkers))

		errorMarkers := allMarkers.BySeverity(osgraph.ErrorSeverity)
		errorSuggestions := 0
		if len(errorMarkers) > 0 {
			fmt.Fprintln(out, "Errors:")
			for _, marker := range errorMarkers {
				fmt.Fprintln(out, indent+"* "+marker.Message)
				if len(marker.Suggestion) > 0 {
					errorSuggestions++
					if d.Suggest {
						switch s := marker.Suggestion.String(); {
						case strings.Contains(s, "\n"):
							fmt.Fprintln(out)
							for _, line := range strings.Split(s, "\n") {
								fmt.Fprintln(out, indent+"  "+line)
							}
						case len(s) > 0:
							fmt.Fprintln(out, indent+"  try: "+s)
						}
					}
				}
			}
		}

		warningMarkers := allMarkers.BySeverity(osgraph.WarningSeverity)
		if len(warningMarkers) > 0 {
			if d.Suggest {
				fmt.Fprintln(out, "Warnings:")
			}
			for _, marker := range warningMarkers {
				if d.Suggest {
					fmt.Fprintln(out, indent+"* "+marker.Message)
					switch s := marker.Suggestion.String(); {
					case strings.Contains(s, "\n"):
						fmt.Fprintln(out)
						for _, line := range strings.Split(s, "\n") {
							fmt.Fprintln(out, indent+"  "+line)
						}
					case len(s) > 0:
						fmt.Fprintln(out, indent+"  try: "+s)
					}
				}
			}
		}

		// We print errors by default and warnings if -v is used. If we get none,
		// this would be an extra new line.
		if len(errorMarkers) != 0 || (d.Suggest && len(warningMarkers) != 0) {
			fmt.Fprintln(out)
		}

		errors, warnings := "", ""
		if len(errorMarkers) == 1 {
			errors = "1 error"
		} else if len(errorMarkers) > 1 {
			errors = fmt.Sprintf("%d errors", len(errorMarkers))
		}
		if len(warningMarkers) == 1 {
			warnings = "1 warning"
		} else if len(warningMarkers) > 1 {
			warnings = fmt.Sprintf("%d warnings", len(warningMarkers))
		}

		switch {
		case !d.Suggest && len(errorMarkers) > 0 && len(warningMarkers) > 0:
			fmt.Fprintf(out, "%s and %s identified, use 'oc status -v' to see details.\n", errors, warnings)

		case !d.Suggest && len(errorMarkers) > 0 && errorSuggestions > 0:
			fmt.Fprintf(out, "%s identified, use 'oc status -v' to see details.\n", errors)

		case !d.Suggest && len(warningMarkers) > 0:
			fmt.Fprintf(out, "%s identified, use 'oc status -v' to see details.\n", warnings)

		case (len(services) == 0) && (len(standaloneDCs) == 0) && (len(standaloneImages) == 0):
			fmt.Fprintln(out, "You have no services, deployment configs, or build configs.")
			fmt.Fprintln(out, "Run 'oc new-app' to create an application.")

		default:
			fmt.Fprintln(out, "View details with 'oc describe <resource>/<name>' or list everything with 'oc get all'.")
		}

		return nil
	})
}

func createForbiddenMarkers(forbiddenResources sets.String) []osgraph.Marker {
	markers := []osgraph.Marker{}
	for forbiddenResource := range forbiddenResources {
		markers = append(markers, osgraph.Marker{
			Severity: osgraph.WarningSeverity,
			Key:      ForbiddenListWarning,
			Message:  fmt.Sprintf("Unable to list %s resources.  Not all status relationships can be established.", forbiddenResource),
		})
	}
	return markers
}

func getMarkerScanners(logsCommandName, securityPolicyCommandFormat, setProbeCommandName string) []osgraph.MarkerScanner {
	return []osgraph.MarkerScanner{
		func(g osgraph.Graph, f osgraph.Namer) []osgraph.Marker {
			return kubeanalysis.FindRestartingPods(g, f, logsCommandName, securityPolicyCommandFormat)
		},
		kubeanalysis.FindDuelingReplicationControllers,
		kubeanalysis.FindMissingSecrets,
		kubeanalysis.FindHPASpecsMissingCPUTargets,
		kubeanalysis.FindHPASpecsMissingScaleRefs,
		kubeanalysis.FindOverlappingHPAs,
		buildanalysis.FindUnpushableBuildConfigs,
		buildanalysis.FindCircularBuilds,
		buildanalysis.FindPendingTags,
		deployanalysis.FindDeploymentConfigTriggerErrors,
		buildanalysis.FindMissingInputImageStreams,
		func(g osgraph.Graph, f osgraph.Namer) []osgraph.Marker {
			return deployanalysis.FindDeploymentConfigReadinessWarnings(g, f, setProbeCommandName)
		},
		routeanalysis.FindPortMappingIssues,
		routeanalysis.FindMissingTLSTerminationType,
		routeanalysis.FindPathBasedPassthroughRoutes,
		routeanalysis.FindRouteAdmissionFailures,
		routeanalysis.FindMissingRouter,
		// We disable this feature by default and we don't have a capability detection for this sort of thing.  Disable this check for now.
		// kubeanalysis.FindUnmountableSecrets,
	}
}

func printLines(out io.Writer, indent string, depth int, lines ...string) {
	for i, s := range lines {
		fmt.Fprintf(out, strings.Repeat(indent, depth))
		if i != 0 {
			fmt.Fprint(out, indent)
		}
		fmt.Fprintln(out, s)
	}
}

func indentLines(indent string, lines ...string) []string {
	ret := make([]string, 0, len(lines))
	for _, line := range lines {
		ret = append(ret, indent+line)
	}

	return ret
}

type formatter interface {
	ResourceName(obj interface{}) string
}

func namespaceNameWithType(resource, name, namespace, defaultNamespace string, noNamespace bool) string {
	if noNamespace || namespace == defaultNamespace || len(namespace) == 0 {
		return resource + "/" + name
	}
	return resource + "/" + name + "[" + namespace + "]"
}

var namespaced = namespacedFormatter{}

type namespacedFormatter struct {
	hideNamespace    bool
	currentNamespace string
}

func (f namespacedFormatter) ResourceName(obj interface{}) string {
	switch t := obj.(type) {

	case *kubegraph.PodNode:
		return namespaceNameWithType("pod", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
	case *kubegraph.ServiceNode:
		return namespaceNameWithType("svc", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
	case *kubegraph.SecretNode:
		return namespaceNameWithType("secret", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
	case *kubegraph.ServiceAccountNode:
		return namespaceNameWithType("sa", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
	case *kubegraph.ReplicationControllerNode:
		return namespaceNameWithType("rc", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
	case *kubegraph.HorizontalPodAutoscalerNode:
		return namespaceNameWithType("hpa", t.HorizontalPodAutoscaler.Name, t.HorizontalPodAutoscaler.Namespace, f.currentNamespace, f.hideNamespace)

	case *imagegraph.ImageStreamNode:
		return namespaceNameWithType("is", t.ImageStream.Name, t.ImageStream.Namespace, f.currentNamespace, f.hideNamespace)
	case *imagegraph.ImageStreamTagNode:
		return namespaceNameWithType("istag", t.ImageStreamTag.Name, t.ImageStreamTag.Namespace, f.currentNamespace, f.hideNamespace)
	case *imagegraph.ImageStreamImageNode:
		return namespaceNameWithType("isi", t.ImageStreamImage.Name, t.ImageStreamImage.Namespace, f.currentNamespace, f.hideNamespace)
	case *imagegraph.ImageNode:
		return namespaceNameWithType("image", t.Image.Name, t.Image.Namespace, f.currentNamespace, f.hideNamespace)
	case *buildgraph.BuildConfigNode:
		return namespaceNameWithType("bc", t.BuildConfig.Name, t.BuildConfig.Namespace, f.currentNamespace, f.hideNamespace)
	case *buildgraph.BuildNode:
		return namespaceNameWithType("build", t.Build.Name, t.Build.Namespace, f.currentNamespace, f.hideNamespace)

	case *deploygraph.DeploymentConfigNode:
		return namespaceNameWithType("dc", t.DeploymentConfig.Name, t.DeploymentConfig.Namespace, f.currentNamespace, f.hideNamespace)

	case *routegraph.RouteNode:
		return namespaceNameWithType("route", t.Route.Name, t.Route.Namespace, f.currentNamespace, f.hideNamespace)

	default:
		return fmt.Sprintf("<unrecognized object: %#v>", obj)
	}
}

func describeProjectAndServer(f formatter, project *projectapi.Project, server string) string {
	if len(server) == 0 {
		return fmt.Sprintf("In project %s on server %s\n", projectapi.DisplayNameAndNameForProject(project), server)
	}
	return fmt.Sprintf("In project %s on server %s\n", projectapi.DisplayNameAndNameForProject(project), server)

}

func describeAllProjectsOnServer(f formatter, server string) string {
	if len(server) == 0 {
		return "Showing all projects\n"
	}
	return fmt.Sprintf("Showing all projects on server %s\n", server)
}

func describeDeploymentInServiceGroup(f formatter, deploy graphview.DeploymentConfigPipeline) []string {
	local := namespacedFormatter{currentNamespace: deploy.Deployment.Namespace}

	includeLastPass := deploy.ActiveDeployment == nil
	if len(deploy.Images) == 1 {
		format := "%s deploys %s %s"
		if deploy.Deployment.Spec.Test {
			format = "%s test deploys %s %s"
		}
		lines := []string{fmt.Sprintf(format, f.ResourceName(deploy.Deployment), describeImageInPipeline(local, deploy.Images[0], deploy.Deployment.Namespace), describeDeploymentConfigTrigger(deploy.Deployment.DeploymentConfig))}
		if len(lines[0]) > 120 && strings.Contains(lines[0], " <- ") {
			segments := strings.SplitN(lines[0], " <- ", 2)
			lines[0] = segments[0] + " <-"
			lines = append(lines, segments[1])
		}
		lines = append(lines, indentLines("  ", describeAdditionalBuildDetail(deploy.Images[0].Build, deploy.Images[0].LastSuccessfulBuild, deploy.Images[0].LastUnsuccessfulBuild, deploy.Images[0].ActiveBuilds, deploy.Images[0].DestinationResolved, includeLastPass)...)...)
		lines = append(lines, describeDeployments(local, deploy.Deployment, deploy.ActiveDeployment, deploy.InactiveDeployments, 3)...)
		return lines
	}

	format := "%s deploys %s"
	if deploy.Deployment.Spec.Test {
		format = "%s test deploys %s"
	}
	lines := []string{fmt.Sprintf(format, f.ResourceName(deploy.Deployment), describeDeploymentConfigTrigger(deploy.Deployment.DeploymentConfig))}
	for _, image := range deploy.Images {
		lines = append(lines, describeImageInPipeline(local, image, deploy.Deployment.Namespace))
		lines = append(lines, indentLines("  ", describeAdditionalBuildDetail(image.Build, image.LastSuccessfulBuild, image.LastUnsuccessfulBuild, image.ActiveBuilds, image.DestinationResolved, includeLastPass)...)...)
		lines = append(lines, describeDeployments(local, deploy.Deployment, deploy.ActiveDeployment, deploy.InactiveDeployments, 3)...)
	}
	return lines
}

func describeRCInServiceGroup(f formatter, rcNode *kubegraph.ReplicationControllerNode) []string {
	if rcNode.ReplicationController.Spec.Template == nil {
		return []string{}
	}

	images := []string{}
	for _, container := range rcNode.ReplicationController.Spec.Template.Spec.Containers {
		images = append(images, container.Image)
	}

	lines := []string{fmt.Sprintf("%s runs %s", f.ResourceName(rcNode), strings.Join(images, ", "))}
	lines = append(lines, describeRCStatus(rcNode.ReplicationController))

	return lines
}

func describePodInServiceGroup(f formatter, podNode *kubegraph.PodNode) []string {
	images := []string{}
	for _, container := range podNode.Pod.Spec.Containers {
		images = append(images, container.Image)
	}

	lines := []string{fmt.Sprintf("%s runs %s", f.ResourceName(podNode), strings.Join(images, ", "))}
	return lines
}

// exposedRoutes orders strings by their leading prefix (https:// -> http:// other prefixes), then by
// the shortest distance up to the first space (indicating a break), then alphabetically:
//
//   https://test.com
//   https://www.test.com
//   http://t.com
//   other string
//
type exposedRoutes []string

func (e exposedRoutes) Len() int      { return len(e) }
func (e exposedRoutes) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
func (e exposedRoutes) Less(i, j int) bool {
	a, b := e[i], e[j]
	prefixA, prefixB := strings.HasPrefix(a, "https://"), strings.HasPrefix(b, "https://")
	switch {
	case prefixA && !prefixB:
		return true
	case !prefixA && prefixB:
		return false
	case !prefixA && !prefixB:
		prefixA, prefixB = strings.HasPrefix(a, "http://"), strings.HasPrefix(b, "http://")
		switch {
		case prefixA && !prefixB:
			return true
		case !prefixA && prefixB:
			return false
		case !prefixA && !prefixB:
			return a < b
		default:
			a, b = a[7:], b[7:]
		}
	default:
		a, b = a[8:], b[8:]
	}
	lA, lB := strings.Index(a, " "), strings.Index(b, " ")
	if lA == -1 {
		lA = len(a)
	}
	if lB == -1 {
		lB = len(b)
	}
	switch {
	case lA < lB:
		return true
	case lA > lB:
		return false
	default:
		return a < b
	}
}

func extractRouteInfo(route *routeapi.Route) (requested bool, other []string, errors []string) {
	reasons := sets.NewString()
	for _, ingress := range route.Status.Ingress {
		exact := route.Spec.Host == ingress.Host
		switch status, condition := routeapi.IngressConditionStatus(&ingress, routeapi.RouteAdmitted); status {
		case kapi.ConditionFalse:
			reasons.Insert(condition.Reason)
		default:
			if exact {
				requested = true
			} else {
				other = append(other, ingress.Host)
			}
		}
	}
	return requested, other, reasons.List()
}

func describeRouteExposed(host string, route *routeapi.Route, errors bool) string {
	var trailer string
	if errors {
		trailer = " (!)"
	}
	var prefix string
	switch {
	case route.Spec.TLS == nil:
		prefix = fmt.Sprintf("http://%s", host)
	case route.Spec.TLS.Termination == routeapi.TLSTerminationPassthrough:
		prefix = fmt.Sprintf("https://%s (passthrough)", host)
	case route.Spec.TLS.Termination == routeapi.TLSTerminationReencrypt:
		prefix = fmt.Sprintf("https://%s (reencrypt)", host)
	case route.Spec.TLS.Termination != routeapi.TLSTerminationEdge:
		// future proof against other types of TLS termination being added
		prefix = fmt.Sprintf("https://%s", host)
	case route.Spec.TLS.InsecureEdgeTerminationPolicy == routeapi.InsecureEdgeTerminationPolicyRedirect:
		prefix = fmt.Sprintf("https://%s (redirects)", host)
	case route.Spec.TLS.InsecureEdgeTerminationPolicy == routeapi.InsecureEdgeTerminationPolicyAllow:
		prefix = fmt.Sprintf("https://%s (and http)", host)
	default:
		prefix = fmt.Sprintf("https://%s", host)
	}

	if route.Spec.Port != nil && len(route.Spec.Port.TargetPort.String()) > 0 {
		return fmt.Sprintf("%s to pod port %s%s", prefix, route.Spec.Port.TargetPort.String(), trailer)
	}
	return fmt.Sprintf("%s%s", prefix, trailer)
}

func describeRouteInServiceGroup(f formatter, routeNode *routegraph.RouteNode) []string {
	// markers should cover printing information about admission failure
	requested, other, errors := extractRouteInfo(routeNode.Route)
	var lines []string
	if requested {
		lines = append(lines, describeRouteExposed(routeNode.Spec.Host, routeNode.Route, len(errors) > 0))
	}
	for _, s := range other {
		lines = append(lines, describeRouteExposed(s, routeNode.Route, len(errors) > 0))
	}
	if len(lines) == 0 {
		switch {
		case len(errors) >= 1:
			// router rejected the output
			lines = append(lines, fmt.Sprintf("%s not accepted: %s", f.ResourceName(routeNode), errors[0]))
		case len(routeNode.Spec.Host) == 0:
			// no errors or output, likely no router running and no default domain
			lines = append(lines, fmt.Sprintf("%s has no host set", f.ResourceName(routeNode)))
		case len(routeNode.Status.Ingress) == 0:
			// host set, but no ingress, an older legacy router
			lines = append(lines, describeRouteExposed(routeNode.Spec.Host, routeNode.Route, false))
		default:
			// multiple conditions but no host exposed, use the generic legacy output
			lines = append(lines, fmt.Sprintf("exposed as %s by %s", routeNode.Spec.Host, f.ResourceName(routeNode)))
		}
	}
	return lines
}

func describeDeploymentConfigTrigger(dc *deployapi.DeploymentConfig) string {
	if len(dc.Spec.Triggers) == 0 {
		return "(manual)"
	}

	return ""
}

func describeStandaloneBuildGroup(f formatter, pipeline graphview.ImagePipeline, namespace string) []string {
	switch {
	case pipeline.Build != nil:
		lines := []string{describeBuildInPipeline(f, pipeline.Build.BuildConfig, pipeline.BaseImage)}
		if pipeline.Image != nil {
			lines = append(lines, fmt.Sprintf("pushes to %s", describeImageTagInPipeline(f, pipeline.Image, namespace)))
		}
		return lines
	case pipeline.Image != nil:
		return []string{describeImageTagInPipeline(f, pipeline.Image, namespace)}
	default:
		return []string{"<unknown>"}
	}
}

func describeImageInPipeline(f formatter, pipeline graphview.ImagePipeline, namespace string) string {
	switch {
	case pipeline.Image != nil && pipeline.Build != nil:
		return fmt.Sprintf("%s <- %s", describeImageTagInPipeline(f, pipeline.Image, namespace), describeBuildInPipeline(f, pipeline.Build.BuildConfig, pipeline.BaseImage))
	case pipeline.Image != nil:
		return describeImageTagInPipeline(f, pipeline.Image, namespace)
	case pipeline.Build != nil:
		return describeBuildInPipeline(f, pipeline.Build.BuildConfig, pipeline.BaseImage)
	default:
		return "<unknown>"
	}
}

func describeImageTagInPipeline(f formatter, image graphview.ImageTagLocation, namespace string) string {
	switch t := image.(type) {
	case *imagegraph.ImageStreamTagNode:
		if t.ImageStreamTag.Namespace != namespace {
			return image.ImageSpec()
		}
		return f.ResourceName(t)
	default:
		return image.ImageSpec()
	}
}

func describeBuildInPipeline(f formatter, build *buildapi.BuildConfig, baseImage graphview.ImageTagLocation) string {
	switch {
	case build.Spec.Strategy.DockerStrategy != nil:
		// TODO: handle case where no source repo
		source, ok := describeSourceInPipeline(&build.Spec.Source)
		if !ok {
			return fmt.Sprintf("bc/%s unconfigured docker build - no source set", build.Name)
		}
		return fmt.Sprintf("bc/%s docker build of %s", build.Name, source)
	case build.Spec.Strategy.SourceStrategy != nil:
		source, ok := describeSourceInPipeline(&build.Spec.Source)
		if !ok {
			return fmt.Sprintf("bc/%s unconfigured source build", build.Name)
		}
		if baseImage == nil {
			return fmt.Sprintf("bc/%s %s; no image set", build.Name, source)
		}
		return fmt.Sprintf("bc/%s builds %s with %s", build.Name, source, baseImage.ImageSpec())
	case build.Spec.Strategy.CustomStrategy != nil:
		source, ok := describeSourceInPipeline(&build.Spec.Source)
		if !ok {
			return fmt.Sprintf("bc/%s custom build ", build.Name)
		}
		return fmt.Sprintf("bc/%s custom build of %s", build.Name, source)
	default:
		return fmt.Sprintf("bc/%s unrecognized build", build.Name)
	}
}

func describeAdditionalBuildDetail(build *buildgraph.BuildConfigNode, lastSuccessfulBuild *buildgraph.BuildNode, lastUnsuccessfulBuild *buildgraph.BuildNode, activeBuilds []*buildgraph.BuildNode, pushTargetResolved bool, includeSuccess bool) []string {
	if build == nil {
		return nil
	}
	out := []string{}

	passTime := unversioned.Time{}
	if lastSuccessfulBuild != nil {
		passTime = buildTimestamp(lastSuccessfulBuild.Build)
	}
	failTime := unversioned.Time{}
	if lastUnsuccessfulBuild != nil {
		failTime = buildTimestamp(lastUnsuccessfulBuild.Build)
	}

	lastTime := failTime
	if passTime.After(failTime.Time) {
		lastTime = passTime
	}

	// display the last successful build if specifically requested or we're going to display an active build for context
	if lastSuccessfulBuild != nil && (includeSuccess || len(activeBuilds) > 0) {
		out = append(out, describeBuildPhase(lastSuccessfulBuild.Build, &passTime, build.BuildConfig.Name, pushTargetResolved))
	}
	if passTime.Before(failTime) {
		out = append(out, describeBuildPhase(lastUnsuccessfulBuild.Build, &failTime, build.BuildConfig.Name, pushTargetResolved))
	}

	if len(activeBuilds) > 0 {
		activeOut := []string{}
		for i := range activeBuilds {
			activeOut = append(activeOut, describeBuildPhase(activeBuilds[i].Build, nil, build.BuildConfig.Name, pushTargetResolved))
		}

		if buildTimestamp(activeBuilds[0].Build).Before(lastTime) {
			out = append(out, activeOut...)
		} else {
			out = append(activeOut, out...)
		}
	}
	if len(out) == 0 && lastSuccessfulBuild == nil {
		out = append(out, "not built yet")
	}
	return out
}

func describeBuildPhase(build *buildapi.Build, t *unversioned.Time, parentName string, pushTargetResolved bool) string {
	imageStreamFailure := ""
	// if we're using an image stream and that image stream is the internal registry and that registry doesn't exist
	if (build.Spec.Output.To != nil) && !pushTargetResolved {
		imageStreamFailure = " (can't push to image)"
	}

	if t == nil {
		ts := buildTimestamp(build)
		t = &ts
	}
	var time string
	if t.IsZero() {
		time = "<unknown>"
	} else {
		time = strings.ToLower(formatRelativeTime(t.Time))
	}
	buildIdentification := fmt.Sprintf("build/%s", build.Name)
	prefix := parentName + "-"
	if strings.HasPrefix(build.Name, prefix) {
		suffix := build.Name[len(prefix):]

		if buildNumber, err := strconv.Atoi(suffix); err == nil {
			buildIdentification = fmt.Sprintf("build #%d", buildNumber)
		}
	}

	revision := describeSourceRevision(build.Spec.Revision)
	if len(revision) != 0 {
		revision = fmt.Sprintf(" - %s", revision)
	}
	switch build.Status.Phase {
	case buildapi.BuildPhaseComplete:
		return fmt.Sprintf("%s succeeded %s ago%s%s", buildIdentification, time, revision, imageStreamFailure)
	case buildapi.BuildPhaseError:
		return fmt.Sprintf("%s stopped with an error %s ago%s%s", buildIdentification, time, revision, imageStreamFailure)
	case buildapi.BuildPhaseFailed:
		return fmt.Sprintf("%s failed %s ago%s%s", buildIdentification, time, revision, imageStreamFailure)
	default:
		status := strings.ToLower(string(build.Status.Phase))
		return fmt.Sprintf("%s %s for %s%s%s", buildIdentification, status, time, revision, imageStreamFailure)
	}
}

func describeSourceRevision(rev *buildapi.SourceRevision) string {
	if rev == nil {
		return ""
	}
	switch {
	case rev.Git != nil:
		author := describeSourceControlUser(rev.Git.Author)
		if len(author) == 0 {
			author = describeSourceControlUser(rev.Git.Committer)
		}
		if len(author) != 0 {
			author = fmt.Sprintf(" (%s)", author)
		}
		commit := rev.Git.Commit
		if len(commit) > 7 {
			commit = commit[:7]
		}
		return fmt.Sprintf("%s: %s%s", commit, rev.Git.Message, author)
	default:
		return ""
	}
}

func describeSourceControlUser(user buildapi.SourceControlUser) string {
	if len(user.Name) == 0 {
		return user.Email
	}
	if len(user.Email) == 0 {
		return user.Name
	}
	return fmt.Sprintf("%s <%s>", user.Name, user.Email)
}

func buildTimestamp(build *buildapi.Build) unversioned.Time {
	if build == nil {
		return unversioned.Time{}
	}
	if !build.Status.CompletionTimestamp.IsZero() {
		return *build.Status.CompletionTimestamp
	}
	if !build.Status.StartTimestamp.IsZero() {
		return *build.Status.StartTimestamp
	}
	return build.CreationTimestamp
}

func describeSourceInPipeline(source *buildapi.BuildSource) (string, bool) {
	switch {
	case source.Git != nil:
		if len(source.Git.Ref) == 0 {
			return source.Git.URI, true
		}
		return fmt.Sprintf("%s#%s", source.Git.URI, source.Git.Ref), true
	case source.Dockerfile != nil:
		return "Dockerfile", true
	case source.Binary != nil:
		return "uploaded code", true
	case len(source.Images) > 0:
		return "contents in other images", true
	}
	return "", false
}

func describeDeployments(f formatter, dcNode *deploygraph.DeploymentConfigNode, activeDeployment *kubegraph.ReplicationControllerNode, inactiveDeployments []*kubegraph.ReplicationControllerNode, count int) []string {
	if dcNode == nil {
		return nil
	}
	out := []string{}
	deploymentsToPrint := append([]*kubegraph.ReplicationControllerNode{}, inactiveDeployments...)

	if activeDeployment == nil {
		on, auto := describeDeploymentConfigTriggers(dcNode.DeploymentConfig)
		if dcNode.DeploymentConfig.Status.LatestVersion == 0 {
			out = append(out, fmt.Sprintf("deployment #1 waiting %s", on))
		} else if auto {
			out = append(out, fmt.Sprintf("deployment #%d pending %s", dcNode.DeploymentConfig.Status.LatestVersion, on))
		}
		// TODO: detect new image available?
	} else {
		deploymentsToPrint = append([]*kubegraph.ReplicationControllerNode{activeDeployment}, inactiveDeployments...)
	}

	for i, deployment := range deploymentsToPrint {
		out = append(out, describeDeploymentStatus(deployment.ReplicationController, i == 0, dcNode.DeploymentConfig.Spec.Test))

		switch {
		case count == -1:
			if deployutil.DeploymentStatusFor(deployment) == deployapi.DeploymentStatusComplete {
				return out
			}
		default:
			if i+1 >= count {
				return out
			}
		}
	}
	return out
}

func describeDeploymentStatus(deploy *kapi.ReplicationController, first, test bool) string {
	timeAt := strings.ToLower(formatRelativeTime(deploy.CreationTimestamp.Time))
	status := deployutil.DeploymentStatusFor(deploy)
	version := deployutil.DeploymentVersionFor(deploy)
	maybeCancelling := ""
	if deployutil.IsDeploymentCancelled(deploy) && !deployutil.IsTerminatedDeployment(deploy) {
		maybeCancelling = " (cancelling)"
	}

	switch status {
	case deployapi.DeploymentStatusFailed:
		reason := deployutil.DeploymentStatusReasonFor(deploy)
		if len(reason) > 0 {
			reason = fmt.Sprintf(": %s", reason)
		}
		// TODO: encode fail time in the rc
		return fmt.Sprintf("deployment #%d failed %s ago%s%s", version, timeAt, reason, describePodSummaryInline(deploy, false))
	case deployapi.DeploymentStatusComplete:
		// TODO: pod status output
		if test {
			return fmt.Sprintf("test deployment #%d deployed %s ago", version, timeAt)
		}
		return fmt.Sprintf("deployment #%d deployed %s ago%s", version, timeAt, describePodSummaryInline(deploy, first))
	case deployapi.DeploymentStatusRunning:
		format := "deployment #%d running%s for %s%s"
		if test {
			format = "test deployment #%d running%s for %s%s"
		}
		return fmt.Sprintf(format, version, maybeCancelling, timeAt, describePodSummaryInline(deploy, false))
	default:
		return fmt.Sprintf("deployment #%d %s%s %s ago%s", version, strings.ToLower(string(status)), maybeCancelling, timeAt, describePodSummaryInline(deploy, false))
	}
}

func describeRCStatus(rc *kapi.ReplicationController) string {
	timeAt := strings.ToLower(formatRelativeTime(rc.CreationTimestamp.Time))
	return fmt.Sprintf("rc/%s created %s ago%s", rc.Name, timeAt, describePodSummaryInline(rc, false))
}

func describePodSummaryInline(rc *kapi.ReplicationController, includeEmpty bool) string {
	s := describePodSummary(rc, includeEmpty)
	if len(s) == 0 {
		return s
	}
	change := ""
	desired := rc.Spec.Replicas
	switch {
	case desired < rc.Status.Replicas:
		change = fmt.Sprintf(" reducing to %d", desired)
	case desired > rc.Status.Replicas:
		change = fmt.Sprintf(" growing to %d", desired)
	}
	return fmt.Sprintf(" - %s%s", s, change)
}

func describePodSummary(rc *kapi.ReplicationController, includeEmpty bool) string {
	actual, requested := rc.Status.Replicas, rc.Spec.Replicas
	if actual == requested {
		switch {
		case actual == 0:
			if !includeEmpty {
				return ""
			}
			return "0 pods"
		case actual > 1:
			return fmt.Sprintf("%d pods", actual)
		default:
			return "1 pod"
		}
	}
	return fmt.Sprintf("%d/%d pods", actual, requested)
}

func describeDeploymentConfigTriggers(config *deployapi.DeploymentConfig) (string, bool) {
	hasConfig, hasImage := false, false
	for _, t := range config.Spec.Triggers {
		switch t.Type {
		case deployapi.DeploymentTriggerOnConfigChange:
			hasConfig = true
		case deployapi.DeploymentTriggerOnImageChange:
			hasImage = true
		}
	}
	switch {
	case hasConfig && hasImage:
		return "on image or update", true
	case hasConfig:
		return "on update", true
	case hasImage:
		return "on image", true
	default:
		return "for manual", false
	}
}

func describeServiceInServiceGroup(f formatter, svc graphview.ServiceGroup, exposed ...string) []string {
	spec := svc.Service.Spec
	ip := spec.ClusterIP
	port := describeServicePorts(spec)
	switch {
	case len(exposed) > 1:
		return append([]string{fmt.Sprintf("%s (%s)", exposed[0], f.ResourceName(svc.Service))}, exposed[1:]...)
	case len(exposed) == 1:
		return []string{fmt.Sprintf("%s (%s)", exposed[0], f.ResourceName(svc.Service))}
	case spec.Type == kapi.ServiceTypeNodePort:
		return []string{fmt.Sprintf("%s (all nodes)%s", f.ResourceName(svc.Service), port)}
	case ip == "None":
		return []string{fmt.Sprintf("%s (headless)%s", f.ResourceName(svc.Service), port)}
	case len(ip) == 0:
		return []string{fmt.Sprintf("%s <initializing>%s", f.ResourceName(svc.Service), port)}
	default:
		return []string{fmt.Sprintf("%s - %s%s", f.ResourceName(svc.Service), ip, port)}
	}
}

func portOrNodePort(spec kapi.ServiceSpec, port kapi.ServicePort) string {
	switch {
	case spec.Type != kapi.ServiceTypeNodePort:
		return strconv.Itoa(port.Port)
	case port.NodePort == 0:
		return "<initializing>"
	default:
		return strconv.Itoa(port.NodePort)
	}
}

func describeServicePorts(spec kapi.ServiceSpec) string {
	switch len(spec.Ports) {
	case 0:
		return " no ports"

	case 1:
		port := portOrNodePort(spec, spec.Ports[0])
		if spec.Ports[0].TargetPort.String() == "0" || spec.ClusterIP == kapi.ClusterIPNone || port == spec.Ports[0].TargetPort.String() {
			return fmt.Sprintf(":%s", port)
		}
		return fmt.Sprintf(":%s -> %s", port, spec.Ports[0].TargetPort.String())

	default:
		pairs := []string{}
		for _, port := range spec.Ports {
			externalPort := portOrNodePort(spec, port)
			if port.TargetPort.String() == "0" || spec.ClusterIP == kapi.ClusterIPNone {
				pairs = append(pairs, externalPort)
				continue
			}
			if port.Port == int(port.TargetPort.IntVal) {
				pairs = append(pairs, port.TargetPort.String())
			} else {
				pairs = append(pairs, fmt.Sprintf("%s->%s", externalPort, port.TargetPort.String()))
			}
		}
		return " ports " + strings.Join(pairs, ", ")
	}
}

// GraphLoader is a stateful interface that provides methods for building the nodes of a graph
type GraphLoader interface {
	// Load is responsible for gathering and saving the objects this GraphLoader should AddToGraph
	Load() error
	// AddToGraph
	AddToGraph(g osgraph.Graph) error
}

type rcLoader struct {
	namespace string
	lister    kclient.ReplicationControllersNamespacer
	items     []kapi.ReplicationController
}

func (l *rcLoader) Load() error {
	list, err := l.lister.ReplicationControllers(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *rcLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		kubegraph.EnsureReplicationControllerNode(g, &l.items[i])
	}

	return nil
}

type serviceLoader struct {
	namespace string
	lister    kclient.ServicesNamespacer
	items     []kapi.Service
}

func (l *serviceLoader) Load() error {
	list, err := l.lister.Services(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *serviceLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		kubegraph.EnsureServiceNode(g, &l.items[i])
	}

	return nil
}

type podLoader struct {
	namespace string
	lister    kclient.PodsNamespacer
	items     []kapi.Pod
}

func (l *podLoader) Load() error {
	list, err := l.lister.Pods(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *podLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		kubegraph.EnsurePodNode(g, &l.items[i])
	}

	return nil
}

type horizontalPodAutoscalerLoader struct {
	namespace string
	lister    kclient.HorizontalPodAutoscalersNamespacer
	items     []extensions.HorizontalPodAutoscaler
}

func (l *horizontalPodAutoscalerLoader) Load() error {
	list, err := l.lister.HorizontalPodAutoscalers(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *horizontalPodAutoscalerLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		kubegraph.EnsureHorizontalPodAutoscalerNode(g, &l.items[i])
	}

	return nil
}

type serviceAccountLoader struct {
	namespace string
	lister    kclient.ServiceAccountsNamespacer
	items     []kapi.ServiceAccount
}

func (l *serviceAccountLoader) Load() error {
	list, err := l.lister.ServiceAccounts(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *serviceAccountLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		kubegraph.EnsureServiceAccountNode(g, &l.items[i])
	}

	return nil
}

type secretLoader struct {
	namespace string
	lister    kclient.SecretsNamespacer
	items     []kapi.Secret
}

func (l *secretLoader) Load() error {
	list, err := l.lister.Secrets(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *secretLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		kubegraph.EnsureSecretNode(g, &l.items[i])
	}

	return nil
}

type isLoader struct {
	namespace string
	lister    client.ImageStreamsNamespacer
	items     []imageapi.ImageStream
}

func (l *isLoader) Load() error {
	list, err := l.lister.ImageStreams(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *isLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		imagegraph.EnsureImageStreamNode(g, &l.items[i])
		imagegraph.EnsureAllImageStreamTagNodes(g, &l.items[i])
	}

	return nil
}

type dcLoader struct {
	namespace string
	lister    client.DeploymentConfigsNamespacer
	items     []deployapi.DeploymentConfig
}

func (l *dcLoader) Load() error {
	list, err := l.lister.DeploymentConfigs(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *dcLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		deploygraph.EnsureDeploymentConfigNode(g, &l.items[i])
	}

	return nil
}

type bcLoader struct {
	namespace string
	lister    client.BuildConfigsNamespacer
	items     []buildapi.BuildConfig
}

func (l *bcLoader) Load() error {
	list, err := l.lister.BuildConfigs(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return errors.TolerateNotFoundError(err)
	}

	l.items = list.Items
	return nil
}

func (l *bcLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		buildgraph.EnsureBuildConfigNode(g, &l.items[i])
	}

	return nil
}

type buildLoader struct {
	namespace string
	lister    client.BuildsNamespacer
	items     []buildapi.Build
}

func (l *buildLoader) Load() error {
	list, err := l.lister.Builds(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return errors.TolerateNotFoundError(err)
	}

	l.items = list.Items
	return nil
}

func (l *buildLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		buildgraph.EnsureBuildNode(g, &l.items[i])
	}

	return nil
}

type routeLoader struct {
	namespace string
	lister    client.RoutesNamespacer
	items     []routeapi.Route
}

func (l *routeLoader) Load() error {
	list, err := l.lister.Routes(l.namespace).List(kapi.ListOptions{})
	if err != nil {
		return err
	}

	l.items = list.Items
	return nil
}

func (l *routeLoader) AddToGraph(g osgraph.Graph) error {
	for i := range l.items {
		routegraph.EnsureRouteNode(g, &l.items[i])
	}

	return nil
}


text:
"""
traceview.latency

This module contains the objects associated with Latency API resources.

http://dev.appneta.com/docs/api-v2/latency.html

"""

from .resource import Resource

class Server(Resource):
    """ The :class:`Server <Server>` class.

    Get server side latency information.

    """

    def latency_series(self, app, *args, **kwargs):
        """ Get a timeseries line of the applications latency and volume.

        Each timeseries point is a triple of (timestamp, volume, latency).

        :param str app: The app name.
        :param str time_window: (optional) The time window ('hour', 'day', or 'week') to filter on.
        :param str time_end: (optional) The end time for the time window.
        :param str domain: (optional) The domain to filter on.
        :param str url: (optional) The url path to filter on.
        :param str layer: (optional) The application layer to filter on.
        :param str controller: (optional) The controller to filter on.
        :param str action: (optional) The action to filter on.
        :return: timeseries data of the application latency and volume
        :rtype: dict

        Usage::

          >>> import traceview
          >>> tv = traceview.TraceView('API KEY HERE')
          >>> tv.server.latency_series('Default')
          {u'fields': u'timestamp,volume,avg_latency', u'items': [[1399089120.0, 27.0, 226074.07407407407], ...]}

        """
        path = 'latency/{app}/server/series'.format(app=app)
        return self.api.get(path, *args, **kwargs)

    def latency_summary(self, app, *args, **kwargs):
        """ Get a summary of the latency and volume traced.

        :param str app: The app name.
        :param str time_window: (optional) The time window ('hour', 'day', or 'week') to filter on.
        :param str time_end: (optional) The end time for the time window.
        :param str domain: (optional) The domain to filter on.
        :param str url: (optional) The url path to filter on.
        :param str layer: (optional) The application layer to filter on.
        :param str controller: (optional) The controller to filter on.
        :param str action: (optional) The action to filter on.
        :return: timeseries data of the application latency and volume
        :rtype: dict

        Usage::

          >>> import traceview
          >>> tv = traceview.TraceView('API KEY HERE')
          >>> tv.server.latency_summary('Default')
          {u'count': 2402.0, u'average': 271437.13572023314, u'latest': 19530.61224489796}

        """
        path = 'latency/{app}/server/summary'.format(app=app)
        return self.api.get(path, *args, **kwargs)

    def latency_by_layer(self, app, *args, **kwargs):
        """ Get timeseries data grouped by application layers.

        :param str app: The app name.
        :param str time_window: (optional) The time window ('hour', 'day', or 'week') to filter on.
        :param str time_end: (optional) The end time for the time window.
        :param str domain: (optional) The domain to filter on.
        :param str url: (optional) The url path to filter on.
        :param str layer: (optional) The application layer to filter on.
        :param str controller: (optional) The controller to filter on.
        :param str action: (optional) The action to filter on.
        :return: timeseries data of the application latency and volume
        :rtype: dict

        Usage::

          >>> import pprint
          >>> import traceview
          >>> tv = traceview.TraceView('API KEY HERE')
          >>> tv.server.latency_by_layer('Default')
          >>> pprint.pprint(tv.server.latency_by_layer('Default'))
          [{u'layer': u'PHP',
            u'timeseries': {u'fields': u'timestamp,volume,avg_latency',
                            u'items': [[1399089540.0, 10, 0], ...]}},
           ...
          ]

        """
        path = 'latency/{app}/server/by-layer'.format(app=app)
        return self.api.get(path, *args, **kwargs)

class Client(Resource):
    """ The :class:`Client <Client>` class.

    Get client side latency information.

    """

    def latency_series(self, app, *args, **kwargs):
        """ Get a timeseries line of the applications latency and volume.

        Each timeseries point is a triple of (timestamp, volume, latency).

        :param str app: The app name.
        :param str time_window: (optional) The time window ('hour', 'day', or 'week') to filter on.
        :param str time_end: (optional) The end time for the time window.
        :param str domain: (optional) The domain to filter on.
        :param str url: (optional) The url path to filter on.
        :param str layer: (optional) The application layer to filter on.
        :param str controller: (optional) The controller to filter on.
        :param str action: (optional) The action to filter on.
        :param str browser: (optional) The browser to filter on.
        :param str region: (optional) The region to filter on.
        :return: timeseries data of the application latency and volume
        :rtype: dict

        Usage::

          >>> import traceview
          >>> tv = traceview.TraceView('API KEY HERE')
          >>> tv.client.latency_series('Default')
          {u'fields': u'timestamp,volume,avg_latency', u'items': [[1399090230.0, 0, None], ...]}

        """
        path = 'latency/{app}/client/series'.format(app=app)
        return self.api.get(path, *args, **kwargs)

    def latency_summary(self, app, *args, **kwargs):
        """ Get a summary of the latency and volume traced.

        :param str app: The app name.
        :param str time_window: (optional) The time window ('hour', 'day', or 'week') to filter on.
        :param str time_end: (optional) The end time for the time window.
        :param str domain: (optional) The domain to filter on.
        :param str url: (optional) The url path to filter on.
        :param str layer: (optional) The application layer to filter on.
        :param str controller: (optional) The controller to filter on.
        :param str action: (optional) The action to filter on.
        :param str browser: (optional) The browser to filter on.
        :param str region: (optional) The region to filter on.
        :return: timeseries data of the application latency and volume
        :rtype: dict

        Usage::

          >>> import traceview
          >>> tv = traceview.TraceView('API KEY HERE')
          >>> tv.client.latency_summary('Default')
          {u'count': 93.0, u'average': 14503082.720430108, u'latest': None}

        """
        path = 'latency/{app}/client/summary'.format(app=app)
        return self.api.get(path, *args, **kwargs)


text:
package main

import (
	"testing"

	"github.com/moby/buildkit/util/testutil/integration"
	"github.com/stretchr/testify/assert"
)

func testPrune(t *testing.T, sb integration.Sandbox) {
	cmd := sb.Cmd("prune")
	err := cmd.Run()
	assert.NoError(t, err)
}


text:
import argparse
import tornado.web
from zmq.eventloop import ioloop
ioloop.install()

from transport import CryptoTransportLayer
from db_store import Obdb
from market import Market
from ws import WebSocketHandler
import logging
import signal
from threading import Thread
from twisted.internet import reactor
from util import open_default_webbrowser
from network_util import get_random_free_tcp_port
import upnp
import os

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect("/html/index.html")

class OpenBazaarStaticHandler(tornado.web.StaticFileHandler):
    def set_extra_headers(self, path):
        self.set_header("X-Frame-Options", "DENY")
        self.set_header("X-Content-Type-Options", "nosniff")

class MarketApplication(tornado.web.Application):
    def __init__(self, market_ip, market_port, market_id=1,
                 bm_user=None, bm_pass=None, bm_port=None, seed_peers=None,
                 seed_mode=0, dev_mode=False, db_path='db/ob.db', disable_sqlite_crypt=False, disable_ip_update=False):
        if seed_peers is None:
            seed_peers = []

        db = Obdb(db_path, disable_sqlite_crypt)

        self.transport = CryptoTransportLayer(market_ip,
                                              market_port,
                                              market_id,
                                              db,
                                              bm_user,
                                              bm_pass,
                                              bm_port,
                                              seed_mode,
                                              dev_mode,
                                              disable_ip_update)

        self.market = Market(self.transport, db)

        # UNUSED
        # def post_joined():
        #     self.transport.dht._refreshNode()
        #     self.market.republish_contracts()

        peers = seed_peers if seed_mode == 0 else []
        self.transport.join_network(peers)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", OpenBazaarStaticHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market_application=self, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

    def get_transport(self):
        return self.transport

    def setup_upnp_port_mappings(self, http_port, p2p_port):
        upnp.PortMapper.DEBUG = False
        print "Setting up UPnP Port Map Entry..."
        # TODO: Add some setting whether or not to use UPnP
        # if Settings.get(Settings.USE_UPNP_PORT_MAPPINGS):
        self.upnp_mapper = upnp.PortMapper()
        # TODO: Add some setting whether or not to clean all previous port
        # mappings left behind by us
        # if Settings.get(Settings.CLEAN_UPNP_PORT_MAPPINGS_ON_START):
        #    upnp_mapper.cleanMyMappings()

        # for now let's always clean mappings every time.
        self.upnp_mapper.clean_my_mappings(p2p_port)
        # result_http_port_mapping = self.upnp_mapper.add_port_mapping(http_port,
        #                                                             http_port)
        # print ("UPnP HTTP Port Map configuration done (%s -> %s) => %s" %
        #        (str(http_port), str(http_port), str(result_http_port_mapping)))

        result_tcp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port)
        print ("UPnP TCP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_tcp_p2p_mapping)))

        result_udp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port,
                                                                   'UDP')
        print ("UPnP UDP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_udp_p2p_mapping)))

        result = result_tcp_p2p_mapping and result_udp_p2p_mapping
        if not result:
            print "Warning: UPnP was not setup correctly. Try doing a port forward on %s and start the node again with -j" % p2p_port

        return result

    def cleanup_upnp_port_mapping(self):
        try:
            if self.upnp_mapper is not None:
                print "Cleaning UPnP Port Mapping -> ", \
                    self.upnp_mapper.clean_my_mappings(self.transport.port)
        except AttributeError:
            print "[openbazaar] MarketApplication.clean_upnp_port_mapping() failed!"

    def shutdown(self, x=None, y=None):
        print "MarketApplication.shutdown!"
        locallogger = logging.getLogger(
            '[%s] %s' % (self.market.market_id, 'root')
        )
        locallogger.info("Received TERMINATE, exiting...")

        # application.get_transport().broadcast_goodbye()
        self.cleanup_upnp_port_mapping()
        tornado.ioloop.IOLoop.instance().stop()

        self.transport.shutdown()
        os._exit(0)

def start_node(my_market_ip,
               my_market_port,
               http_ip,
               http_port,
               log_file,
               market_id,
               bm_user=None,
               bm_pass=None,
               bm_port=None,
               seed_peers=None,
               seed_mode=0,
               dev_mode=False,
               log_level=None,
               database='db/ob.db',
               disable_upnp=False,
               disable_open_browser=False,
               disable_sqlite_crypt=False,
               disable_ip_update=False):
    if seed_peers is None:
        seed_peers = []

    try:
        logging.basicConfig(
            level=int(log_level),
            format=u'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            filename=log_file
        )
        logging._defaultFormatter = logging.Formatter(u'%(message)s')
        locallogger = logging.getLogger('[%s] %s' % (market_id, 'root'))

        handler = logging.handlers.RotatingFileHandler(
            log_file,
            encoding='utf-8',
            maxBytes=50000000,
            backupCount=0
        )
        locallogger.addHandler(handler)
    except Exception as e:
        print "Could not setup logger, continuing: ", e.message

    application = MarketApplication(my_market_ip,
                                    my_market_port,
                                    market_id,
                                    bm_user,
                                    bm_pass,
                                    bm_port,
                                    seed_peers,
                                    seed_mode,
                                    dev_mode,
                                    database,
                                    disable_sqlite_crypt,
                                    disable_ip_update)

    error = True
    p2p_port = my_market_port

    if http_port == -1:
        http_port = get_random_free_tcp_port(8889, 8988)

    while error:
        try:
            application.listen(http_port, http_ip)
            error = False
        except:
            http_port += 1

    if not disable_upnp:
        application.setup_upnp_port_mappings(http_port, p2p_port)
    else:
        print "Disabling upnp setup"

    locallogger.info("Started OpenBazaar Web App at http://%s:%s" %
                     (http_ip, http_port))

    print "Started OpenBazaar Web App at http://%s:%s" % (http_ip, http_port)
    print "Use ./stop.sh to stop"

    if not disable_open_browser:
        open_default_webbrowser('http://%s:%s' % (http_ip, http_port))

    try:
        signal.signal(signal.SIGTERM, application.shutdown)
    except ValueError:
        # not the main thread
        pass

    if not tornado.ioloop.IOLoop.instance():
        ioloop.install()
    else:
        try:
            tornado.ioloop.IOLoop.instance().start()
        except Exception as e:
            pass

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("my_market_ip")
    parser.add_argument("-p", "--my_market_port",
                        type=int, default=12345)
    # default secure behavior is to keep HTTP port private
    parser.add_argument("-k", "--http_ip", default="127.0.0.1")
    parser.add_argument("-q", "--http_port", type=int, default=-1)
    parser.add_argument("-l", "--log_file",
                        default='logs/production.log')
    parser.add_argument("-u", "--market_id",
                        default=1)
    parser.add_argument("-S", "--seed_peers",
                        nargs='*', default=[])
    parser.add_argument("-s", "--seed_mode",
                        default=0)
    parser.add_argument("-d", "--dev_mode",
                        action='store_true')
    parser.add_argument("--database",
                        default='db/ob.db', help="Database filename")
    parser.add_argument("--bmuser",
                        default='username', help="Bitmessage instance user")
    parser.add_argument("--bmpass",
                        default='password', help="Bitmessage instance pass")
    parser.add_argument("--bmport",
                        default='8442', help="Bitmessage instance RPC port")
    parser.add_argument("--log_level",
                        default=10, help="Numeric value for logging level")
    parser.add_argument("--disable_upnp",
                        action='store_true')
    parser.add_argument("--disable_open_browser",
                        action='store_true',
                        default=False)
    parser.add_argument("--disable_sqlite_crypt",
                        action='store_true',
                        default=False)
    parser.add_argument("--disable-ip-update",
                        action='store_true',
                        default=False)

    args = parser.parse_args()
    start_node(args.my_market_ip,
               args.my_market_port,
               args.http_ip,
               args.http_port,
               args.log_file,
               args.market_id,
               args.bmuser,
               args.bmpass,
               args.bmport,
               args.seed_peers,
               args.seed_mode,
               args.dev_mode,
               args.log_level,
               args.database,
               args.disable_upnp,
               args.disable_open_browser,
               args.disable_sqlite_crypt,
               args.disable_ip_update)

# Run this if executed directly
if __name__ == "__main__":
    main()


text:
//
// This file was sciverse.jaxb.generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.07.28 at 12:10:14 AM BST
//

package org.prismstandard.namespaces.basic._2;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * sciverse.jaxb.generated in the org.prismstandard.namespaces.basic._2 package.
 *
An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    private final static QName _StartingPage_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "startingPage");
    private final static QName _AggregationType_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "aggregationType");
    private final static QName _PublicationName_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "publicationName");
    private final static QName _EndingPage_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "endingPage");
    private final static QName _Issn_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "issn");
    private final static QName _IssueIdentifier_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "issueIdentifier");
    private final static QName _Volume_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "volume");
    private final static QName _Doi_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "doi");
    private final static QName _CoverDate_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "coverDate");
    private final static QName _Copyright_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "copyright");
    private final static QName _Url_QNAME = new QName("http://prismstandard.org/namespaces/basic/2.0/", "url");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.prismstandard.namespaces.basic._2
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link Edition }
     *
     */
    public Edition createEdition() {
        return new Edition();
    }

    /**
     * Create an instance of {@link Number }
     *
     */
    public Number createNumber() {
        return new Number();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "startingPage")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    public JAXBElement<String> createStartingPage(String value) {
        return new JAXBElement<String>(_StartingPage_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "aggregationType")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    public JAXBElement<String> createAggregationType(String value) {
        return new JAXBElement<String>(_AggregationType_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "publicationName")
    public JAXBElement<String> createPublicationName(String value) {
        return new JAXBElement<String>(_PublicationName_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "endingPage")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    public JAXBElement<String> createEndingPage(String value) {
        return new JAXBElement<String>(_EndingPage_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "issn")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    public JAXBElement<String> createIssn(String value) {
        return new JAXBElement<String>(_Issn_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "issueIdentifier")
    public JAXBElement<String> createIssueIdentifier(String value) {
        return new JAXBElement<String>(_IssueIdentifier_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "volume")
    public JAXBElement<String> createVolume(String value) {
        return new JAXBElement<String>(_Volume_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "doi")
    public JAXBElement<String> createDoi(String value) {
        return new JAXBElement<String>(_Doi_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "coverDate")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    public JAXBElement<String> createCoverDate(String value) {
        return new JAXBElement<String>(_CoverDate_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "copyright")
    public JAXBElement<String> createCopyright(String value) {
        return new JAXBElement<String>(_Copyright_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://prismstandard.org/namespaces/basic/2.0/", name = "url")
    public JAXBElement<String> createUrl(String value) {
        return new JAXBElement<String>(_Url_QNAME, String.class, null, value);
    }

}


text:
! Sample solution to the problem posed in Lab 12.
! Version with coarse grain parallelism

program main

    use omp_lib
    use random_util, only: init_random_seed

    implicit none
    integer :: seed, nthreads
    integer, parameter :: ntests = 7
    real (kind=8), allocatable :: x(:)
    real (kind=8) :: sum, count1, count4
    real (kind=8), dimension(ntests)  :: mean,q1,q4
    integer :: i,n,k,kstart,kend,thread_num,points_per_thread

    ! Specify number of threads to use:
    nthreads = 1       ! need this value in serial mode
    !$ nthreads = 2
    !$ call omp_set_num_threads(nthreads)
    !$ print "('Using OpenMP with ',i3,' threads')", nthreads

    print *, "input seed"
    read *, seed

    call init_random_seed(seed)

    print *, "      n          mean        quartile 1    quartile 4"

    points_per_thread = (ntests + nthreads - 1) / nthreads
    print *, "points_per_thread = ",points_per_thread

    !$omp parallel private(k,x,count1,count4,sum,kstart,kend,thread_num,n)

    thread_num = 0     ! needed in serial mode
    !$ thread_num = omp_get_thread_num()    ! unique for each thread

    ! Determine start and end index for the set of points to be
    ! handled by this thread:
    kstart = thread_num * points_per_thread + 1
    kend = min((thread_num+1) * points_per_thread, ntests)

    !$omp critical
    print 201, thread_num, kstart, kend
    !$omp end critical
201 format("Thread ",i2," will take k = ",i6," through k = ",i6)

    do k=kstart,kend
        n = 10**(k+1)
        allocate(x(n))
        call random_number(x)
        sum = 0.d0
        count1 = 0
        count4 = 0
        do i=1,n
            sum = sum + x(i)
            if (x(i) < 0.25) then
                count1 = count1 + 1
                endif
            if (x(i) > 0.75) then
                count4 = count4 + 1
                endif
            enddo
        mean(k) = sum / float(n)
        q1(k) = count1 / float(n)
        q4(k) = count4 / float(n)
        deallocate(x)
        enddo
    !$omp end parallel

    do k=1,ntests
        n = 10**(k+1)
        print 601, n,mean(k),q1(k),q4(k)
 601    format(i10,3f15.8)
        enddo

end program main


text:
package tap.execounting.pages;

import java.util.Date;
import java.util.List;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.annotations.Inject;

import tap.execounting.components.editors.AddContract;
import tap.execounting.dal.CRUDServiceDAO;
import tap.execounting.entities.Client;
import tap.execounting.entities.Contract;
import tap.execounting.security.AuthorizationDispatcher;
import tap.execounting.util.DateUtil;

@Import(stylesheet="context:css/stattable.css")
public class ClientPage {

	@Property
	@Persist
	private Client client;
	@Inject
	private CRUDServiceDAO dao;
	@Inject
	private AuthorizationDispatcher dispatcher;
	private boolean editorActive;
	@Property
	@Persist
	private boolean editorActiveAlways;
	@Component
	private Zone ezone;
	@Persist
	@Property
	private boolean constantEventEditor;

	@InjectComponent
	private AddContract editor;
	@Property
	private Contract contract;
	@Property
	private boolean mode;

	// page events
	void onActivate(int clientId) {
		this.client = dao.find(Client.class, clientId);
	}

	int onPassivate() {
		return client.getId();
	}

	void onPrepare() {
		// out.println("Number of contracts: " + client.getContracts().size());
		client = dao.find(Client.class, client.getId());
		setup(client);
	}

	Object onExperiment(Contract con){
		return this;
	}

	Object onCancel(Contract con){
		return this;
	}

	Object onAddContract() {
		// AUTHORIZATION MOUNT POINT CONTRACT CREATE
		if (dispatcher.canCreateContracts())
			editorActive = true;
		return ezone;
	}

	// setup
	public void setup(Client c) {
		client = c;
		c.getContracts().size();
		editor.setup(c);
	}

	// page properties
	public List<Contract> getContracts() {
		return client.getContracts(false);
	}

	public String getFirstContractDate() {
		if (getContracts().size() == 0)
			return "договоров по данному клиенту нет в базе";
		Date d = getContracts().get(0).getDate();
		for (Contract c : client.getContracts()) {
			if (c.getDate().compareTo(d) < 0)
				d = c.getDate();
		}
		return DateUtil.toString("dd MMM YY", d);
	}

	public String getCurrentTeachersInfo() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < client.getCurrentTeachers().size(); i++) {
			sb.append(client.getCurrentTeachers().get(i).getName());
			if (i < client.getCurrentTeachers().size() - 1)
				sb.append(", ");
		}
		return sb.toString();
	}

	public boolean getEditorActive() {
		return editorActive || editorActiveAlways;
	}

}


text:
package com.qihoo360.replugin.utils.pkg;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.qihoo360.mobilesafe.core.BuildConfig;
import com.qihoo360.replugin.helper.LogRelease;
import com.qihoo360.replugin.model.PluginInfo;

import com.qihoo360.replugin.utils.FileUtils;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author RePlugin Team
 */
public class PackageFilesUtil {
    private static final String TAG = "PackageFilesUtil";

    private static final String TIMESTAMP_EXT = ".timestamp";

    /**
     * 我们的很多文件,都是在 assets 目录里有一份,如果有更新,则在 files 目录里也有一份。原来的做法是把 assets 目录里的 copy
     * 到 files 目录,其实没有必要,这里用时间戳判断一下,哪个最新就直接读哪个
     */
    public static InputStream openLatestInputFile(Context c, String filename) {
        InputStream is = null;

        long timestampOfFile = getFileTimestamp(c, filename);
        long timestampOfAsset = getBundleTimestamp(c, filename);

        if (timestampOfFile >= timestampOfAsset) {
            // files 目录的时间戳更新,那么优先读取 files 目录的文件

            try {
                is = c.openFileInput(filename);

                if (BuildConfig.DEBUG) {
                    Log.i(TAG, "Opening in files directory: " + filename);
                }
            } catch (Exception e) {
                if (BuildConfig.DEBUG) {
                    Log.i(TAG, filename + " in files directory not found, skip.");
                }
            }
        }

        if (is == null) {
            // is == null 表明没能从 files 目录读到文件,那么到 assets 目录去读读看

            try {
                is = c.getAssets().open(filename);
                if (BuildConfig.DEBUG) {
                    Log.i(TAG, "Opening in assets: " + filename);
                }
            } catch (FileNotFoundException e) {
                // 找不到文件?很正常,不做任何处理
                // Ignore
            } catch (IOException e) {
                if (BuildConfig.DEBUG) {
                    Log.w(TAG, filename, e);
                }
            }
        }

        return is;
    }

    /** @see Utils#openLatestInputFile(Context, String) */
    public static long getLatestFileTimestamp(Context c, String filename) {
        long timestampOfFile = getFileTimestamp(c, filename);
        long timestampOfAsset = getBundleTimestamp(c, filename);

        return Math.max(timestampOfFile, timestampOfAsset);
    }

    /**
     * 检查 files 目录下个某个文件是否已经为最新(比 assets 目录下的新)
     *
     * @param c
     * @param filename
     * @return 如果文件比 assets 下的同名文件的时间戳旧,或者文件不存在,则返回 false.
     */
    public static boolean isFileUpdated(Context c, String filename) {
        File file = c.getFileStreamPath(filename);
        if (file == null) {
            return false;
        }
        if (!file.exists()) {
            return false;
        }

        long timestampOfFile = getFileTimestamp(c, filename);
        long timestampOfAsset = getBundleTimestamp(c, filename);

        return (timestampOfAsset <= timestampOfFile);
    }

    /** 读取文件的时间戳 */
    public static long getFileTimestamp(Context c, String filename) {
        FileInputStream fis = null;
        try {
            fis = c.openFileInput(filename + TIMESTAMP_EXT);
        } catch (Exception e) {
            //ignore
        }

        if (fis != null) {
            return getTimestampFromStream(fis);
        } else {
            return 0;
        }
    }

    // 对于打包的文件,都是放在 assets 目录的,时间戳自然也在 assets 目录
    public static long getBundleTimestamp(Context c, String filename) {
        InputStream fis = null;
        try {
            fis = c.getAssets().open(filename + TIMESTAMP_EXT);
        } catch (Exception e) {
            //ignore
        }

        if (fis != null) {
            return getTimestampFromStream(fis);
        } else {
            return 0;
        }
    }

    private static long getTimestampFromStream(InputStream fis) {

        DataInputStream dis = null;
        try {
            dis = new DataInputStream(fis);
            String s = dis.readLine();
            if (!TextUtils.isEmpty(s)) {
                long timeStamp = Long.parseLong(s);
                return timeStamp;
            }
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "", e);
            }
        } finally {
            try {
                if (dis != null) {
                    dis.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (Exception e) {
                if (BuildConfig.DEBUG) {
                    Log.e(TAG, "", e);
                }
            }
        }

        return 0;
    }

    public static boolean isExtractedFromAssetsToFiles(Context c, String filename) {
        File file = c.getFileStreamPath(filename);
        if (file == null || !file.exists()) {
            if (BuildConfig.DEBUG) {
                Log.i(TAG, "Extract no exist file from assets filename = " + filename);
            }
            return true;
        }
        // compare file version for extract
        return compareDataFileVersion(c, filename);
    }

    private static boolean compareDataFileVersion(Context c, String fileName) {
        int assetsVer = -1;
        int fileVer = -1;
        DataInputStream dis = null;
        byte[] magic = new byte[4];
        try {
            dis = new DataInputStream(c.getAssets().open(fileName));
            dis.read(magic);
            if (magic[0] == 'V' && magic[1] == 'D' && magic[2] == 'A' && magic[3] == 'T') {
                dis.readInt();
                dis.readInt();
                assetsVer = dis.readInt();
                if (BuildConfig.DEBUG) {
                    Log.i(TAG, "Get assets version file=" + fileName + " version=" + assetsVer);
                }
            } else {
                return true;
            }
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Get assets version error, file:" + fileName, e);
            }
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (Exception e) {
                    if (BuildConfig.DEBUG) {
                        Log.e(TAG, "close error", e);
                    }
                }
            }
        }
        try {
            dis = new DataInputStream(new FileInputStream(c.getFileStreamPath(fileName)));
            dis.read(magic);
            if (magic[0] == 'V' && magic[1] == 'D' && magic[2] == 'A' && magic[3] == 'T') {
                dis.readInt();
                dis.readInt();
                fileVer = dis.readInt();
                if (BuildConfig.DEBUG) {
                    Log.i(TAG, "Get local version file=" + fileName + " version=" + fileVer);
                }
            } else {
                return true;
            }
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Get file version error, file:" + fileName, e);
            }
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (Exception e) {
                    if (BuildConfig.DEBUG) {
                        Log.e(TAG, "close error", e);
                    }
                }
            }
        }
        if (assetsVer != -1 && fileVer != -1 && assetsVer <= fileVer) {
            if (BuildConfig.DEBUG) {
                Log.i(TAG, "compare file version not extract");
            }
            return false;
        } else {
            if (BuildConfig.DEBUG) {
                Log.i(TAG, "compare file version need extract");
            }
        }
        return true;
    }

    /**
     *  移除插件及其已释放的Dex、Native库等文件
     *
     * @param info 插件信息
     */
    public static void forceDelete(PluginInfo info) {
        if (info == null) {
            return;
        }
        try {
            FileUtils.forceDelete(info.getApkFile());
            FileUtils.forceDelete(info.getDexFile());
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                FileUtils.forceDelete(info.getExtraOdexDir());
            }
            FileUtils.forceDelete(info.getNativeLibsDir());
        } catch (IOException e) {
            if (LogRelease.LOGR) {
                e.printStackTrace();
            }
        }
    }
}


text:
package com.sun.corba.se.spi.ior;

/**
 * @author Ken Cavanaugh
 */
public interface ObjectId extends Writeable
{
    public byte[] getId() ;
}