text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

Provides implementations of the {@link net.jini.jeri.Endpoint} and
{@link net.jini.jeri.ServerEndpoint} abstractions that use TCP sockets
as the underlying communication mechanism.

Requests and responses are framed and multiplexed over TCP connections
using the Jini
extensible remote invocation (Jini ERI) multiplexing protocol.

A {@link net.jini.jeri.tcp.TcpEndpoint} can be used to initiate
requests over a TCP connection.  Each instance contains a host name
string (which may be a name or an IP address) and a TCP port number,
as well as an optional {@link javax.net.SocketFactory} for customizing
the type of {@link java.net.Socket} instances to use.  When initiating
a new request, a new TCP connection is created to the host and port,
using the socket factory if present, if an existing connection is not
already available for use.

A {@link net.jini.jeri.tcp.TcpServerEndpoint} can be used to listen
for and receive incoming requests over a TCP connection.  Each
instance contains a TCP port number to listen on, a host name string
to use in Endpoint instances derived from the instance,
an optional {@link javax.net.ServerSocketFactory} for customizing the
type of {@link java.net.ServerSocket} instances to use, and an
optional {@link javax.net.SocketFactory} to use in derived
Endpoint instances.  When listening for requests, the
port is bound to listen for TCP connections, using the server socket
factory if present.  The {@link
net.jini.jeri.tcp.TcpServerEndpoint#enumerateListenEndpoints
TcpServerEndpoint.enumerateListenEndpoints} method will produce
TcpEndpoint instances with the same host name, port, and
client socket factory for client-side use (for example, to be embedded
in remote proxies).

Jini ERI multiplexing protocol mapping

TcpEndpoint and TcpServerEndpoint map,
respectively, {@link net.jini.jeri.OutboundRequest} and {@link
net.jini.jeri.InboundRequest} instances to distinct sessions of a Jini
ERI multiplexing protocol connection.  For each new request initiated,
a TcpEndpoint starts a new session as the client of a
connection to the remote endpoint.  As the server of an accepted
connection, a TcpServerEndpoint creates a new
InboundRequest to represent each session started by the
remote endpoint.  Request data is transmitted as the data sent for the
corresponding session by the client, and response data is transmitted
as the data sent for the corresponding session by the server.  TCP
connections are reused by a TcpEndpoint when possible.

Constraint support

TcpEndpoint and TcpServerEndpoint support
the transport layer aspects of at least the following constraints:

any {@link net.jini.core.constraint.ConnectionAbsoluteTime}

any {@link net.jini.core.constraint.ConnectionRelativeTime}

a {@link net.jini.core.constraint.ConstraintAlternatives} if at
    least one element is supported

{@link net.jini.core.constraint.Integrity#NO Integrity.NO}

{@link net.jini.core.constraint.Confidentiality#NO Confidentiality.NO}

{@link net.jini.core.constraint.ClientAuthentication#NO
				    ClientAuthentication.NO}

{@link net.jini.core.constraint.ServerAuthentication#NO
				    ServerAuthentication.NO}

{@link net.jini.core.constraint.Delegation#NO Delegation.NO}

any {@link net.jini.core.constraint.ClientMaxPrincipal}

any {@link net.jini.core.constraint.ClientMaxPrincipalType}

any {@link net.jini.core.constraint.ClientMinPrincipal}

any {@link net.jini.core.constraint.ClientMinPrincipalType}

any {@link net.jini.core.constraint.ServerMinPrincipal}

any {@link net.jini.core.constraint.DelegationAbsoluteTime}

any {@link net.jini.core.constraint.DelegationRelativeTime}

(Note that ClientMaxPrincipal,
ClientMaxPrincipalType, ClientMinPrincipal,
ClientMinPrincipalType, ServerMinPrincipal,
DelegationAbsoluteTime, and
DelegationRelativeTime constraints are trivially
supported if ClientAuthentication.YES,
ServerAuthentication.YES, and Delegation.YES
are not supported.)

@since 2.0
@version 2.0

@com.sun.jini.impl

This implementation uses {@link
net.jini.jeri.connection.ConnectionManager} and {@link
net.jini.jeri.connection.ServerConnectionManager} for connection
management.

Logging

This implementation uses the {@link java.util.logging.Logger} named
net.jini.jeri.tcp.client to log information at the
following levels:

  Level  Description

  {@link com.sun.jini.logging.Levels#FAILED FAILED}
      exceptions thrown attempting to initiate a request

  {@link com.sun.jini.logging.Levels#HANDLED HANDLED}
      exceptions caught attempting to connect a socket, set
	  options on a client-side socket, or reuse a connection

  {@link java.util.logging.Level#FINE FINE}
      client-side socket operations (create, connect, reuse, and
	  close)

This implementation uses the {@link java.util.logging.Logger} named
net.jini.jeri.tcp.server to log information at the
following levels:

  Level  Description

  {@link java.util.logging.Level#WARNING WARNING}
      exceptions accepting on a server socket

  {@link com.sun.jini.logging.Levels#HANDLED HANDLED}
      exceptions caught setting options on a server-side socket

  {@link java.util.logging.Level#FINE FINE}
      server-side socket operations (create, accept, and close)

System Properties

This implementation recognizes the following system properties:

com.sun.jini.jeri.tcp.useNIO - This property is
interpreted as a boolean value (see {@link
java.lang.Boolean#getBoolean Boolean.getBoolean}).  If
true, then when not using a socket factory, the
implementation will use {@link java.nio.channels} APIs to create
sockets that have associated selectable channels; specifically:

a TcpEndpoint with no socket factory will create
sockets using {@link java.nio.channels.SocketChannel#open
SocketChannel.open}, and

a TcpServerEndpoint with no server socket factory
will create server sockets using {@link
java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}.

Otherwise, when not using a socket factory, the implementation will
create sockets that do not have channels:

a TcpEndpoint with no socket factory will create
sockets using {@link java.net.Socket#Socket()}, and

a TcpServerEndpoint with no server socket factory
will create server sockets using {@link
java.net.ServerSocket#ServerSocket(int)}.


text:
{% extends "experiments_manager/experiment_detail/experiment_detail.html" %}
{% load django_bootstrap_breadcrumbs %}
{% block title %}View file {{ file_name }}{% endblock %}

{% block breadcrumbs %}
    {{ block.super }}
    {% breadcrumb name "file_detail" %}
{% endblock %}

{% block content %}

File contents of {{ file_name }}

        {{ content_file|safe }}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <string name="dialog_title_simple_alert">確認</string>
    <string name="dialog_button_ok">OK</string>
</resources>


text:
describe('dateValidator', function () {
  var id = 'testContainer';

  beforeEach(function () {
    this.$container = $('

').appendTo('body');
  });

  afterEach(function () {
    if (this.$container) {
      destroy();
      this.$container.remove();
    }
  });

  var arrayOfObjects = function () {
    return [
      {date: "01/01/2015", name: "Ted", lastName: "Right"},
      {date: "01/01/15", name: "Frank", lastName: "Honest"},
      {date: "41/01/2015", name: "Joan", lastName: "Well"},
      {date: "01/51/2015", name: "Sid", lastName: "Strong"}
    ];
  };

  it("should not positively validate a non-date string", function () {
    var onAfterValidate = jasmine.createSpy('onAfterValidate');

    handsontable({
      data: arrayOfObjects(),
      columns: [
        {data: 'date', type: 'date'},
        {data: 'name'},
        {data: 'lastName'}
      ],
      afterValidate: onAfterValidate
    });

    setDataAtCell(0, 0, 'wat');

    waitsFor(function () {
      return onAfterValidate.calls.length > 0;
    }, 'Cell validation', 1000);

    runs(function () {
      expect(onAfterValidate).toHaveBeenCalledWith(false, 'wat', 0, 'date', undefined, undefined);
    });
  });

  it("should not positively validate a incorrect date string", function () {
    var onAfterValidate = jasmine.createSpy('onAfterValidate');

    handsontable({
      data: arrayOfObjects(),
      columns: [
        {data: 'date', type: 'date'},
        {data: 'name'},
        {data: 'lastName'}
      ],
      afterValidate: onAfterValidate
    });

    setDataAtCell(0, 0, '33/01/2014');

    waitsFor(function () {
      return onAfterValidate.calls.length > 0;
    }, 'Cell validation', 1000);

    runs(function () {
      expect(onAfterValidate).toHaveBeenCalledWith(false, '33/01/2014', 0, 'date', undefined, undefined);
    });
  });

  it("should not positively validate a date string in wrong format", function () {
    var onAfterValidate = jasmine.createSpy('onAfterValidate');

    handsontable({
      data: arrayOfObjects(),
      columns: [
        {data: 'date', type: 'date'},
        {data: 'name'},
        {data: 'lastName'}
      ],
      afterValidate: onAfterValidate
    });

    setDataAtCell(1, 0, '01/01/15');

    waitsFor(function () {
      return onAfterValidate.calls.length > 0;
    }, 'Cell validation', 1000);

    runs(function () {
      expect(onAfterValidate).toHaveBeenCalledWith(false, '01/01/15', 1, 'date', undefined, undefined);
    });
  });

  it("should not positively validate a date string in wrong format (if custom format is provided)", function () {
    var onAfterValidate = jasmine.createSpy('onAfterValidate');

    handsontable({
      data: arrayOfObjects(),
      columns: [
        {data: 'date', type: 'date', dateFormat: 'DD/MM/YY'},
        {data: 'name'},
        {data: 'lastName'}
      ],
      afterValidate: onAfterValidate
    });

    setDataAtCell(1, 0, '01/01/2015');

    waitsFor(function () {
      return onAfterValidate.calls.length > 0;
    }, 'Cell validation', 1000);

    runs(function () {
      expect(onAfterValidate).toHaveBeenCalledWith(false, '01/01/2015', 1, 'date', undefined, undefined);
    });
  });

  it("should positively validate a date string in correct format", function () {
    var onAfterValidate = jasmine.createSpy('onAfterValidate');

    handsontable({
      data: arrayOfObjects(),
      columns: [
        {data: 'date', type: 'date'},
        {data: 'name'},
        {data: 'lastName'}
      ],
      afterValidate: onAfterValidate
    });

    setDataAtCell(1, 0, '01/01/2015');

    waitsFor(function () {
      return onAfterValidate.calls.length > 0;
    }, 'Cell validation', 1000);

    runs(function () {
      expect(onAfterValidate).toHaveBeenCalledWith(true, '01/01/2015', 1, 'date', undefined, undefined);
    });
  });

  it("should positively validate a date string in correct format (if custom format is provided)", function () {
    var onAfterValidate = jasmine.createSpy('onAfterValidate');

    handsontable({
      data: arrayOfObjects(),
      columns: [
        {data: 'date', type: 'date', dateFormat: 'DD/MM/YY'},
        {data: 'name'},
        {data: 'lastName'}
      ],
      afterValidate: onAfterValidate
    });

    setDataAtCell(1, 0, '23/03/15');

    waitsFor(function () {
      return onAfterValidate.calls.length > 0;
    }, 'Cell validation', 1000);

    runs(function () {
      expect(onAfterValidate).toHaveBeenCalledWith(true, '23/03/15', 1, 'date', undefined, undefined);
    });
  });

  describe("correctFormat", function () {
    it("should not make any changes to entered string if correctFormat is not set", function () {
      var onAfterValidate = jasmine.createSpy('onAfterValidate');

      handsontable({
        data: arrayOfObjects(),
        columns: [
          {data: 'date', type: 'date', dateFormat: "MM/DD/YY"},
          {data: 'name'},
          {data: 'lastName'}
        ],
        afterValidate: onAfterValidate
      });

      setDataAtCell(1, 0, '11/23/2013');

      waitsFor(function () {
        return onAfterValidate.calls.length > 0;
      }, 'Cell validation', 1000);

      runs(function () {
        expect(onAfterValidate).toHaveBeenCalledWith(false, '11/23/2013', 1, 'date', undefined, undefined);
      });
    });

    it("should not make any changes to entered string if correctFormat is set to false", function () {
      var onAfterValidate = jasmine.createSpy('onAfterValidate');

      handsontable({
        data: arrayOfObjects(),
        columns: [
          {data: 'date', type: 'date', dateFormat: "MM/DD/YY", correctFormat: false},
          {data: 'name'},
          {data: 'lastName'}
        ],
        afterValidate: onAfterValidate
      });

      setDataAtCell(1, 0, '11/23/2013');

      waitsFor(function () {
        return onAfterValidate.calls.length > 0;
      }, 'Cell validation', 1000);

      runs(function () {
        expect(onAfterValidate).toHaveBeenCalledWith(false, '11/23/2013', 1, 'date', undefined, undefined);
      });
    });

    it("should rewrite the string to the correct format if a date-string in different format is provided", function () {
      var onAfterValidate = jasmine.createSpy('onAfterValidate');

      handsontable({
        data: arrayOfObjects(),
        columns: [
          {data: 'date', type: 'date', dateFormat: "DD/MM/YY", correctFormat: true},
          {data: 'name'},
          {data: 'lastName'}
        ],
        afterValidate: onAfterValidate
      });

      setDataAtCell(1, 0, '11/23/2013');

      waitsFor(function () {
        return onAfterValidate.calls.length > 0;
      }, 'Cell validation', 1000);

      runs(function () {
        expect(onAfterValidate).toHaveBeenCalledWith(true, '11/23/2013', 1, 'date', undefined, undefined);
      });

      waits(30);

      runs(function () {
        expect(getDataAtCell(1, 0)).toEqual("23/11/13");
      });
    });

    it("should not try to correct format of non-date strings", function () {
      var onAfterValidate = jasmine.createSpy('onAfterValidate');

      handsontable({
        data: arrayOfObjects(),
        columns: [
          {data: 'date', type: 'date', dateFormat: "DD/MM/YY", correctFormat: true},
          {data: 'name'},
          {data: 'lastName'}
        ],
        afterValidate: onAfterValidate
      });

      setDataAtCell(1, 0, 'test non-date string');

      waitsFor(function () {
        return onAfterValidate.calls.length > 0;
      }, 'Cell validation', 1000);

      runs(function () {
        expect(onAfterValidate).toHaveBeenCalledWith(false, 'test non-date string', 1, 'date', undefined, undefined);
      });

      waits(30);

    });
  });

});


text:
package main

import (
	"fmt"
	"math/rand"
	"net/http/httptest"
	"testing"
	"time"

	compute "google.golang.org/api/compute/v1"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/testapi"
	"k8s.io/kubernetes/pkg/apis/extensions"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util"
)

// newFakeClusterManagerOrDie creates a new fakeClusterManager.
func newFakeClusterManagerOrDie(t *testing.T) *fakeClusterManager {
	fcm, err := newFakeClusterManager(testClusterName)
	if err != nil {
		t.Fatalf("%v", err)
	}
	return fcm
}

// newLoadBalancerController create a loadbalancer controller.
func newLoadBalancerController(t *testing.T, cm *fakeClusterManager, masterUrl string) *loadBalancerController {
	client := client.NewOrDie(&client.Config{Host: masterUrl, Version: testapi.Default.Version()})
	lb, err := NewLoadBalancerController(client, cm.ClusterManager, 1*time.Second)
	if err != nil {
		t.Fatalf("%v", err)
	}
	return lb
}

// toHTTPIngressPaths converts the given pathMap to a list of HTTPIngressPaths.
func toHTTPIngressPaths(pathMap map[string]string) []extensions.HTTPIngressPath {
	httpPaths := []extensions.HTTPIngressPath{}
	for path, backend := range pathMap {
		httpPaths = append(httpPaths, extensions.HTTPIngressPath{
			Path: path,
			Backend: extensions.IngressBackend{
				ServiceName: backend,
				ServicePort: testBackendPort,
			},
		})
	}
	return httpPaths
}

// toIngressRules converts the given ingressRule map to a list of IngressRules.
func toIngressRules(hostRules map[string]fakeIngressRuleValueMap) []extensions.IngressRule {
	rules := []extensions.IngressRule{}
	for host, pathMap := range hostRules {
		rules = append(rules, extensions.IngressRule{
			Host: host,
			IngressRuleValue: extensions.IngressRuleValue{
				HTTP: &extensions.HTTPIngressRuleValue{
					Paths: toHTTPIngressPaths(pathMap),
				},
			},
		})
	}
	return rules
}

// newIngress returns a new Ingress with the given path map.
func newIngress(hostRules map[string]fakeIngressRuleValueMap) *extensions.Ingress {
	return &extensions.Ingress{
		ObjectMeta: api.ObjectMeta{
			Name:      fmt.Sprintf("%v", util.NewUUID()),
			Namespace: api.NamespaceNone,
		},
		Spec: extensions.IngressSpec{
			Backend: &extensions.IngressBackend{
				ServiceName: defaultBackendName(testClusterName),
				ServicePort: testBackendPort,
			},
			Rules: toIngressRules(hostRules),
		},
		Status: extensions.IngressStatus{
			LoadBalancer: api.LoadBalancerStatus{
				Ingress: []api.LoadBalancerIngress{
					{IP: testIPManager.ip()},
				},
			},
		},
	}
}

// validIngress returns a valid Ingress.
func validIngress() *extensions.Ingress {
	return newIngress(map[string]fakeIngressRuleValueMap{
		"foo.bar.com": testPathMap,
	})
}

// getKey returns the key for an ingress.
func getKey(ing *extensions.Ingress, t *testing.T) string {
	key, err := keyFunc(ing)
	if err != nil {
		t.Fatalf("Unexpected error getting key for Ingress %v: %v", ing.Name, err)
	}
	return key
}

// nodePortManager is a helper to allocate ports to services and
// remember the allocations.
type nodePortManager struct {
	portMap map[string]int
	start   int
	end     int
}

// randPort generated pseudo random port numbers.
func (p *nodePortManager) getNodePort(svcName string) int {
	if port, ok := p.portMap[svcName]; ok {
		return port
	}
	p.portMap[svcName] = rand.Intn(p.end-p.start) + p.start
	return p.portMap[svcName]
}

// toNodePortSvcNames converts all service names in the given map to gce node
// port names, eg foo -> k8-be-<foo nodeport>
func (p *nodePortManager) toNodePortSvcNames(inputMap map[string]fakeIngressRuleValueMap) map[string]fakeIngressRuleValueMap {
	expectedMap := map[string]fakeIngressRuleValueMap{}
	for host, rules := range inputMap {
		ruleMap := fakeIngressRuleValueMap{}
		for path, svc := range rules {
			ruleMap[path] = beName(int64(p.portMap[svc]))
		}
		expectedMap[host] = ruleMap
	}
	return expectedMap
}

func newPortManager(st, end int) *nodePortManager {
	return &nodePortManager{map[string]int{}, st, end}
}

// addIngress adds an ingress to the loadbalancer controllers ingress store. If
// a nodePortManager is supplied, it also adds all backends to the service store
// with a nodePort acquired through it.
func addIngress(lbc *loadBalancerController, ing *extensions.Ingress, pm *nodePortManager) {
	lbc.ingLister.Store.Add(ing)
	if pm == nil {
		return
	}
	for _, rule := range ing.Spec.Rules {
		for _, path := range rule.HTTP.Paths {
			svc := &api.Service{
				ObjectMeta: api.ObjectMeta{
					Name:      path.Backend.ServiceName,
					Namespace: ing.Namespace,
				},
			}
			var svcPort api.ServicePort
			switch path.Backend.ServicePort.Kind {
			case util.IntstrInt:
				svcPort = api.ServicePort{Port: path.Backend.ServicePort.IntVal}
			default:
				svcPort = api.ServicePort{Name: path.Backend.ServicePort.StrVal}
			}
			svcPort.NodePort = pm.getNodePort(path.Backend.ServiceName)
			svc.Spec.Ports = []api.ServicePort{svcPort}
			lbc.svcLister.Store.Add(svc)
		}
	}
}

func TestLbCreateDelete(t *testing.T) {
	cm := newFakeClusterManagerOrDie(t)
	lbc := newLoadBalancerController(t, cm, "")
	inputMap1 := map[string]fakeIngressRuleValueMap{
		"foo.example.com": {
			"/foo1": "foo1svc",
			"/foo2": "foo2svc",
		},
		"bar.example.com": {
			"/bar1": "bar1svc",
			"/bar2": "bar2svc",
		},
	}
	inputMap2 := map[string]fakeIngressRuleValueMap{
		"baz.foobar.com": {
			"/foo": "foo1svc",
			"/bar": "bar1svc",
		},
	}
	pm := newPortManager(1, 65536)
	ings := []*extensions.Ingress{}
	for _, m := range []map[string]fakeIngressRuleValueMap{inputMap1, inputMap2} {
		newIng := newIngress(m)
		addIngress(lbc, newIng, pm)
		ingStoreKey := getKey(newIng, t)
		lbc.sync(ingStoreKey)
		l7, err := cm.l7Pool.Get(ingStoreKey)
		if err != nil {
			t.Fatalf("%v", err)
		}
		cm.fakeLbs.checkUrlMap(t, l7, pm.toNodePortSvcNames(m))
		ings = append(ings, newIng)
	}
	lbc.ingLister.Store.Delete(ings[0])
	lbc.sync(getKey(ings[0], t))

	// BackendServices associated with ports of deleted Ingress' should get gc'd
	// when the Ingress is deleted, regardless of the service. At the same time
	// we shouldn't pull shared backends out from existing loadbalancers.
	unexpected := []int{pm.portMap["foo2svc"], pm.portMap["bar2svc"]}
	expected := []int{pm.portMap["foo1svc"], pm.portMap["bar1svc"]}

	for _, port := range expected {
		if _, err := cm.backendPool.Get(int64(port)); err != nil {
			t.Fatalf("%v", err)
		}
	}
	for _, port := range unexpected {
		if be, err := cm.backendPool.Get(int64(port)); err == nil {
			t.Fatalf("Found backend %+v for port %v", be, port)
		}
	}
	lbc.ingLister.Store.Delete(ings[1])
	lbc.sync(getKey(ings[1], t))

	// No cluster resources (except the defaults used by the cluster manager)
	// should exist at this point.
	for _, port := range expected {
		if be, err := cm.backendPool.Get(int64(port)); err == nil {
			t.Fatalf("Found backend %+v for port %v", be, port)
		}
	}
	if len(cm.fakeLbs.fw) != 0 || len(cm.fakeLbs.um) != 0 || len(cm.fakeLbs.tp) != 0 {
		t.Fatalf("Loadbalancer leaked resources")
	}
	for _, lbName := range []string{getKey(ings[0], t), getKey(ings[1], t)} {
		if l7, err := cm.l7Pool.Get(lbName); err == nil {
			t.Fatalf("Found unexpected loadbalandcer %+v: %v", l7, err)
		}
	}
}

func TestLbFaultyUpdate(t *testing.T) {
	cm := newFakeClusterManagerOrDie(t)
	lbc := newLoadBalancerController(t, cm, "")
	inputMap := map[string]fakeIngressRuleValueMap{
		"foo.example.com": {
			"/foo1": "foo1svc",
			"/foo2": "foo2svc",
		},
		"bar.example.com": {
			"/bar1": "bar1svc",
			"/bar2": "bar2svc",
		},
	}
	ing := newIngress(inputMap)
	pm := newPortManager(1, 65536)
	addIngress(lbc, ing, pm)

	ingStoreKey := getKey(ing, t)
	lbc.sync(ingStoreKey)
	l7, err := cm.l7Pool.Get(ingStoreKey)
	if err != nil {
		t.Fatalf("%v", err)
	}
	cm.fakeLbs.checkUrlMap(t, l7, pm.toNodePortSvcNames(inputMap))

	// Change the urlmap directly through the lb pool, resync, and
	// make sure the controller corrects it.
	l7.UpdateUrlMap(gceUrlMap{
		"foo.example.com": {
			"/foo1": &compute.BackendService{SelfLink: "foo2svc"},
		},
	})

	lbc.sync(ingStoreKey)
	cm.fakeLbs.checkUrlMap(t, l7, pm.toNodePortSvcNames(inputMap))
}

func TestLbNoService(t *testing.T) {
	cm := newFakeClusterManagerOrDie(t)
	lbc := newLoadBalancerController(t, cm, "")
	inputMap := map[string]fakeIngressRuleValueMap{
		"foo.example.com": {
			"/foo1": "foo1svc",
		},
	}
	ing := newIngress(inputMap)
	ing.Spec.Backend.ServiceName = "foo1svc"
	ingStoreKey := getKey(ing, t)

	// Adds ingress to store, but doesn't create an associated service.
	// This will still create the associated loadbalancer, it will just
	// have empty rules. The rules will get corrected when the service
	// pops up.
	addIngress(lbc, ing, nil)
	lbc.sync(ingStoreKey)

	l7, err := cm.l7Pool.Get(ingStoreKey)
	if err != nil {
		t.Fatalf("%v", err)
	}

	// Creates the service, next sync should have complete url map.
	pm := newPortManager(1, 65536)
	addIngress(lbc, ing, pm)
	lbc.enqueueIngressForService(&api.Service{
		ObjectMeta: api.ObjectMeta{
			Name:      "foo1svc",
			Namespace: ing.Namespace,
		},
	})
	// TODO: This will hang if the previous step failed to insert into queue
	key, _ := lbc.ingQueue.queue.Get()
	lbc.sync(key.(string))

	inputMap[defaultBackendKey] = map[string]string{
		defaultBackendKey: "foo1svc",
	}
	expectedMap := pm.toNodePortSvcNames(inputMap)
	cm.fakeLbs.checkUrlMap(t, l7, expectedMap)
}

func TestLbStatusUpdate(t *testing.T) {
	inputMap := map[string]fakeIngressRuleValueMap{
		"foo.example.com": {
			"/foo1": "foo1svc",
		},
	}
	ing := newIngress(inputMap)
	// Set the namespace because we're testing client get/set
	ing.Namespace = api.NamespaceDefault

	response := runtime.EncodeOrDie(
		testapi.Extensions.Codec(), ing)

	// The loadbalancer controller will do a get, to retrieve the most current
	// version of the resource, followed by a PUT with the new ip. This handler
	// responds to the GET and records the PUT.
	fakeHandler := util.FakeHandler{
		StatusCode:   200,
		ResponseBody: response,
	}
	testServer := httptest.NewServer(&fakeHandler)
	defer testServer.Close()

	cm := newFakeClusterManagerOrDie(t)
	lbc := newLoadBalancerController(t, cm, testServer.URL)

	pm := newPortManager(1, 65536)
	addIngress(lbc, ing, pm)

	ingStoreKey := getKey(ing, t)
	lbc.sync(ingStoreKey)
	l7, err := cm.l7Pool.Get(ingStoreKey)
	if err != nil {
		t.Fatalf("%v", err)
	}
	ing.Status = extensions.IngressStatus{
		LoadBalancer: api.LoadBalancerStatus{
			Ingress: []api.LoadBalancerIngress{
				{IP: l7.GetIP()},
			},
		},
	}
	updatedIng := runtime.EncodeOrDie(testapi.Extensions.Codec(), ing)
	fakeHandler.ValidateRequest(
		t, testapi.Extensions.ResourcePath(
			"ingress", ing.Namespace, ing.Name)+"/status",
		"PUT", &updatedIng)
}


text:
#pragma once

#include  <QObject>

class TestTree : public QObject
{
    Q_OBJECT

private slots:
    void test001 ();
    void test002 ();
    void test003 ();
};


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch07/7.3/7.3-6.js
 * @description 7.3 - ES5 recognizes the character <PS> (\u2029) as terminating string literal
 */

function testcase() {
        var prop = "66\u2029123";
        return prop === "66\u2029123" && prop[2] === "\u2029" && prop.length === 6;
    }
runTestCase(testcase);


text:
"""parses configuration and returns useful things"""
#pylint: disable=relative-import
#pylint: disable=super-on-old-class
#pylint: disable=too-many-ancestors

from etl_framework.SqlSchemaConfig import SqlSchemaConfig
from etl_framework.interfaces.configs import CompositeConfigInterface

class CompositeSqlSchemaConfig(SqlSchemaConfig, CompositeConfigInterface):
    """parses configuration files"""

    def configure(self, builder):

        super(CompositeSqlSchemaConfig, self).configure(builder)

        return self.compose(builder)

    @property
    def component_schemas(self):

        return self.config["component_schemas"]

    def compose(self, builder):

        self._compose_schemas(builder)
        self._compose_fields()
        self._compose_indexes()
        self._compose_unique_keys()

        return self

    def _compose_schemas(self, builder):

        for schema_id, schema_config in list(self.component_schemas.items()):
            schema_config["config"] = builder.get_config(schema_id).morph(
                configs=builder.etl_module
            )

    def _compose_unique_keys(self):

        for schema_id, schema_config in list(self.component_schemas.items()):
            schema = schema_config["config"]
            ignored_unique_keys = schema_config["ignored_unique_keys"]
            field_renames = schema_config["field_renames"]
            for unique_key in schema.unique_keys:
                if unique_key not in ignored_unique_keys:
                    unique_key[0] = field_renames.get(unique_key[0], unique_key[0])
                    unique_key[1] = [field_renames.get(field, field) for field in unique_key[1]]
                    self.unique_keys.append(unique_key)

    def _compose_indexes(self):

        for schema_id, schema_config in list(self.component_schemas.items()):
            schema = schema_config["config"]
            ignored_indexes = schema_config["ignored_indexes"]
            field_renames = schema_config["field_renames"]
            for index in schema.indexes:
                if index not in ignored_indexes:
                    index[0] = field_renames.get(index[0], index[0])
                    index[1] = [field_renames.get(field, field) for field in index[1]]
                    self.indexes.append(index)

    def _compose_fields(self):

        for schema_id, schema_config in list(self.component_schemas.items()):
            schema = schema_config["config"]
            ignored_fields = set(schema_config["ignored_fields"])
            field_renames = schema_config["field_renames"]

            for field_name, value in list(schema.fields.items()):
                if field_name not in ignored_fields:
                    field_name = field_renames.get(field_name, field_name)
                    self.fields[field_name] = value


text:
@interface TestViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (strong, nonatomic) NSMutableArray *images;
@property (weak, nonatomic) UIPageControl *pageControl;
@property (weak, nonatomic) UICollectionView *collectionView;
@property (weak, nonatomic) NSTimer *timer;
@property (assign, nonatomic) NSInteger currentIndex;

@end

@implementation TestViewController

NSString * const ID = @"XXAutoLoopView";
- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = NO;

    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 150)];
    [self.view addSubview:containerView];

    _images = [NSMutableArray arrayWithCapacity:4];
    for (NSInteger i = 0; i < 4; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg", i+1]];
        [_images addObject:image];
    }

    // 扩充数据
    [_images addObject:_images[0]]; // 将第一个数据添加到最后
    [_images insertObject:_images[_images.count - 2] atIndex:0]; // 将原始最后一个(也就是现在的倒数第二个)添加到第一位置

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = containerView.frame.size;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:containerView.frame collectionViewLayout:flowLayout];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.pagingEnabled = YES;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.bounces = NO;
    [collectionView registerClass:[XXCollectionViewCell class] forCellWithReuseIdentifier:ID];
    collectionView.contentOffset = CGPointMake(ScreenWidth, 0);

    self.collectionView = collectionView;
    [containerView addSubview:collectionView];

    // UIPageControl
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 130, ScreenWidth, 0)];
    pageControl.pageIndicatorTintColor = [UIColor greenColor];
    pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    pageControl.numberOfPages = _images.count - 2;
    pageControl.currentPage = 0;
    self.pageControl = pageControl;
    [containerView addSubview:pageControl];

    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(loopImageTimer) userInfo:nil repeats:YES];
}

- (void)loopImageTimer {
    int offsetCount =  self.collectionView.contentOffset.x / ScreenWidth;

    CGFloat offsetX = self.collectionView.contentOffset.x;

#warning 当滚动最后一个图片时会间隔2倍Interval,有个小bug
    NSInteger row = offsetCount + 1;
    if (row == self.images.count - 1) {
        self.collectionView.contentOffset = CGPointMake(0, 0);
    } else {
        [UIView animateWithDuration:2.0 animations:^{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];

            NSLog(@"offsetX=%f, offsetCount=%d, row=%ld, currentPage=%d", offsetX, offsetCount, row, offsetCount);
        } completion:^(BOOL finished) {

        }];
    }

    self.pageControl.currentPage = offsetCount;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _images.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XXCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.image = _images[indexPath.item];

    return cell;
}

// 开始拖拽时停止自动滚动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.timer invalidate];
    self.timer = nil;
}

// 拖动停止时恢复自动滚动功能
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(loopImageTimer) userInfo:nil repeats:YES];

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 向左滑动,查看后面的图片
    CGFloat offsetX = scrollView.contentOffset.x;
    CGFloat maxOffsetX = (self.images.count - 1) * ScreenWidth;
    NSLog(@"scrollViewDidEndDecelerating=%f", offsetX);
    if (offsetX == 0) { // 第一张
        self.collectionView.contentOffset = CGPointMake(maxOffsetX - ScreenWidth, 0);
        self.pageControl.currentPage = self.pageControl.numberOfPages - 1;

        return;
    } else if (offsetX == maxOffsetX) {  // 最后一张
        self.collectionView.contentOffset = CGPointMake(ScreenWidth, 0);
        self.pageControl.currentPage = 0;

        return;
    }

    self.pageControl.currentPage = (scrollView.contentOffset.x - ScreenWidth) / ScreenWidth;
}

@end


text:
::-webkit-scrollbar {
  width: 0 !important; }

.col-red {
  background: #F44336; }

.col-yellow {
  background: #FFEB3B; }

.col-amber {
  background: #F4A460; }

.col-green {
  background: #4CAF50; }

.text-amber {
  color: #F4A460; }

.mb-20 {
  margin-bottom: 20px; }

.mb-40 {
  margin-bottom: 40px; }

select {
  text-align-last: center;
  border: none; }

@font-face {
  font-family: 'Roboto Light';
  src: url("../fonts/Roboto-Light.ttf"); }
@font-face {
  font-family: 'Roboto Thin';
  src: url("../fonts/Roboto-Thin.ttf"); }
@font-face {
  font-family: 'Roboto Regular';
  src: url("../fonts/Roboto-Regular.ttf"); }
@font-face {
  font-family: 'Roboto Medium';
  src: url("../fonts/Roboto-Medium.ttf"); }
@font-face {
  font-family: 'Roboto Bold';
  src: url("../fonts/Roboto-Bold.ttf"); }
input[type="checkbox"] {
  visibility: hidden; }

.checkb {
  width: 25px;
  margin: 20px 100px;
  position: relative;
  display: inline-block;
  margin: 0; }
  .checkb label {
    cursor: pointer;
    position: absolute;
    width: 25px;
    height: 25px;
    top: 0;
    left: -10px;
    background: white;
    border: 1px solid #ddd;
    border-radius: 50%; }
    .checkb label:after {
      opacity: 0;
      content: '';
      position: absolute;
      width: 9px;
      height: 5px;
      background: transparent;
      top: 6px;
      left: 7px;
      border: 3px solid #4CAF50;
      border-top: none;
      border-right: none;
      transform: rotate(-45deg);
      transition: all 0.1s ease-out; }

.checkb input[type="checkbox"]:checked + label:after {
  opacity: 1;
  width: 14px;
  height: 8px;
  top: 4px;
  left: 5px;
  transition: all 0.1s ease-in; }

.clear {
  clear: both; }

.mCSB_draggerContainer {
  right: -10px !important; }

html {
  overflow: hidden; }

body {
  position: absolute;
  top: 0px;
  width: 100%; }

.center.row {
  height: 100%;
  margin-left: auto;
  margin-right: auto;
  max-width: 500px; }

.menu, .insides, .imageHolder {
  -webkit-app-region: no-drag;
  -webkit-user-select: none; }

#background-container {
  -webkit-app-region: drag; }

.slide-right {
  z-index: 2;
  position: absolute;
  right: 20px;
  font-size: 54px;
  bottom: -102px;
  color: white; }
  .slide-right:hover, .slide-right:visited, .slide-right:focus {
    color: white; }

.slide-left {
  z-index: 2;
  position: absolute;
  left: 20px;
  font-size: 54px;
  color: white;
  bottom: -102px; }
  .slide-left:hover, .slide-left:visited, .slide-left:focus {
    color: white; }

.clean {
  list-style-type: none;
  padding: 0 0 !important;
  margin: 0 0; }
  .clean li {
    display: list-item;
    position: absolute;
    width: 100%; }

input::-webkit-input-placeholder {
  /* WebKit, Blink, Edge */
  color: #767b7f; }

#background-container {
  position: absolute;
  top: 0px;
  width: 100%;
  height: 700px;
  background: url("../backgrounds/img/6.jpg") no-repeat center;
  background-size: cover; }
  #background-container:after {
    position: absolute;
    background-color: #325C62;
    opacity: .3;
    top: 0; }

#vid {
  position: fixed;
  top: 0;
  left: -50%;
  z-index: -100;
  width: auto;
  height: 100%; }

.imageHolder {
  -webkit-user-select: none;
  position: relative;
  z-index: 2;
  margin-top: 10%;
  text-align: center; }
  .imageHolder .logo {
    color: black;
    display: inline-block;
    padding: 50px 35px;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    font-size: 27px;
    margin: 0;
    box-shadow: #404040 0px 0px 4px;
    font-family: "Roboto Light";
    text-shadow: gray 0px 2px 5px;
    transition: all 0.3s ease; }
    .imageHolder .logo:hover {
      box-shadow: #987ABC 0px 0px 10px;
      text-shadow: 0;
      background: white;
      transition: all 0.3s ease; }
  .imageHolder .title {
    margin-top: 10px;
    font-family: "Roboto Light";
    font-size: 48px;
    color: white; }

.menu {
  display: inline-block;
  position: absolute;
  top: 0px;
  right: 20px;
  z-index: 1; }
  .menu a {
    font-size: 40px;
    font-family: "Roboto Thin";
    display: inline-block;
    color: white; }

.linkbtn {
  color: #393D40;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 3px;
  display: block;
  margin-top: 10px;
  text-align: center; }
  .linkbtn:hover {
    background: rgba(152, 122, 188, 0.9);
    color: white;
    transition: all 0.3s ease; }

.insides {
  position: relative;
  top: 20px;
  z-index: 1;
  min-height: 400px; }

#auth-tabs {
  background: transparent;
  border: none;
  color: white;
  max-width: 70%;
  margin: 0 auto;
  text-align: center; }
  #auth-tabs:active, #auth-tabs :focus, #auth-tabs :visited, #auth-tabs :hover {
    background: transparent;
    color: white; }
  #auth-tabs a {
    color: white; }
  #auth-tabs a[aria-selected=true] {
    color: white;
    background-color: transparent; }
  #auth-tabs li a {
    padding-bottom: 5px;
    padding: 1.25rem 1rem; }
  #auth-tabs .is-active {
    border-bottom: solid 3px #F4A460 !important; }

#auth-tabs * {
  font-family: "Roboto Regular";
  font-size: 20px; }

.tabs-content {
  max-width: 50%;
  margin: 0 auto;
  background: transparent;
  border: none;
  position: relative;
  color: white;
  z-index: 1; }
  .tabs-content form input {
    background: rgba(255, 255, 255, 0.9);
    text-align: center;
    color: #767b7f;
    border: none;
    border-radius: 3px;
    box-shadow: none;
    height: 2.5rem;
    line-height: 1.2;
    transition: all 0.3s ease; }
    .tabs-content form input:focus, .tabs-content form input:active {
      box-shadow: none;
      background: #987ABC;
      color: white;
      transition: all 0.3s ease; }
    .tabs-content form input:focus::-webkit-input-placeholder {
      color: white;
      transition: all 0.3s ease; }
  .tabs-content form .checkb {
    position: relative; }
    .tabs-content form .checkb label {
      display: inline-block;
      color: white; }
      .tabs-content form .checkb label span {
        position: relative;
        left: 30px;
        width: 100px;
        overflow: hidden;
        white-space: nowrap; }
  .tabs-content form input[type="checkbox"] {
    margin-bottom: 0; }
  .tabs-content form .button {
    width: 100% !important;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 3px;
    color: #393D40;
    font-family: "Roboto Bold";
    font-size: 20px;
    padding: 10px;
    margin: 10px 0px 0px 0px; }
    .tabs-content form .button:hover, .tabs-content form .button:active, .tabs-content form .button:focus {
      background: rgba(255, 255, 255, 0.9);
      color: #987ABC;
      box-shadow: #987ABC 0px 1px 10px; }
  .tabs-content form select {
    background-color: rgba(255, 255, 255, 0.9);
    color: #767b7f;
    border-radius: 3px; }
  .tabs-content form .bottom {
    display: block;
    width: 100%;
    cursor: pointer;
    text-align: center;
    position: relative;
    left: 0;
    z-index: 2;
    color: white;
    font-family: "Roboto Light";
    font-size: 18px;
    line-height: 2.5; }
    .tabs-content form .bottom:visited, .tabs-content form .bottom :focus, .tabs-content form .bottom :active {
      color: white; }

.tabs-content * {
  font-family: "Roboto Regular"; }

/*# sourceMappingURL=auth.css.map */


text:
package norman.passgen.ui;

import norman.passgen.core.Generator;
import norman.passgen.core.Generator.Optionality;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import java.util.ResourceBundle;

import static norman.passgen.core.Generator.Optionality.MANDATORY;
import static norman.passgen.core.Generator.Optionality.PROHIBITED;

public class MainFrame extends JFrame implements ActionListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(MainFrame.class);
    private ResourceBundle bundle;
    private Properties appProps;
    private Container desktop;
    private JMenuItem exitFileItem;

    private JSpinner nbrOfPasswordsSpinner;
    private JSpinner lengthSpinner;
    private JCheckBox numberForFirstCheckBox;
    private JCheckBox lowerCaseCheckBox;
    private JCheckBox upperCaseCheckBox;
    private JCheckBox numericCheckBox;
    private JCheckBox specialCheckBox;
    private JButton generateButton;
    private JTextArea passwordsTextArea;
    private JButton clipboardButton;

    public MainFrame(Properties appProps) throws HeadlessException {
        super();
        setResizable(false);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.appProps = appProps;

        initComponents();

        nbrOfPasswordsSpinner.setValue(Integer.parseInt(appProps.getProperty("nbr.of.passwords")));
        lengthSpinner.setValue(Integer.parseInt(appProps.getProperty("length")));
        numberForFirstCheckBox.setSelected(Boolean.parseBoolean(appProps.getProperty("number.for.first")));
        lowerCaseCheckBox.setSelected(Boolean.parseBoolean(appProps.getProperty("lower.case")));
        upperCaseCheckBox.setSelected(Boolean.parseBoolean(appProps.getProperty("upper.case")));
        numericCheckBox.setSelected(Boolean.parseBoolean(appProps.getProperty("numeric")));
        specialCheckBox.setSelected(Boolean.parseBoolean(appProps.getProperty("special")));

        pack();
        int x = Integer.parseInt(appProps.getProperty("main.frame.location.x"));
        int y = Integer.parseInt(appProps.getProperty("main.frame.location.y"));
        setLocation(x, y);
    }

    private void initComponents() {
        bundle = ResourceBundle.getBundle("norman.passgen.ui.MainFrame");
        setTitle(bundle.getString("title"));
        desktop = new JPanel(new GridBagLayout());
        setContentPane(desktop);

        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(8, 16, 4, 8);
        desktop.add(new JLabel(bundle.getString("nbr.of.passwords.label")), c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(8, 8, 4, 16);
        nbrOfPasswordsSpinner = new JSpinner(new SpinnerNumberModel(88, 1, 99, 1));
        desktop.add(nbrOfPasswordsSpinner, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 1;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 16, 4, 8);
        desktop.add(new JLabel(bundle.getString("length.label")), c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 1;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 8, 4, 16);
        lengthSpinner = new JSpinner(new SpinnerNumberModel(88, 1, 99, 1));
        desktop.add(lengthSpinner, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 2;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 16, 4, 8);
        desktop.add(new JLabel(bundle.getString("number.for.first.label")), c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 2;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 8, 4, 16);
        numberForFirstCheckBox = new JCheckBox();
        desktop.add(numberForFirstCheckBox, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 3;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 16, 4, 8);
        desktop.add(new JLabel(bundle.getString("lower.case.label")), c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 3;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 8, 4, 16);
        lowerCaseCheckBox = new JCheckBox();
        desktop.add(lowerCaseCheckBox, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 4;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 16, 4, 8);
        desktop.add(new JLabel(bundle.getString("upper.case.label")), c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 4;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 8, 4, 16);
        upperCaseCheckBox = new JCheckBox();
        desktop.add(upperCaseCheckBox, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 5;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 16, 4, 8);
        desktop.add(new JLabel(bundle.getString("numeric.label")), c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 5;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 8, 4, 16);
        numericCheckBox = new JCheckBox();
        desktop.add(numericCheckBox, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 6;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 16, 4, 8);
        desktop.add(new JLabel(bundle.getString("special.label")), c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 6;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 8, 4, 16);
        specialCheckBox = new JCheckBox();
        desktop.add(specialCheckBox, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 7;
        c.gridwidth = 2;
        c.insets = new Insets(4, 16, 4, 16);
        generateButton = new JButton(bundle.getString("generate.button.label"));
        desktop.add(generateButton, c);
        generateButton.addActionListener(this);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 8;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(4, 16, 8, 8);
        passwordsTextArea = new JTextArea(3, 20);
        passwordsTextArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(passwordsTextArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        desktop.add(scrollPane, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 8;
        c.insets = new Insets(4, 8, 8, 16);
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            URL url = loader.getResource("images/clipboard-regular.png");
            BufferedImage image = ImageIO.read(url);
            ImageIcon icon = new ImageIcon(image);
            clipboardButton = new JButton(icon);
            clipboardButton.setToolTipText(bundle.getString("clipboard.button.tool.tip.text"));
        } catch (IOException e) {
            LOGGER.warn("Unable to create button icon", e);
            clipboardButton = new JButton(bundle.getString("clipboard.button.tool.tip.text"));
        }
        desktop.add(clipboardButton, c);
        clipboardButton.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        if (actionEvent.getSource().equals(generateButton)) {
            generatePassword();
        } else if (actionEvent.getSource().equals(clipboardButton)) {
            copyPasswordsToClipboard();
        }
    }

    @Override
    protected void processWindowEvent(WindowEvent windowEvent) {
        if (windowEvent.getSource() == this && windowEvent.getID() == WindowEvent.WINDOW_CLOSING) {

            // Get current size and position of UI and remember it.
            Point location = getLocation();
            appProps.setProperty("main.frame.location.x", Integer.toString(location.x));
            appProps.setProperty("main.frame.location.y", Integer.toString(location.y));

            appProps.setProperty("nbr.of.passwords", Integer.toString((Integer) nbrOfPasswordsSpinner.getValue()));
            appProps.setProperty("length", Integer.toString((Integer) lengthSpinner.getValue()));
            appProps.setProperty("number.for.first", Boolean.toString(numberForFirstCheckBox.isSelected()));
            appProps.setProperty("lower.case", Boolean.toString(lowerCaseCheckBox.isSelected()));
            appProps.setProperty("upper.case", Boolean.toString(upperCaseCheckBox.isSelected()));
            appProps.setProperty("numeric", Boolean.toString(numericCheckBox.isSelected()));
            appProps.setProperty("special", Boolean.toString(specialCheckBox.isSelected()));

            // Save the properties file to a local file.
            try {
                Application.storeProps(appProps);
            } catch (LoggingException e) {
                JOptionPane.showMessageDialog(this, bundle.getString("error.message.saving.window.size.and.location"),
                        bundle.getString("error.dialog.title"), JOptionPane.ERROR_MESSAGE);
            }
        }
        super.processWindowEvent(windowEvent);
    }

    private void generatePassword() {
        int nbrOfPasswords = (int) nbrOfPasswordsSpinner.getValue();
        int length = (int) lengthSpinner.getValue();
        boolean allowNumberForFirstChar = numberForFirstCheckBox.isSelected();
        Optionality includeLows = lowerCaseCheckBox.isSelected() ? MANDATORY : PROHIBITED;
        Optionality includeCaps = upperCaseCheckBox.isSelected() ? MANDATORY : PROHIBITED;
        Optionality includeNumbers = numericCheckBox.isSelected() ? MANDATORY : PROHIBITED;
        Optionality includeSpecials = specialCheckBox.isSelected() ? MANDATORY : PROHIBITED;
        if (allowNumberForFirstChar && includeLows == PROHIBITED && includeCaps == PROHIBITED &&
                includeNumbers == PROHIBITED && includeSpecials == PROHIBITED) {
            passwordsTextArea.setText(null);
            JOptionPane.showMessageDialog(this, bundle.getString("validate.message.generate.1"),
                    bundle.getString("error.dialog.title"), JOptionPane.ERROR_MESSAGE);
        } else if (!allowNumberForFirstChar && includeLows == PROHIBITED && includeCaps == PROHIBITED &&
                includeSpecials == PROHIBITED) {
            passwordsTextArea.setText(null);
            JOptionPane.showMessageDialog(this, bundle.getString("validate.message.generate.2"),
                    bundle.getString("error.dialog.title"), JOptionPane.ERROR_MESSAGE);
        } else {
            StringBuilder sb = null;
            for (int i = 0; i < nbrOfPasswords; i++) {

                String password = Generator
                        .generatePassword(length, allowNumberForFirstChar, includeLows, includeCaps, includeNumbers,
                                includeSpecials);
                if (sb == null) {
                    sb = new StringBuilder(password);
                } else {
                    sb.append(System.lineSeparator());
                    sb.append(password);
                }
            }
            passwordsTextArea.setText(sb.toString());
        }
    }

    private void copyPasswordsToClipboard() {
        StringSelection stringSelection = new StringSelection(passwordsTextArea.getText());
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);
    }
}


text:
package org.wso2.carbon.registry.resource.services.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.registry.common.eventing.NotificationService;
import org.wso2.carbon.registry.common.eventing.RegistryEvent;

public class CommonUtil {

    private static final Log log = LogFactory.getLog(CommonUtil.class);

    private static RegistryService registryService;

    private static NotificationService registryNotificationService;

    public static void setRegistryService(RegistryService service) {
        registryService = service;
    }

    public static RegistryService getRegistryService() {
        return registryService;
    }

    public static void setRegistryNotificationService(NotificationService registryNotificationService) {
        CommonUtil.registryNotificationService = registryNotificationService;
    }

    public static void notify(RegistryEvent event, Registry registry, String path)
            throws Exception {
        try {
            if (CommonUtil.registryNotificationService == null) {
                log.debug("Eventing service is unavailable.");
                return;
            }
            if (registry == null || registry.getEventingServiceURL(path) == null) {
                CommonUtil.registryNotificationService.notify(event);
            } else if (registry.getEventingServiceURL(null) == null) {
                log.error("Unable to send notification.");
            } else if (registry.getEventingServiceURL(path).equals(registry.getEventingServiceURL(null))) {
                CommonUtil.registryNotificationService.notify(event);
            } else {
                CommonUtil.registryNotificationService.notify(event, registry.getEventingServiceURL(path));
            }
        } catch (RegistryException e) {
            log.error("Unable to send notification", e);
        }
    }
}


text:
/**
 * Created by Kevin on 12/12/2016.
 */

(function() {
    'use strict';

    angular
        .module('app')
        .controller('AppCtrl', AppCtrl);

    AppCtrl.$inject = ['$scope'];

    function AppCtrl($scope) {
        $scope.currentNavItem = 'view1';
    }

})();


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdBorderStyle extends React.Component<IconBaseProps> { }


text:
package com.airbnb.common.ml.strategy.trainer

import scala.reflect.ClassTag
import scala.util.Random
import scala.util.Try

import com.typesafe.config.Config
import org.apache.spark.SparkContext
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.stat.Statistics
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.hive.HiveContext
import org.apache.spark.storage.StorageLevel

import com.airbnb.common.ml.strategy.config.{BaseSearchConfig, DirectQueryEvalConfig, EvalConfig, TrainingConfig, TrainingOptions}
import com.airbnb.common.ml.strategy.data.DataLoadingRules
import com.airbnb.common.ml.strategy.data.{BinaryTrainingSample, ModelOutput, TrainingData}
import com.airbnb.common.ml.strategy.eval.BinaryMetrics
import com.airbnb.common.ml.strategy.params.StrategyParams
import com.airbnb.common.ml.util.{HDFSUtil, HiveUtil, PipelineUtil, RandomUtil, ScalaLogging, Sort}

trait BinaryRegressionTrainer[T <: BinaryTrainingSample]
  extends Serializable
    with ScalaLogging {

  def strategyParams: StrategyParams[T]

  def trainingDataType: TrainingData[T]

  def getDefaultParams(trainingOptions: TrainingOptions): StrategyParams[T] = {
    if (strategyParams.params.length == 0) {
      strategyParams.getDefaultParams(trainingOptions)
    } else {
      strategyParams
    }
  }

  /**
    * Given a query, load StrategyParams from Hive
    *
    * @param hiveContext HiveContext
    * @param paramsQuery Hive query to pull params
    * @return the loaded per-model params
    */
  def loadParamsFromHive(hiveContext: HiveContext, paramsQuery: String):
  RDD[(String, StrategyParams[T])] = {
    hiveContext.sql(paramsQuery)
      // params share same key with training data.
      .map(row => (trainingDataType.parseKeyFromHiveRow(row),
                    strategyParams.parseParamsFromHiveRow(row)))
  }

  def getLearningRate(
      r0: Double, r1: Double,
      example: T,
      options: TrainingOptions
  ): Double

  // each trainer provides its own schema to generate data frame
  def createDataFrameFromModelOutput(models: RDD[(String, StrategyParams[T])], hc: HiveContext):
  DataFrame

  def loadModelWithIndexMapFromHdfs(output: String):
  scala.collection.Map[(java.lang.String, Int), StrategyParams[T]] = {
    val modelStr = HDFSUtil.readStringFromFile(output)
    modelStr
      .split("\n")
      .map(strategyParams.parseLine)
      .toMap
  }

  // load Training data by join two DataFrame with key,
  // this generates new training samples which
  // should has same fields as the loadTrainingDataFromHive methods
  // use this method if you want to change any fields and retrain model
  def loadTrainingDataByJoinTwoDataFrames(
      main: DataFrame,
      key: Seq[String],
      addition: DataFrame
  )(implicit c: ClassTag[T]):
  RDD[(String, Seq[T])] = {
    val joined = main.join(addition, key)
    trainingDataType.loadDataFromDataFrame(joined)
  }

  // default is same as loadTrainingDataFromHive
  // allow to override so that it loads different data
  // refer to StrategyModelTrainerV1.loadDataWithOptions for how to use it
  // TODO retire it
  def loadDataWithOptions(
      config: Config,
      hc: HiveContext,
      dataQuery: String,
      forTraining: Boolean = true
  )(implicit c: ClassTag[T]): RDD[(String, Seq[T])] = {
    trainingDataType.loadDataFromHive(hc, dataQuery)
  }

  // return trained result in data frame,
  // i.e. StrategyModelTrainerV1 return StrategyModelDataSource.schema
  def getResultDataFrame(
      strategyConfig: Config,
      hc: HiveContext,
      trainingData: RDD[(String, Seq[T])]
  )(implicit c: ClassTag[T]): DataFrame = {
    val models: RDD[(String, StrategyParams[T])] =
      trainStrategyModelWithRDD(
        hc,
        strategyConfig,
        trainingData
      )
    createDataFrameFromModelOutput(models, hc)
  }

  /**
    * Given an RDD of [(id, TrainingData)], train strategy models for each set
    * of training datas and save the results to Hive.
    *
    * @param hc              HiveContext
    * @param config          top-level config
    * @param rawTrainingData (id -> [TrainingData])
    * @return RDD of (id, StrategyParams)
    */
  def trainStrategyModelWithRDD(
      hc: HiveContext,
      config: Config,
      rawTrainingData: RDD[(String, Seq[T])]
  )(implicit c: ClassTag[T]): RDD[(String, StrategyParams[T])] = {
    // Load training options from config
    val trainingOptions: TrainingOptions =
      TrainingOptions
        .loadBaseTrainingOptions(
          config.getConfig("training_options"))

    // Prepare the per-model strategy params for our training data
    val trainingExamples: RDD[(String, (Seq[T], Option[StrategyParams[T]]))] =
      joinTrainingSamplesWithParams(hc, config, rawTrainingData, trainingOptions)

    // Perform the training and return trained strategy params
    trainAll(trainingExamples, trainingOptions)
  }

  /**
    * support parameter search, i.e. given Array[TrainingOptions] return
    * trained models for each TrainingOption in the array key in the
    * returning RDD is (id, param_idx), where param_idx specifies
    * the index of the TrainingOptions used to run the training.
    *
    * @param examples             training samples
    * @param trainingOptionsArray a TrainingOption for each hyperparam combo
    * @return (id, training_options_index) -> trained_params
    */
  def trainAllWithOptionArray(
      examples: RDD[(String, Seq[T])],
      trainingOptionsArray: Array[TrainingOptions]
  ): RDD[((String, Int), StrategyParams[T])] = {
    // Note: This does not support initialization from existing parameters
    examples
      .mapPartitions(iterable => {
        iterable.flatMap { example =>
          val id: String = example._1
          val samples: Seq[T] = example._2

          // For each of the training options, train it using all
          // of the samples for this id instance
          trainingOptionsArray
            .zipWithIndex
            .map {
              case (option: TrainingOptions, idx: Int) => {
                ((id, idx), train(samples, option)._1)
              }
            }.iterator
        }
      })
  }

  /**
    * Given training examples and initial strategy params, train each of the models'
    * strategy params.
    *
    * @param examples training samples, with starting training options
    * @param options  training options
    * @return trained params
    */
  def trainAll(
      examples: RDD[(String, (Seq[T], Option[StrategyParams[T]]))],
      options: TrainingOptions
  ): RDD[(String, StrategyParams[T])] = {
    examples
      .map {
        case (id: String, (samples: Seq[T], param: Option[StrategyParams[T]])) => {
          (id, train(samples, options, param)._1)
        }
      }
  }

  def getParamsFromPerModelOptions(
      trainingExamples: RDD[(String, Seq[T])],
      perModelOptions: RDD[(String, Array[Double])],
      trainingOptions: TrainingOptions
  ): RDD[String] = {
    trainingExamples.
      leftOuterJoin(perModelOptions).
      map {
        case (id, (examples, options)) => {
          val modelOptions = if (options.isDefined) {
            TrainingOptions.fromArrayAndGeneralOptions(
              options.get,
              trainingOptions
            )
          } else {
            trainingOptions
          }
          val params = train(examples, modelOptions)
          Vector(id, params._1.toString, params._2).mkString("\t")
        }
      }
  }

  def trainWithSameOptions(
      sc: SparkContext,
      config: Config
  )(implicit c: ClassTag[T]): Unit = {
    val trainingConfig = TrainingConfig.loadConfig(config)
    val hc: HiveContext = new HiveContext(sc)

    val trainingExamples: RDD[(String, Seq[T])] =
      BinaryRegressionTrainer.getTraining(
        hc,
        trainingDataType,
        trainingConfig,
        DataLoadingRules.isEnoughSamplesToTrain
      )

    val trainingOptions: TrainingOptions =
      TrainingOptions
        .loadBaseTrainingOptions(
          config.getConfig("training_options"))

    val result = trainingExamples.
      map {
        case (id, examples) => {
          val params = train(examples, trainingOptions)
          Vector(id, params._1.toString, params._2).mkString("\t")
        }
      }
    HiveUtil.saveToHiveWithConfig(hc, config.getConfig("production"), result)
  }

  def trainWithPerModelOptions(
      sc: SparkContext,
      config: Config
  )(implicit c: ClassTag[T]): Unit = {
    val trainingConfig = TrainingConfig.loadConfig(config)
    val hc: HiveContext = new HiveContext(sc)

    val trainingExamples: RDD[(String, Seq[T])] =
      BinaryRegressionTrainer.getTraining(
        hc,
        trainingDataType,
        trainingConfig,
        DataLoadingRules.isEnoughSamplesToTrain
      )

    val trainingOptions: TrainingOptions =
      TrainingOptions
        .loadBaseTrainingOptions(
          config.getConfig("training_options"))

    val perModelOptions = HiveUtil.loadDataFromHive(
      hc,
      config.getString("options_query"),
      HiveUtil.parseLongToStringFromHiveRow("id_listing"),
      HiveUtil.parseDoubleArrayFromHiveRow("options")
    )

    val result = getParamsFromPerModelOptions(
      trainingExamples,
      perModelOptions,
      trainingOptions
    )

    HiveUtil.saveToHiveWithConfig(hc, config.getConfig("production"), result)
  }

  /**
    * Given a top-level configuration, perform a search training and evaluation job.
    * used in dev
    *
    * @param sc     SparkContext
    * @param config top-level config instance
    */
  def paramSearchPerModelWithEvalAndHoldout(
      sc: SparkContext,
      config: Config
  )(implicit c: ClassTag[T]): Unit = {
    // Pull out the search and eval configs for passing along
    val searchConf: BaseSearchConfig = BaseSearchConfig.loadConfig(config)
    val evalConfig: EvalConfig =
      DirectQueryEvalConfig.loadConfig(config)

    // Train using the given search and eval configs
    trainWithBaseSearchConfigPerModel(sc, searchConf, evalConfig)
  }

  /**
    * Given a top-level configuration, divide the training_data_query
    * into training/eval/holdout based on config.
    * used in production
    *
    * @param sc     SparkContext
    * @param config top-level config instance
    */
  def paramSearchPerModel(
      sc: SparkContext,
      config: Config
  )(implicit c: ClassTag[T]): Unit = {
    // Pull out the search and eval configs for passing along
    val searchConfig: BaseSearchConfig = BaseSearchConfig.loadConfig(config)
    val trainingConfig = TrainingConfig.loadConfig(config)

    val hc: HiveContext = new HiveContext(sc)
    val trainingOptionsArray: Array[TrainingOptions] = searchConfig.getTrainingOptions
    logger.info(s"Training models with ${trainingOptionsArray.mkString(",")}")
    val trainingExamples: RDD[(String, Seq[T])] =
      BinaryRegressionTrainer.getTraining(
        hc,
        trainingDataType,
        trainingConfig,
        DataLoadingRules.isEnoughSamplesToTrain
      )
    val results: RDD[ModelOutput[T]] =
      trainingExamples
        .map {
          case (id: String, data: Seq[T]) => {
            val samples = RandomUtil.sample(data, searchConfig.sampleRatio)
            // TODO cross validation
            searchBestOptions(id, samples.head, samples(1), samples(2), trainingOptionsArray)
          }
        }
        .cache()

    BinaryRegressionTrainer.saveAndEvalModelOutput(hc, results, searchConfig)

    // Clean up the results RDD
    results.unpersist()
  }

  /**
    * Using the config, load our data sets and use them to perform the training
    * search and evaluation.
    *
    * @param sc           SparkContext
    * @param searchConfig BaseSearchConfig instance with param search options
    * @param evalConfig   StrategyModelEvalConfig instance
    */
  def trainWithBaseSearchConfigPerModel(
      sc: SparkContext,
      searchConfig: BaseSearchConfig,
      evalConfig: EvalConfig
  )(implicit c: ClassTag[T]): Unit = {
    // Load training, eval, and holdout data feeds
    val hc: HiveContext = new HiveContext(sc)

    val trainingExamples: RDD[(String, Seq[T])] =
      BinaryRegressionTrainer.getTraining(
        hc,
        trainingDataType,
        evalConfig.trainingConfig,
        DataLoadingRules.isEnoughSamplesToTrain
      )

    logger.info("Loading eval data")
    val evalSamples: RDD[(String, Seq[T])] =
      trainingDataType.loadDataFromHive(hc, evalConfig.evalDataQuery)

    logger.info("Loading holdout data")
    val holdoutSamples: RDD[(String, Seq[T])] =
      trainingDataType.loadDataFromHive(hc, evalConfig.holdoutDataQuery)

    val trainingOptionsArray: Array[TrainingOptions] = searchConfig.getTrainingOptions
    logger.info(s"Training models with ${trainingOptionsArray.mkString(",")}")
    val results: RDD[ModelOutput[T]] =
      searchBestOptionsPerModel(
        trainingExamples,
        evalSamples,
        holdoutSamples,
        trainingOptionsArray
      ).cache()

    BinaryRegressionTrainer.saveAndEvalModelOutput(hc, results, searchConfig)

    // Clean up the results RDD
    results.unpersist()
  }

  /**
    * Given training, eval and holdout examples, join them together by modelId
    * and use them to grid search for the best training options.
    *
    * ** Note: This does not support initialization from existing parameters
    *
    * @param trainingExamples training data set
    * @param evalExamples     evaluation data set
    * @param holdoutExamples  holdout data set
    * @param optionArr        TrainingOptions to try
    * @return a ModelOutput for every model
    */
  def searchBestOptionsPerModel(
      trainingExamples: RDD[(String, Seq[T])],
      evalExamples: RDD[(String, Seq[T])],
      holdoutExamples: RDD[(String, Seq[T])],
      optionArr: Array[TrainingOptions]
  ): RDD[ModelOutput[T]] = {
    trainingExamples
      .join(evalExamples)
      .join(holdoutExamples)
      .map {
        case (id: String, ((training: Seq[T], eval: Seq[T]), holdout: Seq[T])) => {
          searchBestOptions(id, training, eval, holdout, optionArr)
        }
      }
  }

  /**
    * Grid search across our training options, perform training, and then
    * perform evaluation of the eval and holdout examples.
    *
    * @param id               modelId
    * @param trainingExamples training data set
    * @param evalExamples     eval data set
    * @param holdoutExamples  holdout dataset
    * @param optionArr        different TrainingOptions permutations to try
    * @return
    */
  def searchBestOptions(
      id: String,
      trainingExamples: Seq[T],
      evalExamples: Seq[T],
      holdoutExamples: Seq[T],
      optionArr: Array[TrainingOptions]
  ): ModelOutput[T] = {
    // Run the training and evaluation
    val ((params: StrategyParams[T], loss: Double), trainingOptions: TrainingOptions) =
      optionArr
        .map { option: TrainingOptions =>
          (trainAndEval(trainingExamples, evalExamples, option), option)
        }
        .min(Ordering.by {
          output: ((StrategyParams[T], Double), TrainingOptions) =>
            output._1._2
        })

    // Evaluate metrics for the the eval and holdout examples
    val evalMetrics: BinaryMetrics =
      BinaryRegressionTrainer.getMetrics(evalExamples, params)
    val holdoutMetrics: BinaryMetrics =
      BinaryRegressionTrainer.getMetrics(holdoutExamples, params)

    // Return a constructed ModelOutput instance
    ModelOutput(id, params, loss, evalMetrics, holdoutMetrics, trainingOptions)
  }

  /**
    * Given training and eval examples, perform a train and eval run.
    *
    * @param trainingExamples training data set
    * @param evalExamples     eval data set
    * @param defaultOptions   default training options for this model
    * @param inputParam       strategy params to start with
    * @param debug            true if debug mode is needed
    * @return (trainedParams, evalScore)
    */
  def trainAndEval(
      trainingExamples: Seq[T],
      evalExamples: Seq[T],
      defaultOptions: TrainingOptions,
      inputParam: Option[StrategyParams[T]] = None,
      debug: Boolean = false
  ): (StrategyParams[T], Double) = {
    val params: StrategyParams[T] =
      train(trainingExamples, defaultOptions, inputParam, debug)._1
    (params, eval(evalExamples, params, defaultOptions.evalRatio))
  }

  def eval(
      examples: Seq[T],
      params: StrategyParams[T],
      ratio: Double
  ): Double = {
    val evalResult: Seq[Double] =
      examples.map(example =>
        BinaryRegressionTrainer.evalExample(example, params, ratio)
      )
    evalResult.sum / evalResult.length
  }

  /**
    * Given a set of training examples and a collection of training options,
    * train strategy params using a bounded loss function.
    *
    * @param examples               training samples
    * @param defaultTrainingOptions training options
    * @param inputParam             initial strategy params
    * @param debug                  if true, print extra logging
    * @return trained strategy params
    */
  def train(
      examples: Seq[T],
      defaultTrainingOptions: TrainingOptions,
      inputParam: Option[StrategyParams[T]] = None,
      debug: Boolean = false
  ): (StrategyParams[T], Double) = {
    // Input:
    // - examples are corresponding to the same model
    // - each implementation defines its own params
    // Output:
    // - updated host rejection parameters
    var params: StrategyParams[T] =
      getOrDefaultParams(inputParam, defaultTrainingOptions)

    val sampleCount: Int = examples.length

    if (BinaryRegressionTrainer.enoughTrueSamples(defaultTrainingOptions, examples)) {
      // Decaying learning rates
      var r0: Double = defaultTrainingOptions.r0
      var r1: Double = defaultTrainingOptions.r1

      // Keep track of the lowest loss sum we've seen
      var minLossSum: Double = Double.MaxValue
      // Keep track of the best params we've encountered
      var bestParams: StrategyParams[T] = params

      // Break training up into mini-batches
      val numBatches: Int =
        Math.floor(sampleCount / defaultTrainingOptions.miniBatchSize).toInt
      val numEpochs = BinaryRegressionTrainer.adjustNumEpochs(defaultTrainingOptions, numBatches)
      // Train across many epoches
      for (i <- 0 until numEpochs) {
        // sample examples for training
        val shuffledSamples: Seq[T] = Random.shuffle(examples)

        // Compute the total loss across all of the batches
        var lossSum: Double = 0.0
        for (j <- 0 until numBatches) {
          val samples: Seq[T] =
            shuffledSamples.slice(
              j * defaultTrainingOptions.miniBatchSize,
              (j + 1) * defaultTrainingOptions.miniBatchSize)
          val (loss: Double, newParams: StrategyParams[T]) =
            trainMiniBatch(
              params,
              samples,
              defaultTrainingOptions,
              r0,
              r1)
          lossSum += loss
          params = newParams
        }

        // If the current strategy params are the best-performing
        // so far, keep them.
        if (lossSum < minLossSum) {
          minLossSum = lossSum
          bestParams = params
        }

        // If we're in debug mode, print out epoch info
        if (debug) {
          val avgLossSum: Double = lossSum / sampleCount.toDouble
          logger.info(
            s"Epoch $i, lossSum=$lossSum, avgLossSum=$avgLossSum" + bestParams.prettyPrint
          )
        }

        // Decay our learning rates after each epoch
        r0 = r0 * defaultTrainingOptions.rateDecay
        r1 = r1 * defaultTrainingOptions.rateDecay
      }

      // Ensure that our final loss is acceptable. If it is, return the
      // trained params.
      // If it is not, return the final trained strategy params.
      val minAvgLossSum: Double = minLossSum / sampleCount.toDouble
      if (BinaryRegressionTrainer.acceptLoss(minAvgLossSum, defaultTrainingOptions) &&
        bestParams.hasValidValue) {
        (bestParams, minAvgLossSum)
      } else {
        (params, minAvgLossSum)
      }
    } else {
      (params, BinaryRegressionTrainer.DefaultParamLoss)
    }
  }

  /**
    * Given training samples, initialize strategy params.
    * If `$initialize_from_global_prior` is set to false, load the initial
    * strategy params in from the param output of the prior DS.
    * If it is set to true (default) it will use the global prior, according to the StrategyParams
    *
    * @param hc              HiveContext
    * @param config          base config object
    * @param rawTrainingData (id, [TrainingData])
    * @param trainingOptions options for training
    * @return
    */
  def joinTrainingSamplesWithParams(
      hc: HiveContext,
      config: Config,
      rawTrainingData: RDD[(String, Seq[T])],
      trainingOptions: TrainingOptions
  )(implicit c: ClassTag[T]):
  RDD[(String, (Seq[T], Option[StrategyParams[T]]))] = {
    // Filter out training datas which don't have enough examples for an effective
    // training
    val trainingSamples: RDD[(String, Seq[T])] =
      rawTrainingData
        .filter(x => DataLoadingRules.isEnoughSamplesToTrain(x._2))

    // If initializeFromGlobalPrior is true, we initialize the model using global prior.
    // Otherwise, we initialize the model using previous day's output.
    val initializeFromGlobalPrior: Boolean =
      Try(config.getBoolean("initialize_from_global_prior")).getOrElse(true)

    if (initializeFromGlobalPrior) {
      val emptyStrategyParamInput: Option[StrategyParams[T]] = None
      trainingSamples
        .mapValues(sample => (sample, emptyStrategyParamInput))
    } else {
      // initialize using previous day's output
      val dsEval: String = config.getString("ds_eval")
      val paramsQuery: String = config.getString("params_query")
      val params: RDD[(String, StrategyParams[T])] =
        loadParamsFromHive(
          hc,
          // Substitute in a new value for $DS_EVAL to get the prior day's params
          paramsQuery.replace("$DS_EVAL", PipelineUtil.dateMinus(dsEval, 1)))

      // Join yesterday's params with today's training data
      trainingSamples.leftOuterJoin(params)
    }
  }

  /**
    * Given a batch of training samples, compute a round of training.
    * This includes computing the collective loss and param gradients
    * across all of the samples.
    *
    * @param params  strategy params to base scoring on
    * @param samples training samples in the mini-batch
    * @param options training options
    * @param r0      learning rate r0
    * @param r1      learning rate r1
    * @return
    */
  def trainMiniBatch(
      params: StrategyParams[T],
      samples: Seq[T],
      options: TrainingOptions,
      r0: Double,
      r1: Double
  ): (Double, StrategyParams[T]) = {
    var lossSum: Double = 0.0
    val gradSum: Array[Double] =
      Array.fill[Double](params.params.length)(0)

    // For each of the samples, compute loss and gradient
    samples
      .foreach(example => {
        val (loss: Double, grad: Double) =
          getLossAndGradient(example, params, options)
        val gradUpdate: Array[Double] =
          params.computeGradient(grad, example)
        // Update our gradient array
        updateGradientSum(
          r0,
          r1,
          options,
          example,
          gradUpdate,
          gradSum)

        // Keep a loss total
        lossSum += loss
      })

    (lossSum, params.updatedParams(gradSum, options))
  }

  /**
    * Given current gradients and an array of update gradients,
    * update the gradients in-place on the `gradients` array.
    *
    * @param r0              learning rate r0
    * @param r1              learning rate r1
    * @param options         training options
    * @param example         the sample to
    * @param updateGradients gradient deltas for updating `gradients`
    * @param gradients       mutable gradients array to update in-place
    */
  def updateGradientSum(
      r0: Double,
      r1: Double,
      options: TrainingOptions,
      example: T,
      updateGradients: Array[Double],
      gradients: Array[Double]
  ): Unit = {
    // Ensure that our existing gradients and our updates have
    // the same number of params
    assert(
      updateGradients.length == gradients.length,
      s"${updateGradients.length}, ${gradients.length}")

    // Update each of the param gradients using the update array
    if (BinaryRegressionTrainer.validGradient(gradients)) {
      val learningRate: Double =
        getLearningRate(r0, r1, example, options)
      for (i <- gradients.indices) {
        gradients(i) += learningRate * updateGradients(i)
      }
    }
  }

  /**
    * Given a training sample, score it and get the loss and gradient
    * for it, given the passed-in model params.
    *
    * @param example training sample
    * @param params  current strategy params
    * @param options training options
    * @return (loss, gradient)
    */
  def getLossAndGradient(
      example: T,
      params: StrategyParams[T],
      options: TrainingOptions
  ): (Double, Double) = {
    // get loss and the gradient of loss w.r.t to model score
    val score: Double = params.score(example)
    var absLoss: Double = 0.0
    var grad: Double = 0.0

    // optimal value should lie in [lowerBound, upperBound]
    val lowerBound: Double = example.getLowerBound(options)
    lazy val upperBound: Double = example.getUpperBound(options)
    if (score < lowerBound) {
      absLoss += lowerBound - score
      grad -= 1.0
    } else if (score > upperBound) {
      absLoss += score - upperBound
      grad += 1.0
    } else {
      // no loss
    }

    // if `maxAvgLossRatio` is set and valid, compute loss as
    // a ratio of the `pivotValue`.
    if (options.maxAvgLossRatio > 0) {
      (absLoss / example.scoringPivot, grad)
    } else {
      (absLoss, grad)
    }
  }

  /**
    * Get params from an Option[StrategyParams], falling back to the
    * default specified in training options if not present.
    *
    * @param paramsOpt       strategy params
    * @param trainingOptions training options with a default
    * @return
    */
  protected def getOrDefaultParams(
      paramsOpt: Option[StrategyParams[T]],
      trainingOptions: TrainingOptions
  ): StrategyParams[T] = {
    if (paramsOpt.isDefined) {
      paramsOpt.get
    } else {
      getDefaultParams(trainingOptions)
    }
  }
}

object BinaryRegressionTrainer extends ScalaLogging {

  // TODO move it to config
  private final val MaxAvgLossSum      : Int    = 1000
  private final val DefaultParamLoss   : Double = -1
  private final val MinEpochs          : Int    = 10
  private final val MAXEpochSampleCount: Int    = 2000

  /**
    * Given StrategyParams, evaluate a sample
    *
    * @param example sample to evaluate
    * @param params  trained params to use
    * @param ratio   unused
    * @return
    */
  def evalExample[T <: BinaryTrainingSample](
      example: T,
      params: StrategyParams[T],
      // ratio indicates relative weights assigned to positive labels.
      ratio: Double
  ): Double = {
    val prediction: Double = params.score(example)
    example.lossRatioWithPrediction(prediction, ratio)
  }

  /**
    * Given params and an evaluation data set, compute our performance metrics.
    *
    * @param evalExamples evaluation data set
    * @param params       trained strategy params
    * @return a populated BinaryMetrics instance
    */
  def getMetrics[T <: BinaryTrainingSample](
      evalExamples: Seq[T],
      params: StrategyParams[T]
  ): BinaryMetrics = {
    val byKey: Seq[((Boolean, Boolean), Double)] =
      evalExamples
        .map { example: T =>
          val prediction: Double = params.score(example)
          val predictionLower: Boolean = example.predictionLower(prediction)
          val predictionIncrease: Double = example.predictionIncrease(prediction)
          (example.label, predictionLower) -> predictionIncrease
        }

    val results: Map[(Boolean, Boolean), (Int, Double)] =
      byKey
        // Group by key
        .groupBy(_._1)
        .map {
          case (key: (Boolean, Boolean), predictions: Seq[((Boolean, Boolean), Double)]) => {
            val count: Int = predictions.length
            val sum: Double = predictions.map(_._2).sum
            (key, (count, sum))
          }
        }

    // Get the regret cost at the 50th and 75th percentiles.
    trueRegret(byKey, List(0.50, 0.75)) match {
      case Seq(regret50: Double, regret75: Double) =>
        // Use them to compute our eval metrics
      {
        BinaryMetrics.computeEvalMetricFromCounts(results, regret50, regret75)
      }
    }
  }

  /**
    * Calculate true regret of the prediction
    *
    * @param predictions          evaluation predictions to find regret from
    * @param percentilesToCompute ie, [0.25, 0.5, 0.75]
    * @return the true regret at the requested percentiles
    */
  def trueRegret(
      // ((label, predictionLower), predictionIncrease)
      predictions: Seq[((Boolean, Boolean), Double)],
      percentilesToCompute: List[Double]
  ): List[Double] = {
    // Filter out examples where label is true but prediction was lower
    val regret: Seq[Double] =
      predictions
        .filter {
          case ((label: Boolean, predictionLower: Boolean), _) => {
            label && predictionLower
          }
        }
        .map(_._2)

    // If we have examples remaining, retrieve their regret at the requested percentiles
    if (regret.nonEmpty) {
      percentilesToCompute
        .map { percentile: Double =>
          val pos: Int = (percentile * regret.length.toDouble).floor.toInt
          Sort.quickSelect(regret, pos)
        }
    } else {
      List.fill(percentilesToCompute.length)(0)
    }
  }

  def enoughTrueSamples[T <: BinaryTrainingSample](options: TrainingOptions, examples: Seq[T]):
  Boolean = {
    val count = options.minTrueLabelCount
    if (count == 0) {
      true
    } else {
      examples.count(_.label) >= count
    }
  }

  private def validGradient(gradients: Array[Double]): Boolean = {
    gradients.forall(!_.isNaN)
  }

  /**
    * Is this loss acceptable?
    * If we've defined a valid maxAvgLossRatio, we compare it as a per-sample
    * ratio. If we haven't defined it, it's compared to a total count.
    *
    * @param loss   loss ratio or loss sum to check
    * @param option training options
    * @return true if the loss is within acceptable bounds
    */
  private def acceptLoss(loss: Double, option: TrainingOptions): Boolean = {
    if (option.maxAvgLossRatio > 0) {
      loss <= option.maxAvgLossRatio
    } else {
      loss <= BinaryRegressionTrainer.MaxAvgLossSum
    }
  }

  def getTraining[T <: BinaryTrainingSample](
      hc: HiveContext,
      trainingData: TrainingData[T],
      config: TrainingConfig,
      isEnoughSamplesToTrain: Seq[T] => Boolean
  )(implicit c: ClassTag[T]): RDD[(String, Seq[T])] = {
    logger.info("Loading training data")
    trainingData.loadDataFromHive(hc, config.trainingDataQuery)
      .filter(x => isEnoughSamplesToTrain(x._2))
      // Shuffle distributes data evenly and with each partition has a lot less data
      // executor is less likely to spill. If you have 500+ executor cores, it is always
      // good to shuffle. Otherwise the cost of shuffling might be big enough and the lack
      // of parallelism makes it not worth it.
      //
      // NB: If uniform sampling is performed via simple mod, caution should be exercised here
      // to make sure the hashcode can be uniformed distributed.
      // For example, the current implementation is a String based hashcode which would not
      // correlate
      // with simple mod on id_listing.
      // However, if we switch to Long based key, then the repartition number should be co-prime
      // with modular used in sampling.
      .coalesce(config.partitions, config.shuffle)
  }

  def saveAndEvalModelOutput[T <: BinaryTrainingSample](
      hc: HiveContext,
      result: RDD[ModelOutput[T]],
      searchConfig: BaseSearchConfig
  ): Unit = {
    // Ensure that the incoming RDD is persisted, otherwise this method will
    // force recomputations and have poor performance.
    assert(
      result.getStorageLevel != StorageLevel.NONE,
      "`result` RDD must be persisted outside of this method or it may force re-training."
    )

    // Save the training results
    ModelOutput.save(hc, result, searchConfig.table, searchConfig.partition)

    // Log evaluation metrics
    logger.info(BinaryMetrics.metricsHeader)
    logger.info(
      "evalMetrics: " +
        BinaryMetrics.combineEvalMetricFromRDD(result.map(_.evalMetrics)).toString)
    logger.info(
      "holdoutMetrics: " +
        BinaryMetrics.combineEvalMetricFromRDD(result.map(_.holdoutMetrics)).toString)

    // TODO make it configurable
    BinaryRegressionTrainer.computeStats(result)
  }

  private def computeStats[T <: BinaryTrainingSample](result: RDD[ModelOutput[T]]) = {
    val statsData = result.map { x => {
      (Vectors.dense(x.params.params), Vectors.dense(x.options.toArray.take(4)))
    }
    }
    val paramStats = Statistics.colStats(statsData.map(x => x._1))
    val paramColmean = paramStats.mean.toArray.mkString(",")
    val paramColVariance = paramStats.variance.toArray.mkString(",")
    logger.info("paramsMean: " + paramColmean)
    logger.info("paramsVariance: " + paramColVariance)

    // we only get stats for hyper params: trueLowerBound, falseUpperBound, falseLowerBound, trueUpperBound
    val optionStats = Statistics.colStats(statsData.map(x => x._2))
    val optionColmean = optionStats.mean.toArray.mkString(",")
    val optionColVariance = optionStats.variance.toArray.mkString(",")
    logger.info("optionsMean: " + optionColmean)
    logger.info("optionsVariance: " + optionColVariance)
  }

  def adjustNumEpochs(defaultTrainingOptions: TrainingOptions, numBatches: Int): Int = {
    val maxBatchesCount = MAXEpochSampleCount /
      defaultTrainingOptions.miniBatchSize
    if (numBatches > maxBatchesCount) {
      val d = numBatches / maxBatchesCount
      math.max(MinEpochs, defaultTrainingOptions.numEpochs / d)
    } else {
      defaultTrainingOptions.numEpochs
    }
  }
}


text: console.log('Kageyama Tobio');


text:
<!DOCTYPE html>

  <meta charset="utf-8" />

  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

  <title>index</title>
  <meta name="description" content="" />
  <meta name="author" content="Charlie" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

Open in Chrome debugger, turn to the console page.

View the source


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JavaScript Engine testing utilities.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corp.
 * Portions created by the Initial Developer are Copyright (C) 2002
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   george@vanous.com, igor@icesoft.no, pschwartau@netscape.com
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/*
 *
 * Date:    19 September 2002
 * SUMMARY: Testing Array.prototype.concat()
 * See http://bugzilla.mozilla.org/show_bug.cgi?id=169795
 *
 */
//-----------------------------------------------------------------------------
var UBound = 0;
var BUGNUMBER = 169795;
var summary = 'Testing Array.prototype.concat()';
var status = '';
var statusitems = [];
var actual = '';
var actualvalues = [];
var expect= '';
var expectedvalues = [];
var x;

status = inSection(1);
x = "Hello";
actual = [].concat(x).toString();
expect = x.toString();
addThis();

status = inSection(2);
x = 999;
actual = [].concat(x).toString();
expect = x.toString();
addThis();

status = inSection(3);
x = /Hello/g;
actual = [].concat(x).toString();
expect = x.toString();
addThis();

status = inSection(4);
x = new Error("Hello");
actual = [].concat(x).toString();
expect = x.toString();
addThis();

status = inSection(5);
x = function() {return "Hello";};
actual = [].concat(x).toString();
expect = x.toString();
addThis();

status = inSection(6);
x = [function() {return "Hello";}];
actual = [].concat(x).toString();
expect = x.toString();
addThis();

status = inSection(7);
x = [1,2,3].concat([4,5,6]);
actual = [].concat(x).toString();
expect = x.toString();
addThis();

status = inSection(8);
x = eval('this');
actual = [].concat(x).toString();
expect = x.toString();
addThis();

/*
 * The next two sections are by igor@icesoft.no; see
 * http://bugzilla.mozilla.org/show_bug.cgi?id=169795#c3
 */
status = inSection(9);
x={length:0};
actual = [].concat(x).toString();
expect = x.toString();
addThis();

status = inSection(10);
x={length:2, 0:0, 1:1};
actual = [].concat(x).toString();
expect = x.toString();
addThis();

//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------

function addThis()
{
  statusitems[UBound] = status;
  actualvalues[UBound] = actual;
  expectedvalues[UBound] = expect;
  UBound++;
}

function test()
{
  enterFunc('test');
  printBugNumber(BUGNUMBER);
  printStatus(summary);

  for (var i=0; i<UBound; i++)
  {
    reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]);
  }

  exitFunc ('test');
}


text:
package org.cordovastudio.editors.designer.designSurface;

import org.cordovastudio.editors.designer.model.RadComponent;
import org.cordovastudio.editors.designer.model.RadLayout;
import org.cordovastudio.editors.designer.designSurface.editableArea.IEditableArea;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * @author Alexander Lobas
 */
public interface ICaption {
  @NotNull
  RadLayout getCaptionLayout(IEditableArea mainArea, boolean horizontal);

  @NotNull
  List<RadComponent> getCaptionChildren(IEditableArea mainArea, boolean horizontal);
}


text:
""" Module for easy KMC from python. """

# Copyright (c)  2013  Mikael Leetmaa
#
# This file is part of the KMCLib project distributed under the terms of the
# GNU General Public License version 3, see <http://www.gnu.org/licenses/>.
#

from CoreComponents.KMCLocalConfiguration import KMCLocalConfiguration
from CoreComponents.KMCInteractions import KMCInteractions
from CoreComponents.KMCProcess import KMCProcess
from CoreComponents.KMCConfiguration import KMCConfiguration
from CoreComponents.KMCLattice import KMCLattice
from CoreComponents.KMCLatticeModel import KMCLatticeModel
from CoreComponents.KMCUnitCell import KMCUnitCell
from CoreComponents.KMCControlParameters import KMCControlParameters
from Analysis.OnTheFlyMSD import OnTheFlyMSD
from Analysis.TimeStepDistribution import TimeStepDistribution
from Utilities.SaveAndReadUtilities import KMCInteractionsFromScript
from Utilities.SaveAndReadUtilities import KMCConfigurationFromScript
from PluginInterfaces.KMCRateCalculatorPlugin import KMCRateCalculatorPlugin
from PluginInterfaces.KMCAnalysisPlugin import KMCAnalysisPlugin
from Backend.Backend import MPICommons
from KMCLib.Utilities.Trajectory.XYZTrajectory import XYZTrajectory
from KMCLib.Utilities.Trajectory.Trajectory import Trajectory
from KMCLib.Utilities.Trajectory.CFGTrajectory import CFGTrajectory

__all__ = ['KMCLocalConfiguration', 'KMCInteractions', 'KMCConfiguration',
           'KMCLattice', 'KMCLatticeModel', 'KMCUnitCell',
           'KMCControlParameters', 'KMCInteractionsFromScript',
           'KMCConfigurationFromScript', 'KMCRateCalculatorPlugin',
           'KMCAnalysisPlugin', 'KMCProcess', 'OnTheFlyMSD',
           'TimeStepDistribution', 'MPICommons', 'XYZTrajectory', 'Trajectory', 'CFGTrajectory']

# Trick to initialize and finalize MPI only once.
MPICommons.init()

# Print the header when the module is loaded.
Utilities.PrintUtilities.printHeader()

# Make sure to finalize MPI on exit.
def killme():
    MPICommons.finalize()

import atexit
atexit.register(killme)


text:
//
// (C) Copyright 2015 Martin E. Nordberg III
// Apache 2.0 License
//

package org.steamflake.core.persistence.codeio.codegen.impl;

/**
 * Token representing a decrement to the indentation level.
 */
final class UnindentCodeOutputToken
    extends AbstractCodeOutputToken {

    /**
     * Constructs a new unindent token.
     */
    UnindentCodeOutputToken() {
    }

    @Override
    public int writeText( StringBuilder output, int startingIndent, int spacesPerIndent ) {
        return startingIndent - 1;
    }

}