text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Microsoft.MixedReality.Toolkit.Utilities.Solvers;
using UnityEditor;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Utilities.Editor.Solvers
{
    [CustomEditor(typeof(Follow))]
    [CanEditMultipleObjects]
    public class FollowEditor : SolverInspector
    {
        // Orientation
        private SerializedProperty orientationType;
        private SerializedProperty faceTrackedObjectWhileClamped;
        private SerializedProperty faceUserDefinedTargetTransform;
        private SerializedProperty targetToFace;
        private SerializedProperty pivotAxis;
        private SerializedProperty reorientWhenOutsideParameters;
        private SerializedProperty orientToControllerDeadzoneDegrees;

        // Distance
        private SerializedProperty ignoreDistanceClamp;
        private SerializedProperty minDistance;
        private SerializedProperty maxDistance;
        private SerializedProperty defaultDistance;
        private SerializedProperty verticalMaxDistance;

        // Direction
        private SerializedProperty ignoreAngleClamp;
        private SerializedProperty ignoreReferencePitchAndRoll;
        private SerializedProperty pitchOffset;
        private SerializedProperty angularClampMode;
        private SerializedProperty tetherAngleSteps;
        private SerializedProperty maxViewHorizontalDegrees;
        private SerializedProperty maxViewVerticalDegrees;
        private SerializedProperty boundsScaler;

        private bool orientationFoldout = true;
        private bool distanceFoldout = true;
        private bool directionFoldout = true;

        private Follow solverInBetween;

        protected override void OnEnable()
        {
            base.OnEnable();

            orientationType = serializedObject.FindProperty("orientationType");
            faceTrackedObjectWhileClamped = serializedObject.FindProperty("faceTrackedObjectWhileClamped");
            faceUserDefinedTargetTransform = serializedObject.FindProperty("faceUserDefinedTargetTransform");
            targetToFace = serializedObject.FindProperty("targetToFace");
            pivotAxis = serializedObject.FindProperty("pivotAxis");
            reorientWhenOutsideParameters = serializedObject.FindProperty("reorientWhenOutsideParameters");
            orientToControllerDeadzoneDegrees = serializedObject.FindProperty("orientToControllerDeadzoneDegrees");

            ignoreDistanceClamp = serializedObject.FindProperty("ignoreDistanceClamp");
            minDistance = serializedObject.FindProperty("minDistance");
            maxDistance = serializedObject.FindProperty("maxDistance");
            defaultDistance = serializedObject.FindProperty("defaultDistance");
            verticalMaxDistance = serializedObject.FindProperty("verticalMaxDistance");

            ignoreAngleClamp = serializedObject.FindProperty("ignoreAngleClamp");
            ignoreReferencePitchAndRoll = serializedObject.FindProperty("ignoreReferencePitchAndRoll");
            pitchOffset = serializedObject.FindProperty("pitchOffset");
            angularClampMode = serializedObject.FindProperty("angularClampMode");
            tetherAngleSteps = serializedObject.FindProperty("tetherAngleSteps");
            maxViewHorizontalDegrees = serializedObject.FindProperty("maxViewHorizontalDegrees");
            maxViewVerticalDegrees = serializedObject.FindProperty("maxViewVerticalDegrees");
            boundsScaler = serializedObject.FindProperty("boundsScaler");

            solverInBetween = target as Follow;
        }

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

            serializedObject.Update();

            GUIStyle style = EditorStyles.foldout;
            FontStyle previousStyle = style.fontStyle;
            style.fontStyle = FontStyle.Bold;

            EditorGUILayout.Space();
            orientationFoldout = EditorGUILayout.Foldout(orientationFoldout, "Orientation", true);

            if (orientationFoldout)
            {
                EditorGUILayout.PropertyField(faceUserDefinedTargetTransform);
                if (faceUserDefinedTargetTransform.boolValue)
                {
                    EditorGUILayout.PropertyField(targetToFace);
                    EditorGUILayout.PropertyField(pivotAxis);
                }
                else
                {
                    EditorGUILayout.PropertyField(orientationType);
                    EditorGUILayout.PropertyField(faceTrackedObjectWhileClamped);
                }

                EditorGUILayout.PropertyField(reorientWhenOutsideParameters);
                if (reorientWhenOutsideParameters.boolValue)
                {
                    EditorGUILayout.PropertyField(orientToControllerDeadzoneDegrees);
                }
            }

            EditorGUILayout.Space();
            distanceFoldout = EditorGUILayout.Foldout(distanceFoldout, "Distance", true);

            if (distanceFoldout)
            {
                EditorGUILayout.PropertyField(ignoreDistanceClamp);
                if (!ignoreDistanceClamp.boolValue)
                {
                    EditorGUILayout.PropertyField(minDistance);
                    EditorGUILayout.PropertyField(maxDistance);
                    EditorGUILayout.PropertyField(defaultDistance);
                    EditorGUILayout.PropertyField(verticalMaxDistance);
                }
                else
                {
                    EditorGUILayout.HelpBox("Disable \"Ignore Distance Clamp\" to show options", MessageType.Info);
                }
            }

            EditorGUILayout.Space();
            directionFoldout = EditorGUILayout.Foldout(directionFoldout, "Direction", true);

            if (directionFoldout)
            {
                EditorGUILayout.PropertyField(ignoreAngleClamp);
                if (!ignoreAngleClamp.boolValue)
                {
                    EditorGUILayout.PropertyField(ignoreReferencePitchAndRoll);
                    if (ignoreReferencePitchAndRoll.boolValue)
                    {
                        EditorGUILayout.PropertyField(pitchOffset);
                    }

                    EditorGUILayout.PropertyField(angularClampMode);

                    switch ((Follow.AngularClampType)angularClampMode.enumValueIndex)
                    {
                        case Follow.AngularClampType.AngleStepping:
                            {
                                EditorGUILayout.PropertyField(tetherAngleSteps);
                            }
                            break;
                        case Follow.AngularClampType.ViewDegrees:
                            {
                                EditorGUILayout.PropertyField(maxViewHorizontalDegrees);
                                EditorGUILayout.PropertyField(maxViewVerticalDegrees);
                            }
                            break;

                        case Follow.AngularClampType.RendererBounds:
                        case Follow.AngularClampType.ColliderBounds:
                            {
                                EditorGUILayout.PropertyField(boundsScaler);
                            }
                            break;
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("Disable \"Ignore Angle Clamp\" to show options", MessageType.Info);
                }
            }

            // reset foldouts style
            style.fontStyle = previousStyle;

            serializedObject.ApplyModifiedProperties();
        }
    }
}


text:
"""
funcnet
=======

Related Publications
~~~~~~~~~~~~~~~~~~~~

To do
~~~~~
  - ...

Known Bugs
~~~~~~~~~~
  - ...

"""

from .coupling_analysis import CouplingAnalysis
from .coupling_analysis_pure_python import CouplingAnalysisPurePython
from .event_synchronization import EventSynchronization

redpajama_set_name: RedPajamaGithub


text:
package etcd

import (
	"testing"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/latest"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/storage"
	etcdstorage "k8s.io/kubernetes/pkg/storage/etcd"
	"k8s.io/kubernetes/pkg/tools"
	"k8s.io/kubernetes/pkg/tools/etcdtest"
	"k8s.io/kubernetes/pkg/util"

	"k8s.io/kubernetes/pkg/expapi"

	"github.com/coreos/go-etcd/etcd"
)

func newEtcdStorage(t *testing.T) (*tools.FakeEtcdClient, storage.Interface) {
	fakeEtcdClient := tools.NewFakeEtcdClient(t)
	fakeEtcdClient.TestIndex = true
	etcdStorage := etcdstorage.NewEtcdStorage(fakeEtcdClient, latest.Codec, etcdtest.PathPrefix())
	return fakeEtcdClient, etcdStorage
}

func newStorage(t *testing.T) (*RcREST, *ScaleREST, *tools.FakeEtcdClient, storage.Interface) {
	fakeEtcdClient, etcdStorage := newEtcdStorage(t)
	storage := NewStorage(etcdStorage)
	return storage.ReplicationController, storage.Scale, fakeEtcdClient, etcdStorage
}

var validPodTemplate = api.PodTemplate{
	Template: api.PodTemplateSpec{
		ObjectMeta: api.ObjectMeta{
			Labels: map[string]string{"a": "b"},
		},
		Spec: api.PodSpec{
			Containers: []api.Container{
				{
					Name:            "test",
					Image:           "test_image",
					ImagePullPolicy: api.PullIfNotPresent,
				},
			},
			RestartPolicy: api.RestartPolicyAlways,
			DNSPolicy:     api.DNSClusterFirst,
		},
	},
}

var validReplicas = 8

var validControllerSpec = api.ReplicationControllerSpec{
	Replicas: validReplicas,
	Selector: validPodTemplate.Template.Labels,
	Template: &validPodTemplate.Template,
}

var validController = api.ReplicationController{
	ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "1"},
	Spec:       validControllerSpec,
}

var validScale = expapi.Scale{
	ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test"},
	Spec: expapi.ScaleSpec{
		Replicas: validReplicas,
	},
	Status: expapi.ScaleStatus{
		Replicas: 0,
		Selector: validPodTemplate.Template.Labels,
	},
}

func TestGet(t *testing.T) {
	expect := &validScale

	fakeEtcdClient, etcdStorage := newEtcdStorage(t)

	key := etcdtest.AddPrefix("/controllers/test/foo")
	fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Value:         runtime.EncodeOrDie(latest.Codec, &validController),
				ModifiedIndex: 1,
			},
		},
	}
	storage := NewStorage(etcdStorage).Scale

	obj, err := storage.Get(api.WithNamespace(api.NewContext(), "test"), "foo")
	scale := obj.(*expapi.Scale)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if e, a := expect, scale; !api.Semantic.DeepEqual(e, a) {
		t.Errorf("Unexpected scale: %s", util.ObjectDiff(e, a))
	}
}

func TestUpdate(t *testing.T) {
	fakeEtcdClient, etcdStorage := newEtcdStorage(t)
	storage := NewStorage(etcdStorage).Scale

	key := etcdtest.AddPrefix("/controllers/test/foo")
	fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Value:         runtime.EncodeOrDie(latest.Codec, &validController),
				ModifiedIndex: 1,
			},
		},
	}
	replicas := 12
	update := expapi.Scale{
		ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test"},
		Spec: expapi.ScaleSpec{
			Replicas: replicas,
		},
	}

	_, _, err := storage.Update(api.WithNamespace(api.NewContext(), "test"), &update)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	response, err := fakeEtcdClient.Get(key, false, false)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	var controller api.ReplicationController
	latest.Codec.DecodeInto([]byte(response.Node.Value), &controller)
	if controller.Spec.Replicas != replicas {
		t.Errorf("wrong replicas count expected: %d got: %d", replicas, controller.Spec.Replicas)
	}
}


text:
/* line 1, ../src/css/flash-messages.scss */
.flash-messages {
  margin-top: 15px;
  margin-left: -15px;
  position: absolute;
  z-index: 2000;
}
/* line 6, ../src/css/flash-messages.scss */
.flash-messages .flash-message {
  cursor: pointer;
  transition: 200ms all;
  box-shadow: 3px 3px 10px #acacac;
  opacity: 0.96;
  height: 70px;
}
/* line 12, ../src/css/flash-messages.scss */
.flash-messages .flash-message:hover {
  opacity: 1;
  box-shadow: 3px 3px 10px #6c6c6c;
}
/* line 16, ../src/css/flash-messages.scss */
.flash-messages .flash-message.dismissing {
  transition: 200ms all linear 800ms, 800ms opacity;
  opacity: 0;
  height: 1px;
  margin-bottom: 0px;
  padding-top: 0px;
  padding-bottom: 0px;
}
/* line 24, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert {
  border-radius: 3px;
  color: #ffffff;
}
/* line 27, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert h4 {
  margin: 0px;
  font-weight: 600;
}
/* line 31, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert .icon {
  margin-right: 10px;
}
/* line 34, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert .close {
  color: #000000;
  opacity: 0.2;
  filter: alpha(opacity=20);
}
/* line 38, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert .close:hover {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
/* line 43, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert a {
  color: #ffffff;
  text-decoration: underline;
}
/* line 47, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert.alert-success {
  border-color: #008d4c;
  background-color: #00a65a !important;
}
/* line 51, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert.alert-danger, .flash-messages .flash-message.alert.alert-error {
  border-color: #d73925;
  background-color: #dd4b39 !important;
}
/* line 56, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert.alert-warning {
  border-color: #e08e0b;
  background-color: #f39c12 !important;
}
/* line 60, ../src/css/flash-messages.scss */
.flash-messages .flash-message.alert.alert-info {
  border-color: #00acd6;
  background-color: #00c0ef !important;
}


text:
import os
import json
import re
import pandas
import numpy
import glob
import json
import sys
from natsort import natsorted
from geopmpy import __version__

class AppOutput(object):
    def __init__(self, report_glob=None, trace_glob=None, dir_name='.', verbose=False):
        self._reports = {}
        self._reports_df = pandas.DataFrame()
        self._traces = {}
        self._traces_df = pandas.DataFrame()
        self._all_paths = []
        self._reports_df_list = []
        self._traces_df_list = []
        self._index_tracker = IndexTracker()

        if report_glob == '':
            report_glob = '*report-*'
        if report_glob:
            report_glob = os.path.join(dir_name, report_glob)
            report_files = natsorted(glob.glob(report_glob))
            self._all_paths.extend(report_files)

            if len(report_files) == 0:
                raise RuntimeError('No report files found with pattern {}.'.format(report_glob))

            # Create a dict of <NODE_NAME> : <REPORT_OBJ>; Create DF
            files = 0
            filesize = 0
            for rf in report_files: # Get report count for verbose progress
                filesize += os.stat(rf).st_size
                with open(rf, 'r') as fid:
                    for line in fid:
                        if re.findall(r'Host:', line):
                            files += 1

            filesize = '{}KiB'.format(filesize/1024)
            fileno = 1
            for rf in report_files:
                # Parse the first report
                rr_size = os.stat(rf).st_size
                rr = Report(rf)
                if verbose:
                    sys.stdout.write('\rParsing report file {} of {} ({}).. '.format(fileno, files, filesize))
                    sys.stdout.flush()
                fileno += 1
                self.add_report_df(rr)
                self._reports[rr.get_node_name()] = rr

                # Parse the remaining reports in this file
                while (rr.get_last_offset() != rr_size):
                    rr = Report(rf, rr.get_last_offset())
                    if rr.get_node_name() is not None:
                        self.add_report_df(rr)
                        self._reports[rr.get_node_name()] = rr
                        if verbose:
                            sys.stdout.write('\rParsing report file {} of {} ({})... '.format(fileno, files, filesize))
                            sys.stdout.flush()
                        fileno += 1
                Report.reset_vars() # If we've reached the end of a report, reset the static vars
            if verbose:
                sys.stdout.write('Done.\n')
                sys.stdout.flush()

            if verbose:
                sys.stdout.write('Creating combined reports DF... ')
                sys.stdout.flush()
            self._reports_df = pandas.concat(self._reports_df_list)
            self._reports_df = self._reports_df.sort_index(ascending=True)
            if verbose:
                sys.stdout.write('Done.\n')
                sys.stdout.flush()

        if trace_glob == '':
            trace_glob = '*trace-*'
        if trace_glob:
            trace_glob = os.path.join(dir_name, trace_glob)
            self._index_tracker.reset()
            trace_paths = natsorted(glob.glob(trace_glob))
            self._all_paths.extend(trace_paths)
            # Create a dict of <NODE_NAME> : <TRACE_DATAFRAME>
            fileno = 1
            filesize = 0
            for tp in trace_paths: # Get size of all trace files
                filesize += os.stat(tp).st_size
            filesize = '{}MiB'.format(filesize/1024/1024)
            for tp in trace_paths:
                if verbose:
                    sys.stdout.write('\rParsing trace file {} of {} ({})... '.format(fileno, len(trace_paths), filesize))
                    sys.stdout.flush()
                fileno += 1
                tt = Trace(tp)
                self._traces[tt.get_node_name()] = tt.get_df() # Basic dict assumes one node per trace
                self.add_trace_df(tt) # Handles multiple traces per node
            if verbose:
                sys.stdout.write('Done.\n')
                sys.stdout.flush()
            if verbose:
                sys.stdout.write('Creating combined traces DF... ')
                sys.stdout.flush()
            self._traces_df = pandas.concat(self._traces_df_list)
            self._traces_df = self._traces_df.sort_index(ascending=True)
            if verbose:
                sys.stdout.write('Done.\n')
                sys.stdout.flush()

    def remove_files(self):
        for ff in self._all_paths:
            try:
                os.remove(ff)
            except OSError:
                pass

    def add_report_df(self, rr):
        # Build and index the DF
        rdf = pandas.DataFrame(rr).T.drop('name', 1)
        numeric_cols = ['count', 'energy', 'frequency', 'mpi_runtime', 'runtime']
        rdf[numeric_cols] = rdf[numeric_cols].apply(pandas.to_numeric)

        # Add extra index info
        rdf = rdf.set_index(self._index_tracker.get_multiindex(rr))
        self._reports_df_list.append(rdf)

    def add_trace_df(self, tt):
        tdf = tt.get_df()
        tdf = tdf.set_index(self._index_tracker.get_multiindex(tt))
        self._traces_df_list.append(tdf)

    def get_node_names(self):
        return self._reports.keys()

    def get_report(self, node_name):
        return self._reports[node_name]

    def get_trace(self, node_name):
        return self._traces[node_name]

    def get_report_df(self):
        return self._reports_df

    def get_trace_df(self):
        return self._traces_df

class IndexTracker(object):
    """
    Maintains a dict of what unique indicies have been parsed already.  This is used to keep a count of
    how many times a particular experiment has been performed.  The current unique tuple to identify an
    experiment is:
    (<GEOPM_VERSION>, <PROFILE_NAME>, <POWER_BUDGET> , <TREE_DECIDER>, <LEAF_DECIDER>, <NODE_NAME>)
    """
    def __init__ (self):
        self._run_outputs = {}

    def _check_increment(self, run_output):
        """
        Checks to see if the current run_output has been seen before.  If so, the count is incremented.  Otherwise it is
        stored as 1.
        """
        index = (run_output.get_version(), os.path.basename(run_output.get_profile_name()), run_output.get_power_budget(),
                 run_output.get_tree_decider(), run_output.get_leaf_decider(), run_output.get_node_name())

        if index not in self._run_outputs.keys():
            self._run_outputs[index] = 1
        else:
            self._run_outputs[index] += 1

    def _get_base_index(self, run_output):
        """
        Takes a run_output as input, and returns the unique tuple to identify this run_output in the DataFrame.  Note that
        this method appends the current experiment iteration to the end of the returned tuple.  E.g.:
        >>> self._index_tracker.get_base_index(rr)
        ('0.1.1+dev365gfcda929', 'geopm_test_integration', 170, 'static_policy', 'power_balancing', 'mr-fusion2', 1)
        """
        key = (run_output.get_version(), os.path.basename(run_output.get_profile_name()), run_output.get_power_budget(),
               run_output.get_tree_decider(), run_output.get_leaf_decider(), run_output.get_node_name())

        return key + (self._run_outputs[key], )

    def get_multiindex(self, run_output):
        """
        Returns a multiindex from this run_output.  Used in DataFrame construction.
        """
        self._check_increment(run_output)

        itl = []
        index_names = ['version', 'name', 'power_budget', 'tree_decider', 'leaf_decider', 'node_name', 'iteration']

        if type(run_output) is Report:
            index_names.append('region')
            for region in sorted(run_output.keys()): # Pandas sorts the keys when a DF is created
                itl.append(self._get_base_index(run_output) + (region, )) # Append region to the existing tuple
        else: # Trace file index
            index_names.append('index')
            for ii in range(len(run_output.get_df())): # Append the integer index to the DataFrame index
                itl.append(self._get_base_index(run_output) + (ii, ))

        mi = pandas.MultiIndex.from_tuples(itl, names=index_names)
        return mi

    def reset(self):
        self._run_outputs = {}

class Report(dict):
    _version = None
    _name = None
    _mode = None
    _tree_decider = None
    _leaf_decider = None
    _power_budget = None

    @staticmethod
    def reset_vars():
        (Report._version, Report._profile_name, Report._mode, Report._tree_decider, Report._leaf_decider, Report._power_budget) = \
            None, None, None, None, None, None

    def __init__(self, report_path, offset=0):
        super(Report, self).__init__()
        self._path = report_path
        self._offset = offset
        self._version = None
        self._profile_name = None
        self._mode = None
        self._tree_decider = None
        self._leaf_decider = None
        self._power_budget = None
        self._total_runtime = None
        self._total_energy = None
        self._total_ignore_runtime = None
        self._total_mpi_runtime = None
        self._node_name = None

        found_totals = False
        (region_name, region_id, runtime, energy, frequency, mpi_runtime, count) = None, None, None, None, None, None, None
        float_regex = r'([-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)'

        with open(self._path, 'r') as fid:
            fid.seek(self._offset)
            line = fid.readline()
            while len(line) != 0:
                if self._version is None:
                    match = re.search(r'^##### geopm (\S+) #####$', line)
                    if match is not None:
                        self._version = match.group(1)
                elif self._profile_name is None:
                    match = re.search(r'^Profile: (\S+)$', line)
                    if match is not None:
                        self._profile_name = match.group(1)
                elif self._mode is None:
                    match = re.search(r'^Policy Mode: (\S+)$', line)
                    if match is not None:
                        self._mode = match.group(1)
                elif self._tree_decider is None:
                    match = re.search(r'^Tree Decider: (\S+)$', line)
                    if match is not None:
                        self._tree_decider = match.group(1)
                elif self._leaf_decider is None:
                    match = re.search(r'^Leaf Decider: (\S+)$', line)
                    if match is not None:
                        self._leaf_decider = match.group(1)
                elif self._power_budget is None:
                    match = re.search(r'^Power Budget: (\S+)$', line)
                    if match is not None:
                        self._power_budget = int(match.group(1))
                if self._node_name is None:
                    match = re.search(r'^Host: (\S+)$', line)
                    if match is not None:
                        self._node_name = match.group(1)
                elif region_name is None:
                    match = re.search(r'^Region (\S+) \(([0-9]+)\):', line)
                    if match is not None:
                        region_name = match.group(1)
                        region_id = match.group(2)
                elif runtime is None:
                    match = re.search(r'^\s+runtime.+: ' + float_regex, line)
                    if match is not None:
                        runtime = float(match.group(1))
                elif energy is None:
                    match = re.search(r'^\s+energy.+: ' + float_regex, line)
                    if match is not None:
                        energy = float(match.group(1))
                elif frequency is None:
                    match = re.search(r'^\s+frequency.+: ' + float_regex, line)
                    if match is not None:
                        frequency = float(match.group(1))
                elif mpi_runtime is None:
                    match = re.search(r'^\s+mpi-runtime.+: ' + float_regex, line)
                    if match is not None:
                        mpi_runtime = float(match.group(1))
                elif count is None:
                    match = re.search(r'^\s+count: ' + float_regex, line)
                    if match is not None:
                        count = float(match.group(1))
                        self[region_name] = Region(region_name, region_id, runtime, energy, frequency, mpi_runtime, count)
                        (region_name, region_id, runtime, energy, frequency, mpi_runtime, count) = \
                            None, None, None, None, None, None, None
                if not found_totals:
                    match = re.search(r'^Application Totals:$', line)
                    if match is not None:
                        found_totals = True
                elif self._total_runtime is None:
                    match = re.search(r'\s+runtime.+: ' + float_regex, line)
                    if match is not None:
                        self._total_runtime = float(match.group(1))
                elif self._total_energy is None:
                    match = re.search(r'\s+energy.+: ' + float_regex, line)
                    if match is not None:
                        self._total_energy = float(match.group(1))
                elif self._total_mpi_runtime is None:
                    match = re.search(r'\s+mpi-runtime.+: ' + float_regex, line)
                    if match is not None:
                        self._total_mpi_runtime = float(match.group(1))
                elif self._total_ignore_runtime is None:
                    match = re.search(r'\s+ignore-time.+: ' + float_regex, line)
                    if match is not None:
                        self._total_ignore_runtime = float(match.group(1))
                        break # End of report blob

                line = fid.readline()
            self._offset = fid.tell()

        # Check static vars to see if they were parsed.  if not, use the Report vals
        if self._version is None and Report._version:
            self._version = Report._version
        elif self._version:
            Report._version = self._version
        else:
            raise SyntaxError('Unable to parse version information from report!')
        if self._profile_name is None and Report._profile_name:
            self._profile_name = Report._profile_name
        elif self._profile_name:
            Report._profile_name = self._profile_name
        else:
            raise SyntaxError('Unable to parse name information from report!')
        if self._mode is None and Report._mode:
            self._mode = Report._mode
        elif self._mode:
            Report._mode = self._mode
        else:
            raise SyntaxError('Unable to parse mode information from report!')
        if self._tree_decider is None and Report._tree_decider:
            self._tree_decider = Report._tree_decider
        elif self._tree_decider:
            Report._tree_decider = self._tree_decider
        else:
            raise SyntaxError('Unable to parse tree_decider information from report!')
        if self._leaf_decider is None and Report._leaf_decider:
            self._leaf_decider = Report._leaf_decider
        elif self._leaf_decider:
            Report._leaf_decider = self._leaf_decider
        else:
            raise SyntaxError('Unable to parse leaf_decider information from report!')
        if self._power_budget is None and Report._power_budget:
            self._power_budget = Report._power_budget
        elif self._power_budget:
            Report._power_budget = self._power_budget
        else:
            raise SyntaxError('Unable to parse power_budget information from report!')

        if (len(line) != 0 and (region_name is not None or not found_totals or
            None in (self._total_runtime, self._total_energy, self._total_ignore_runtime, self._total_mpi_runtime))):
            raise SyntaxError('Unable to parse report {} before offset {}: '.format(self._path, self._offset))

    def get_profile_name(self):
        return self._profile_name

    def get_version(self):
        return self._version

    def get_path(self):
        return self._path

    def get_runtime(self):
        return self._total_runtime

    def get_ignore_runtime(self):
        return self._total_ignore_runtime

    def get_mpi_runtime(self):
        return self._total_mpi_runtime

    def get_energy(self):
        return self._total_energy

    def get_node_name(self):
        return self._node_name

    def get_last_offset(self):
        return self._offset

    def get_mode(self):
        return self._mode

    def get_tree_decider(self):
        return self._tree_decider

    def get_leaf_decider(self):
        return self._leaf_decider

    def get_power_budget(self):
        return self._power_budget

class Region(dict):
    def __init__(self, name, rid, runtime, energy, frequency, mpi_runtime, count):
        super(Region, self).__init__()
        self['name'] = name
        self['id'] = rid
        self['runtime'] = float(runtime)
        self['energy'] = float(energy)
        self['frequency'] = float(frequency)
        self['mpi_runtime'] = float(mpi_runtime)
        self['count'] = int(count)

    def __repr__(self):
        template = """\
{name} ({rid})
  runtime     : {runtime}
  energy      : {energy}
  frequency   : {frequency}
  mpi-runtime : {mpi_runtime}
  count       : {count}
"""
        return template.format(name=self['name'],
                               rid=self['id'],
                               runtime=self['runtime'],
                               energy=self['energy'],
                               frequency=self['frequency'],
                               mpi_runtime=self['mpi_runtime'],
                               count=self['count'])

    def __str__(self):
        return self.__repr__()

    def get_name(self):
        return self['name']

    def get_id(self):
        return self['id']

    def get_runtime(self):
        return self['runtime']

    def get_energy(self):
        return self['energy']

    def get_frequency(self):
        return self['frequency']

    def get_mpi_runtime(self):
        return self['mpi_runtime']

    def get_count(self):
        return self['count']

class Trace(object):
    def __init__(self, trace_path):
        self._path = trace_path
        self._df = pandas.read_csv(trace_path, sep='|', comment='#', dtype={'region_id ' : str})
        self._df.columns = list(map(str.strip, self._df[:0])) # Strip whitespace from column names
        self._df['region_id'] = self._df['region_id'].astype(str).map(str.strip) # Strip whitespace from region ID's
        self._version = None
        self._profile_name = None
        self._power_budget = None
        self._tree_decider = None
        self._leaf_decider = None
        self._node_name = None
        self._parse_header(trace_path)

    def __repr__(self):
        return self._df.__repr__()

    def __str__(self):
        return self.__repr__()

    def __getattr__(self, attr):
        return getattr(self._df, attr)

    def __getitem__(self, key):
        return self._df.__getitem__(key)

    def _parse_header(self, trace_path):
        done = False
        out = []
        with open(trace_path) as fid:
            while not done:
                ll = fid.readline()
                if ll.startswith('#'):
                    out.append(ll[1:])
                else:
                    done = True
        out.insert(0, '{')
        out.append('}')
        json_str = ''.join(out)
        dd = json.loads(json_str)
        try:
            self._version = dd['geopm_version']
            self._profile_name = dd['profile_name']
            self._power_budget = dd['power_budget']
            self._tree_decider = dd['tree_decider']
            self._leaf_decider = dd['leaf_decider']
            self._node_name = dd['node_name']
        except KeyError:
            raise SyntaxError('Trace file header could not be parsed!')

    def get_df(self):
        return self._df

    def get_version(self):
        return self._version

    def get_profile_name(self):
        return self._profile_name

    def get_tree_decider(self):
        return self._tree_decider

    def get_leaf_decider(self):
        return self._leaf_decider

    def get_power_budget(self):
        return self._power_budget

    def get_node_name(self):
        return self._node_name

    @staticmethod
    def diff_df(trace_df, column_regex, epoch=True):
        """Diff the DataFrame.

        Since the counters in the trace files are monotonically increasing, a diff must be performed to extract the
        useful data.

        Args:
            trace_df: The multiindexed DataFrame created by the AppOutput class.
            column_regex: A string representing the regex search pattern for the column names to diff.
            epoch: A flag to set whether or not to focus solely on epoch regions.

        Returns:
            pandas.DataFrame: With the diffed columns specified by 'column_regex, and an 'elapsed_time' column.

        Todo:
            * Should I drop everything before the first epoch if 'epoch' is false?
        """
        epoch_rid = '9223372036854775808'

        if epoch:
            tmp_df = trace_df.loc[trace_df['region_id'] == epoch_rid]
        else:
            tmp_df = trace_df

        filtered_df = tmp_df.filter(regex=column_regex)
        filtered_df['elapsed_time'] = tmp_df['seconds']
        filtered_df = filtered_df.diff()
        # The following drops all 0's and the negative sample when traversing between 2 trace files.
        filtered_df = filtered_df.loc[(filtered_df > 0).all(axis=1)]

        # Reset 'index' to be 0 to the length of the unique trace files
        traces_list = []
        for (version, name, power_budget, tree_decider, leaf_decider, node_name, iteration), df in \
            filtered_df.groupby(level=['version', 'name', 'power_budget', 'tree_decider', 'leaf_decider',
                                       'node_name', 'iteration']):
            df = df.reset_index(level='index')
            df['index'] = pandas.Series(numpy.arange(len(df)), index=df.index)
            df = df.set_index('index', append=True)
            traces_list.append(df)

        return pandas.concat(traces_list)

    @staticmethod
    def get_median_df(trace_df, column_regex, config):
        """Extract the median experiment iteration.

        This logic calculates the sum of elapsed times for all of the experiment iterations for all nodes in
        that iteration.  It then extracts the DataFrame for the iteration that is closest to the median.  For
        input DataFrames with a single iteration, the single iteration is returned.

        Args:
            trace_df: The multiindexed DataFrame created by the AppOutput class.
            column_regex: A string representing the regex search pattern for the column names to diff.
            config: The TraceConfig object being used presently.

        Returns:
            pandas.DataFrame: Containing a single experiment iteration.
        """
        diffed_trace_df = Trace.diff_df(trace_df, column_regex)

        idx = pandas.IndexSlice
        et_sums = diffed_trace_df.groupby(level=['iteration'])['elapsed_time'].sum()
        median_index = (et_sums - et_sums.median()).abs().sort_values().index[0]
        median_df = diffed_trace_df.loc[idx[:, :, :, :, :, :, median_index],]
        if config.verbose:
            median_df_index = []
            median_df_index.append(median_df.index.get_level_values('version').unique()[0])
            median_df_index.append(median_df.index.get_level_values('name').unique()[0])
            median_df_index.append(median_df.index.get_level_values('power_budget').unique()[0])
            median_df_index.append(median_df.index.get_level_values('tree_decider').unique()[0])
            median_df_index.append(median_df.index.get_level_values('leaf_decider').unique()[0])
            median_df_index.append(median_df.index.get_level_values('iteration').unique()[0])
            sys.stdout.write('Median DF index = ({})...\n'.format(' '.join(str(s) for s in median_df_index)))
            sys.stdout.flush()
        return median_df

class AppConf(object):
    def __init__(self, path):
        self._path = path
        self._loop_count = 1;
        self._region = []
        self._big_o = []
        self._hostname = []
        self._imbalance = []

    def set_loop_count(self, loop_count):
        self._loop_count = loop_count

    def append_region(self, name, big_o):
        self._region.append(name)
        self._big_o.append(big_o)

    def append_imbalance(self, hostname, imbalance):
        self._hostname.append(hostname)
        self._imbalance.append(imbalance)

    def get_path(self):
        return self._path

    def write(self):
        obj = {'loop-count' : self._loop_count,
               'region' : self._region,
               'big-o' : self._big_o}

        if (self._imbalance and self._hostname):
            obj['imbalance'] = self._imbalance
            obj['hostname'] = self._hostname

        with open(self._path, 'w') as fid:
            json.dump(obj, fid)

class CtlConf(object):
    def __init__(self, path, mode, options):
        self._path = path
        self._mode = mode
        self._options = options

    def set_tree_decider(self, decider):
        self._options['tree_decider'] = decider

    def set_leaf_decider(self, decider):
        self._options['leaf_decider'] = decider

    def set_platform(self, platform):
        self._options['platform'] = platform

    def set_power_budget(self, budget):
        self._options['power_budget'] = budget

    def get_path(self):
        return self._path

    def write(self):
        obj = {'mode' : self._mode,
               'options' : self._options}
        with open(self._path, 'w') as fid:
            json.dump(obj, fid)


text:
#include "emu.h"
#include "tiaintf.h"
#include "tiasound.h"

typedef struct _tia_state tia_state;
struct _tia_state
{
	sound_stream * channel;
	void *chip;
};

INLINE tia_state *get_safe_token(device_t *device)
{
	assert(device != NULL);
	assert(device->type() == TIA);
	return (tia_state *)downcast<legacy_device_base *>(device)->token();
}

static STREAM_UPDATE( tia_update )
{
	tia_state *info = (tia_state *)param;
	tia_process(info->chip, outputs[0], samples);
}

static DEVICE_START( tia )
{
	tia_state *info = get_safe_token(device);

	info->channel = device->machine().sound().stream_alloc(*device, 0, 1, device->clock(), info, tia_update);

	info->chip = tia_sound_init(device->clock(), device->clock(), 16);
	assert_always(info->chip != NULL, "Error creating TIA chip");
}

static DEVICE_STOP( tia )
{
	tia_state *info = get_safe_token(device);
	tia_sound_free(info->chip);
}

WRITE8_DEVICE_HANDLER( tia_sound_w )
{
	tia_state *info = get_safe_token(device);
	info->channel->update();
	tia_write(info->chip, offset, data);
}

/**************************************************************************
 * Generic get_info
 **************************************************************************/

DEVICE_GET_INFO( tia )
{
	switch (state)
	{
		/* --- the following bits of info are returned as 64-bit signed integers --- */
		case DEVINFO_INT_TOKEN_BYTES:					info->i = sizeof(tia_state);			break;

		/* --- the following bits of info are returned as pointers to data or functions --- */
		case DEVINFO_FCT_START:							info->start = DEVICE_START_NAME( tia );		break;
		case DEVINFO_FCT_STOP:							info->stop = DEVICE_STOP_NAME( tia );			break;
		case DEVINFO_FCT_RESET:							/* Nothing */								break;

		/* --- the following bits of info are returned as NULL-terminated strings --- */
		case DEVINFO_STR_NAME:							strcpy(info->s, "TIA");						break;
		case DEVINFO_STR_FAMILY:					strcpy(info->s, "Atari custom");			break;
		case DEVINFO_STR_VERSION:					strcpy(info->s, "1.0");						break;
		case DEVINFO_STR_SOURCE_FILE:						strcpy(info->s, __FILE__);					break;
		case DEVINFO_STR_CREDITS:					strcpy(info->s, "Copyright Nicola Salmoria and the MAME Team"); break;
	}
}

DEFINE_LEGACY_SOUND_DEVICE(TIA, tia);


text:
<?php

namespace SecurePay\XMLAPI\Responses;
use SecurePay\XMLAPI\Utils\Configurations;

/**
 * Reads the XML response from the server.
 *
 * Class Response
 * @author Beng Lim <benglim92@gmail.com>
 * @package SecurePay\XMLAPI\Responses
 */
class Response
{
    /**
     * @var string The status code
     */
    private $statusCode;

    /**
     * @var string The description for the status code
     */
    private $statusDesc;

    /**
     * @var array The actions in the XML API response
     */
    private $actionList;

    /**
     * @var \SimpleXMLElement The DOM for the XML API response.
     */
    private $responseArray;

    /**
     * @var bool Identifies whether our request list was processed.
     */
    private $requestProcessed;

    /**
     * Response constructor.
     * @param string $xmlResponse The XML API response from SecurePay
     */
    public function __construct($xmlResponse)
    {
        $this->requestProcessed = false;
        $this->responseArray = simplexml_load_string($xmlResponse);
        $this->statusCode = strval($this->responseArray->Status->statusCode);
        $this->statusDesc = strval($this->responseArray->Status->statusDescription);
        $this->actionList = [];
        // Checking 0, 00 and 000 as SecurePay can return any of the three variants...
        if ($this->statusCode == "0" ||
            $this->statusCode == "00" ||
            $this->statusCode == "000") {
            $this->requestProcessed = true;
            $path = null;
             if ($this->responseArray->RequestType == "Periodic") {
                $path = $this->responseArray->Periodic->PeriodicList->PeriodicItem;
             } else if ($this->responseArray->RequestType == "Payment") {
                 $path = $this->responseArray->Payment->TxnList->Txn;
             } else if ($this->responseArray->RequestType == "addToken" || $this->responseArray->RequestType == "lookupToken") {
                 $path = $this->responseArray->Token->TokenList->TokenItem;
             }
            foreach ($path as $actionItem) {
                $this->actionList[] = $actionItem;
            }
        }
    }

    /**
     * Returns true if all actions on the list are approved.
     *
     * @return bool If all actions are approved
     */
    public function isAllApproved() {
        if (sizeOf($this->actionList) == 0) {
            return false;
        }
        foreach($this->actionList as $action) {
            $responseCode = strval($action->responseCode);
            if (!in_array($responseCode, Configurations::getConfig("approved_codes"))) {
                return false;
            }
        }
        return true;
    }

    /**
     * Returns the first item in the action list (will usually be the only..)
     *
     * @return null|\SimpleXMLElement
     */
    public function getFirstItem() {
        if (sizeOf($this->actionList) == 0) {
            return null;
        }
        return $this->actionList[0];
    }

    /**
     * Convenience function for checking to see if first action in the request has been approved.
     *
     * @return bool If first request has been approved.
     */
    public function isFirstItemApproved() {
        if (sizeOf($this->actionList) == 0) {
            return false;
        }
        if (isset($this->actionList[0]->responseCode)) {
            $responseCode = strval($this->actionList[0]->responseCode);
            if (in_array($responseCode, Configurations::getConfig("approved_codes"))) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns the transaction's response code.
     *
     * @return null|string The response code
     */
    public function getFirstItemResponseCode() {
        if (!isset($this->actionList[0]->responseCode)) {
            return null;
        }
        return strval($this->actionList[0]->responseCode);
    }

    /**
     * Returns the transaction's response description
     *
     * @return null|string The response description
     */
    public function getFirstItemResponseText() {
        if (!isset($this->actionList[0]->responseText)) {
            return null;
        }
        return strval($this->actionList[0]->responseText);
    }

    /**
     * Returns the transaction's txnID which can be used for refunds subsequently.
     *
     * @return null|string The transaction Id
     */
    public function getFirstItemTxnId() {
        if (!isset($this->actionList[0]->txnID)) {
            return null;
        }
        return strval($this->actionList[0]->txnID);
    }

    /**
     * Returns the preauthID which can be used for complete requests subsequently.
     *
     * @return null|string The preauthorisation Id
     */
    public function getFirstItemPreauthId() {
        if (!isset($this->actionList[0]->preauthID)) {
            return null;
        }
        return strval($this->actionList[0]->preauthID);
    }

    /**
     * Returns the customer reference number of the transaction which can be used to trigger payments at a later date.
     *
     * @return null|string The client Id or customer reference number
     */
    public function getFirstItemClientId() {
        if (!isset($this->actionList[0]->clientID)) {
            return null;
        }
        return strval($this->actionList[0]->clientID);
    }

    /**
     * Returns the token value of a customer's card which can be used to trigger payments at a later date.
     *
     * @return null|string The token value
     */
    public function getFirstItemTokenValue() {
        if (!isset($this->actionList[0]->tokenValue)) {
            return null;
        }
        return strval($this->actionList[0]->tokenValue);
    }

    /**
     * Returns the status code
     *
     * @return string The status code
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }

    /**
     * Returrns The status description
     *
     * @return string The status description
     */
    public function getStatusDesc()
    {
        return $this->statusDesc;
    }

    /**
     * Returns the array of actions in the list. (Usually will only return 1 due to SecurePay's restriction).
     *
     * @return array The action list
     */
    public function getActionList()
    {
        return $this->actionList;
    }

    /**
     * Returns the full XML DOM object from SecurePay's XML API.
     *
     * @return \SimpleXMLElement The XML array object.
     */
    public function getResponseArray()
    {
        return $this->responseArray;
    }

    /**
     * Returns true if the status description was 0 (Normal).
     *
     * @return boolean
     */
    public function isRequestProcessed()
    {
        return $this->requestProcessed;
    }
}


text:
'use strict';

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

import AnimatedInterpolation from './AnimatedInterpolation';
import AnimatedNode from './AnimatedNode';
import AnimatedWithChildren from './AnimatedWithChildren';

var AnimatedDiffClamp =
/*#__PURE__*/
function (_AnimatedWithChildren) {
  _inheritsLoose(AnimatedDiffClamp, _AnimatedWithChildren);

  function AnimatedDiffClamp(a, min, max) {
    var _this;

    _this = _AnimatedWithChildren.call(this) || this;
    _this._a = a;
    _this._min = min;
    _this._max = max;
    _this._value = _this._lastValue = _this._a.__getValue();
    return _this;
  }

  var _proto = AnimatedDiffClamp.prototype;

  _proto.__makeNative = function __makeNative() {
    this._a.__makeNative();

    _AnimatedWithChildren.prototype.__makeNative.call(this);
  };

  _proto.interpolate = function interpolate(config) {
    return new AnimatedInterpolation(this, config);
  };

  _proto.__getValue = function __getValue() {
    var value = this._a.__getValue();

    var diff = value - this._lastValue;
    this._lastValue = value;
    this._value = Math.min(Math.max(this._value + diff, this._min), this._max);
    return this._value;
  };

  _proto.__attach = function __attach() {
    this._a.__addChild(this);
  };

  _proto.__detach = function __detach() {
    this._a.__removeChild(this);

    _AnimatedWithChildren.prototype.__detach.call(this);
  };

  _proto.__getNativeConfig = function __getNativeConfig() {
    return {
      type: 'diffclamp',
      input: this._a.__getNativeTag(),
      min: this._min,
      max: this._max
    };
  };

  return AnimatedDiffClamp;
}(AnimatedWithChildren);

export default AnimatedDiffClamp;


text:
class AddSpiderCountToProjects < ActiveRecord::Migration
  def self.up
  	add_column :projects, :spider_count, :integer, :default=> 0
  end

  def self.down
  	remove_column :projects, :spider_count
  end
end


text:
package com.thinkgem.jeesite.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.process.service.TaskService;
import com.thinkgem.jeesite.modules.sys.entity.CompanyChargeInfo;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.service.CompanyChargeInfoService;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 公司收费Controller
 * @author 俞超
 * @version 2014-12-17
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/companyChargeInfo")
public class CompanyChargeInfoController extends BaseController {

	@Autowired
	private CompanyChargeInfoService companyChargeInfoService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private TaskService taskService;

	@ModelAttribute
	public CompanyChargeInfo get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return companyChargeInfoService.get(id);
		}else{
			return new CompanyChargeInfo();
		}
	}

	@RequestMapping(value = {"list", ""})
	public String list(CompanyChargeInfo companyChargeInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<CompanyChargeInfo> page = companyChargeInfoService.find(new Page<CompanyChargeInfo>(request, response), companyChargeInfo);
        model.addAttribute("page", page);
		return "modules/" + "sys/companyChargeInfoList";
	}

	@RequestMapping(value = "form")
	public String form(CompanyChargeInfo companyChargeInfo, Model model) {
		if (companyChargeInfo.getTaskList()==null){
			//role.setOffice(UserUtils.getUser().getOffice());
		}
		model.addAttribute("taskList", taskService.findAll());
		model.addAttribute("companyChargeInfo", companyChargeInfo);
		return "modules/" + "sys/companyChargeInfoForm";
	}

	@RequestMapping(value = "save")
	public String save(CompanyChargeInfo companyChargeInfo, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (!beanValidator(model, companyChargeInfo)){
			return form(companyChargeInfo, model);
		}
		/*Office office=officeService.get(request.getParameter("company.id"));*/

		companyChargeInfo.setCompany(new Office(request.getParameter("company.id")));
		companyChargeInfoService.save(companyChargeInfo);
		addMessage(redirectAttributes, "保存公司收费成功");
		return "redirect:"+Global.getAdminPath()+"/sys/companyChargeInfo/?repage";
	}

	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		companyChargeInfoService.delete(id);

		addMessage(redirectAttributes, "删除公司收费成功");
		return "redirect:"+Global.getAdminPath()+"/sys/companyChargeInfo/?repage";
	}
	@RequiresUser
	@ResponseBody
	@RequestMapping("treeData")
	public List<Map<String, Object>> treeData(HttpServletResponse response,
			@RequestParam(required = false) Long extId,
			@RequestParam(required = false) Long type,
			@RequestParam(required = false) Long grade) {

		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = Lists.newArrayList();

//		User user = UserUtils.getUser();
		List<Office> list = officeService.findAll();
		for (int i=0; i<list.size(); i++){
			Office e = list.get(i);

			if ((extId == null || (extId!=null && !extId.equals(e.getId()) ))
					&& (type == null || (type != null ))
					&& (grade == null || (grade != null )) &&e.getParent() == null){

				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
//				map.put("pId", !user.isAdmin() && e.getId().equals(user.getOffice().getId())?0:e.getParent()!=null?e.getParent().getId():0);
//              	map.put("pId", e.getParent() != null ? e.getParent().getId() : 0);
				map.put("name", e.getName());
				map.put("open", true);
				mapList.add(map);
			}
		}
		return mapList;
	}

}


text:
<?php

namespace AppBundle\Form\Type;

use AppBundle\Entity\Account;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class AccountType
 */
class AccountType extends AbstractType
{
    /**
     * @inheritDoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'name',
            TextType::class,
            [
                'label'    => 'Account Name',
                'required' => true,
                'attr'     => ['maxlength' => 255],
            ]
        );
        $builder->add(
            'type',
            ChoiceType::class,
            [
                'choices' => [
                    Account::TYPE_CHECKING    => Account::TYPE_CHECKING,
                    Account::TYPE_SAVINGS     => Account::TYPE_SAVINGS,
                    Account::TYPE_CREDIT_CARD => Account::TYPE_CREDIT_CARD,
                ]
            ]
        );
        $builder->add(
            'save',
            SubmitType::class
        );
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => Account::class,
            ]
        );
    }
}


text:
var Manager;

(function ($) {

  $(function () {
    Manager = new AjaxSolr.Manager({
      solrUrl: 'http://evolvingweb.ca/solr/reuters/'
    });
    Manager.addWidget(new AjaxSolr.ResultWidget({
      id: 'result',
      target: '#docs'
    }));
    Manager.addWidget(new AjaxSolr.PagerWidget({
      id: 'pager',
      target: '#pager',
      prevLabel: '<',
      nextLabel: '>',
      innerWindow: 1,
      renderHeader: function (perPage, offset, total) {
        $('#pager-header').html($('').text('displaying ' + Math.min(total, offset + 1) + ' to ' + Math.min(total, offset + perPage) + ' of ' + total));
      }
    }));
    var fields = [ 'topics', 'organisations', 'exchanges' ];
    for (var i = 0, l = fields.length; i < l; i++) {
      Manager.addWidget(new AjaxSolr.TagcloudWidget({
        id: fields[i],
        target: '#' + fields[i],
        field: fields[i]
      }));
    }
    Manager.addWidget(new AjaxSolr.CurrentSearchWidget({
      id: 'currentsearch',
      target: '#selection'
    }));
    Manager.init();
    Manager.store.addByValue('q', '*:*');
    var params = {
      facet: true,
      'facet.field': [ 'topics', 'organisations', 'exchanges' ],
      'facet.limit': 20,
      'facet.mincount': 1,
      'f.topics.facet.limit': 50,
      'json.nl': 'map'
    };
    for (var name in params) {
      Manager.store.addByValue(name, params[name]);
    }
    Manager.doRequest();
  });

})(jQuery);


text:
:- use_module('$REGULUS/PrologLib/utilities').
:- use_module('$REGULUS/PrologLib/batchrec_tools').

:- use_module(library(lists)).
:- use_module(library(system)).
'SICSTUS4ONLY'( ( :- use_module(library(file_systems)) ) ).

update_transcriptions(TranscriptionsFile, ListingsFile, RootDir, NewTranscriptionsFile) :-
	absolute_file_name(TranscriptionsFile, AbsTranscriptionsFile),
	absolute_file_name(ListingsFile, AbsListingsFile),
	absolute_file_name(NewTranscriptionsFile, AbsNewTranscriptionsFile),

	read_file_to_atom_list(AbsListingsFile, WavfilesList),
	length(WavfilesList, NWavfiles),
	format('~N--- Read wavfile listings file (~d elements) ~w~n', [NWavfiles, AbsListingsFile]),

	(   file_exists(AbsTranscriptionsFile) ->
	    parse_transcriptions_file_to_list(AbsTranscriptionsFile, TranscriptionsListIn),
	    length(TranscriptionsListIn, NTranscriptions),
	    format('~N--- Read transcriptions file (~d elements) ~w~n', [NTranscriptions, AbsTranscriptionsFile])
	;
	    otherwise ->
	    TranscriptionsListIn = [],
	    format('~N--- No initial transcriptions file~n', [])

	),

	fill_in_transcriptions_in_wavfile_list(WavfilesList, TranscriptionsListIn, RootDir, TranscriptionsListOut, 0-NOld, 0-NNew),

	write_atom_list_to_file(TranscriptionsListOut, AbsNewTranscriptionsFile),
	format('~N--- Written transcriptions file (~d old elements, ~d new elements) ~w~n', [NOld, NNew, AbsNewTranscriptionsFile]),
	!.

fill_in_transcriptions_in_wavfile_list([], _TranscriptionsListIn, _RootDir, [], OldIn-OldIn, NewIn-NewIn).
fill_in_transcriptions_in_wavfile_list([F | R], TranscriptionsListIn, RootDir, [F1 | R1], OldIn-OldOut, NewIn-NewOut) :-
	fill_in_transcriptions_in_wavfile_list_single(F, TranscriptionsListIn, RootDir, F1, OldIn-OldNext, NewIn-NewNext),
	!,
	fill_in_transcriptions_in_wavfile_list(R, TranscriptionsListIn, RootDir, R1, OldNext-OldOut, NewNext-NewOut).

fill_in_transcriptions_in_wavfile_list_single(Wavfile0, TranscriptionsListIn, RootDir, OutAtom, OldIn-OldOut, NewIn-NewOut) :-
	format_to_atom('~w/~w', [RootDir, Wavfile0], Wavfile1),
	absolute_file_name(Wavfile1, Wavfile),
	(   ( member(transcription(Wavfile, Transcription), TranscriptionsListIn), Transcription \== [] ) ->
	    join_with_spaces([Wavfile1 | Transcription], OutAtom),
	    OldOut is OldIn + 1,
	    NewOut = NewIn
	;
	    get_transcription_from_wavfile(Wavfile, WavfileTranscription) ->
	    join_with_spaces([Wavfile1 | WavfileTranscription], OutAtom),
	    OldOut = OldIn,
	    NewOut is NewIn + 1
	;
	    otherwise ->
	    OutAtom = Wavfile1,
	    OldOut = OldIn,
	    NewOut is NewIn + 1
	),
	!.


text:
#include <aws/ec2/model/DeleteTagsRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::EC2::Model;
using namespace Aws::Utils;

DeleteTagsRequest::DeleteTagsRequest() :
    m_dryRun(false),
    m_dryRunHasBeenSet(false),
    m_resourcesHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

Aws::String DeleteTagsRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DeleteTags&";
  if(m_dryRunHasBeenSet)
  {
    ss << "DryRun=" << std::boolalpha << m_dryRun << "&";
  }

  if(m_resourcesHasBeenSet)
  {
    unsigned resourcesCount = 1;
    for(auto& item : m_resources)
    {
      ss << "ResourceId." << resourcesCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      resourcesCount++;
    }
  }

  if(m_tagsHasBeenSet)
  {
    unsigned tagsCount = 1;
    for(auto& item : m_tags)
    {
      item.OutputToStream(ss, "Tag.", tagsCount, "");
      tagsCount++;
    }
  }

  ss << "Version=2016-11-15";
  return ss.str();
}

void  DeleteTagsRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
"use strict";

var paths = require('./paths'),
    Args = require('./args'),
    Document = require('./document'),
    _ = require('lodash');

module.exports = function() {
    var args = Args(arguments);
    var modify = args.last();

    if (_.startsWith(_.trim(args.first()), '<'))
    {
        var document = Document.load(args.first());
        modify(document, {});
        return document.toString();
    }
    else
    {
        var files = args.applyLeading(paths.expand);

        files.forEach(function(file) {
            var document = Document.open(file.path);
            modify(document, file.context);
            document.save();
        });
    }
};

module.exports.XmlString = Document.XmlString;
module.exports.CDataValue = Document.CDataValue;


text:
import unittest

from airflow.contrib.operators.bigquery_operator import \
    BigQueryCreateExternalTableOperator, BigQueryCreateEmptyTableOperator, \
    BigQueryDeleteDatasetOperator, BigQueryCreateEmptyDatasetOperator, \
    BigQueryOperator

try:
    from unittest import mock
except ImportError:
    try:
        import mock
    except ImportError:
        mock = None

TASK_ID = 'test-bq-create-table-operator'
TEST_DATASET = 'test-dataset'
TEST_PROJECT_ID = 'test-project'
TEST_TABLE_ID = 'test-table-id'
TEST_GCS_BUCKET = 'test-bucket'
TEST_GCS_DATA = ['dir1/*.csv']
TEST_SOURCE_FORMAT = 'CSV'

class BigQueryCreateEmptyTableOperatorTest(unittest.TestCase):

    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryCreateEmptyTableOperator(task_id=TASK_ID,
                                                    dataset_id=TEST_DATASET,
                                                    project_id=TEST_PROJECT_ID,
                                                    table_id=TEST_TABLE_ID)

        operator.execute(None)
        mock_hook.return_value \
            .get_conn() \
            .cursor() \
            .create_empty_table \
            .assert_called_once_with(
                dataset_id=TEST_DATASET,
                project_id=TEST_PROJECT_ID,
                table_id=TEST_TABLE_ID,
                schema_fields=None,
                time_partitioning={},
                labels=None
            )

class BigQueryCreateExternalTableOperatorTest(unittest.TestCase):

    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryCreateExternalTableOperator(
            task_id=TASK_ID,
            destination_project_dataset_table='{}.{}'.format(
                TEST_DATASET, TEST_TABLE_ID
            ),
            schema_fields=[],
            bucket=TEST_GCS_BUCKET,
            source_objects=TEST_GCS_DATA,
            source_format=TEST_SOURCE_FORMAT
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn() \
            .cursor() \
            .create_external_table \
            .assert_called_once_with(
                external_project_dataset_table='{}.{}'.format(
                    TEST_DATASET, TEST_TABLE_ID
                ),
                schema_fields=[],
                source_uris=['gs://{}/{}'.format(TEST_GCS_BUCKET, source_object)
                             for source_object in TEST_GCS_DATA],
                source_format=TEST_SOURCE_FORMAT,
                compression='NONE',
                skip_leading_rows=0,
                field_delimiter=',',
                max_bad_records=0,
                quote_character=None,
                allow_quoted_newlines=False,
                allow_jagged_rows=False,
                src_fmt_configs={},
                labels=None
            )

class BigQueryDeleteDatasetOperatorTest(unittest.TestCase):
    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryDeleteDatasetOperator(
            task_id=TASK_ID,
            dataset_id=TEST_DATASET,
            project_id=TEST_PROJECT_ID
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn() \
            .cursor() \
            .delete_dataset \
            .assert_called_once_with(
                dataset_id=TEST_DATASET,
                project_id=TEST_PROJECT_ID
            )

class BigQueryCreateEmptyDatasetOperatorTest(unittest.TestCase):
    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryCreateEmptyDatasetOperator(
            task_id=TASK_ID,
            dataset_id=TEST_DATASET,
            project_id=TEST_PROJECT_ID
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn() \
            .cursor() \
            .create_empty_dataset \
            .assert_called_once_with(
                dataset_id=TEST_DATASET,
                project_id=TEST_PROJECT_ID,
                dataset_reference={}
            )

class BigQueryOperatorTest(unittest.TestCase):
    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryOperator(
            task_id=TASK_ID,
            sql='Select * from test_table',
            destination_dataset_table=None,
            write_disposition='WRITE_EMPTY',
            allow_large_results=False,
            flatten_results=None,
            bigquery_conn_id='bigquery_default',
            udf_config=None,
            use_legacy_sql=True,
            maximum_billing_tier=None,
            maximum_bytes_billed=None,
            create_disposition='CREATE_IF_NEEDED',
            schema_update_options=(),
            query_params=None,
            labels=None,
            priority='INTERACTIVE',
            time_partitioning=None,
            api_resource_configs=None,
            cluster_fields=None,
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn() \
            .cursor() \
            .run_query \
            .assert_called_once_with(
                sql='Select * from test_table',
                destination_dataset_table=None,
                write_disposition='WRITE_EMPTY',
                allow_large_results=False,
                flatten_results=None,
                udf_config=None,
                maximum_billing_tier=None,
                maximum_bytes_billed=None,
                create_disposition='CREATE_IF_NEEDED',
                schema_update_options=(),
                query_params=None,
                labels=None,
                priority='INTERACTIVE',
                time_partitioning=None,
                api_resource_configs=None,
                cluster_fields=None,
            )

    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_bigquery_operator_defaults(self, mock_hook):
        operator = BigQueryOperator(
            task_id=TASK_ID,
            sql='Select * from test_table',
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn() \
            .cursor() \
            .run_query \
            .assert_called_once_with(
                sql='Select * from test_table',
                destination_dataset_table=None,
                write_disposition='WRITE_EMPTY',
                allow_large_results=False,
                flatten_results=None,
                udf_config=None,
                maximum_billing_tier=None,
                maximum_bytes_billed=None,
                create_disposition='CREATE_IF_NEEDED',
                schema_update_options=(),
                query_params=None,
                labels=None,
                priority='INTERACTIVE',
                time_partitioning=None,
                api_resource_configs=None,
                cluster_fields=None,
            )


text:
package org.apache.beam.runners.direct;

import java.util.concurrent.ExecutorService;

/**
 * A factory that creates {@link ExecutorService ExecutorServices}. {@link ExecutorService
 * ExecutorServices} created by this factory should be independent of one another (e.g., if any
 * executor is shut down the remaining executors should continue to process work).
 */
interface ExecutorServiceFactory {
  /** Create a new {@link ExecutorService}. */
  ExecutorService create();
}


text:
package org.apache.tuscany.sdo.model.impl;

import commonj.sdo.Sequence;

import java.util.Collection;
import java.util.List;

import org.apache.tuscany.sdo.impl.DataObjectBase;

import org.apache.tuscany.sdo.model.ModelFactory;
import org.apache.tuscany.sdo.model.Property;
import org.apache.tuscany.sdo.model.Type;

/**
 *
 * An implementation of the model object 'Property'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#getAliasName Alias Name}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#getAny Any}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#getName Name}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#isMany Many}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#isContainment Containment}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#getDefault Default}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#isReadOnly Read Only}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#getType_ Type}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#getOpposite Opposite}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#isNullable Nullable}

 *
{@link org.apache.tuscany.sdo.model.impl.PropertyImpl#getAnyAttribute Any Attribute}

 *

 *

 *
 * @generated
 */
public class PropertyImpl extends DataObjectBase implements Property
{

  public final static int ALIAS_NAME = 0;

  public final static int ANY = -1;

  public final static int NAME = 1;

  public final static int MANY = 2;

  public final static int CONTAINMENT = 3;

  public final static int DEFAULT = 4;

  public final static int READ_ONLY = 5;

  public final static int TYPE = 6;

  public final static int OPPOSITE = 7;

  public final static int NULLABLE = 8;

  public final static int ANY_ATTRIBUTE = -2;

  public final static int SDO_PROPERTY_COUNT = 9;

  public final static int EXTENDED_PROPERTY_COUNT = -2;

  /**
   * The internal feature id for the 'Alias Name' attribute list.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_ALIAS_NAME = 0;

  /**
   * The internal feature id for the 'Any' attribute list.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_ANY = 1;

  /**
   * The internal feature id for the 'Name' attribute.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_NAME = 2;

  /**
   * The internal feature id for the 'Many' attribute.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_MANY = 3;

  /**
   * The internal feature id for the 'Containment' attribute.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_CONTAINMENT = 4;

  /**
   * The internal feature id for the 'Default' attribute.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_DEFAULT = 5;

  /**
   * The internal feature id for the 'Read Only' attribute.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_READ_ONLY = 6;

  /**
   * The internal feature id for the 'Type' reference.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_TYPE = 7;

  /**
   * The internal feature id for the 'Opposite' reference.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_OPPOSITE = 8;

  /**
   * The internal feature id for the 'Nullable' attribute.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_NULLABLE = 9;

  /**
   * The internal feature id for the 'Any Attribute' attribute list.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_ANY_ATTRIBUTE = 10;

  /**
   * The number of properties for this type.
   *
   *
   * @generated
   * @ordered
   */
  public final static int INTERNAL_PROPERTY_COUNT = 11;

  protected int internalConvertIndex(int internalIndex)
  {
    switch (internalIndex)
    {
      case INTERNAL_ALIAS_NAME: return ALIAS_NAME;
      case INTERNAL_ANY: return ANY;
      case INTERNAL_NAME: return NAME;
      case INTERNAL_MANY: return MANY;
      case INTERNAL_CONTAINMENT: return CONTAINMENT;
      case INTERNAL_DEFAULT: return DEFAULT;
      case INTERNAL_READ_ONLY: return READ_ONLY;
      case INTERNAL_TYPE: return TYPE;
      case INTERNAL_OPPOSITE: return OPPOSITE;
      case INTERNAL_NULLABLE: return NULLABLE;
      case INTERNAL_ANY_ATTRIBUTE: return ANY_ATTRIBUTE;
    }
    return super.internalConvertIndex(internalIndex);
  }

  /**
   * The cached value of the '{@link #getAliasName() Alias Name}' attribute list.
   *
   *
   * @see #getAliasName()
   * @generated
   * @ordered
   */

  protected List aliasName = null;

  /**
   * The cached value of the '{@link #getAny() Any}' attribute list.
   *
   *
   * @see #getAny()
   * @generated
   * @ordered
   */

  protected Sequence any = null;

  /**
   * The default value of the '{@link #getName() Name}' attribute.
   *
   *
   * @see #getName()
   * @generated
   * @ordered
   */
  protected static final String NAME_DEFAULT_ = null;

  /**
   * The cached value of the '{@link #getName() Name}' attribute.
   *
   *
   * @see #getName()
   * @generated
   * @ordered
   */
  protected String name = NAME_DEFAULT_;

  /**
   * This is true if the Name attribute has been set.
   *
   *
   * @generated
   * @ordered
   */
  protected boolean name_set_ = false;

  /**
   * The default value of the '{@link #isMany() Many}' attribute.
   *
   *
   * @see #isMany()
   * @generated
   * @ordered
   */
  protected static final boolean MANY_DEFAULT_ = false;

  /**
   * The cached value of the '{@link #isMany() Many}' attribute.
   *
   *
   * @see #isMany()
   * @generated
   * @ordered
   */
  protected boolean many = MANY_DEFAULT_;

  /**
   * This is true if the Many attribute has been set.
   *
   *
   * @generated
   * @ordered
   */
  protected boolean many_set_ = false;

  /**
   * The default value of the '{@link #isContainment() Containment}' attribute.
   *
   *
   * @see #isContainment()
   * @generated
   * @ordered
   */
  protected static final boolean CONTAINMENT_DEFAULT_ = false;

  /**
   * The cached value of the '{@link #isContainment() Containment}' attribute.
   *
   *
   * @see #isContainment()
   * @generated
   * @ordered
   */
  protected boolean containment = CONTAINMENT_DEFAULT_;

  /**
   * This is true if the Containment attribute has been set.
   *
   *
   * @generated
   * @ordered
   */
  protected boolean containment_set_ = false;

  /**
   * The default value of the '{@link #getDefault_() Default}' attribute.
   *
   *
   * @see #getDefault_()
   * @generated
   * @ordered
   */
  protected static final String DEFAULT_DEFAULT_ = null;

  /**
   * The cached value of the '{@link #getDefault_() Default}' attribute.
   *
   *
   * @see #getDefault_()
   * @generated
   * @ordered
   */
  protected String default_ = DEFAULT_DEFAULT_;

  /**
   * This is true if the Default attribute has been set.
   *
   *
   * @generated
   * @ordered
   */
  protected boolean default_set_ = false;

  /**
   * The default value of the '{@link #isReadOnly() Read Only}' attribute.
   *
   *
   * @see #isReadOnly()
   * @generated
   * @ordered
   */
  protected static final boolean READ_ONLY_DEFAULT_ = false;

  /**
   * The cached value of the '{@link #isReadOnly() Read Only}' attribute.
   *
   *
   * @see #isReadOnly()
   * @generated
   * @ordered
   */
  protected boolean readOnly = READ_ONLY_DEFAULT_;

  /**
   * This is true if the Read Only attribute has been set.
   *
   *
   * @generated
   * @ordered
   */
  protected boolean readOnly_set_ = false;

  /**
   * The cached value of the '{@link #getType_() Type}' reference.
   *
   *
   * @see #getType_()
   * @generated
   * @ordered
   */

  protected Type type = null;

  /**
   * This is true if the Type reference has been set.
   *
   *
   * @generated
   * @ordered
   */
  protected boolean type_set_ = false;

  /**
   * The cached value of the '{@link #getOpposite_() Opposite}' reference.
   *
   *
   * @see #getOpposite_()
   * @generated
   * @ordered
   */

  protected Property opposite = null;

  /**
   * This is true if the Opposite reference has been set.
   *
   *
   * @generated
   * @ordered
   */
  protected boolean opposite_set_ = false;

  /**
   * The default value of the '{@link #isNullable() Nullable}' attribute.
   *
   *
   * @see #isNullable()
   * @generated
   * @ordered
   */
  protected static final boolean NULLABLE_DEFAULT_ = false;

  /**
   * The cached value of the '{@link #isNullable() Nullable}' attribute.
   *
   *
   * @see #isNullable()
   * @generated
   * @ordered
   */
  protected boolean nullable = NULLABLE_DEFAULT_;

  /**
   * This is true if the Nullable attribute has been set.
   *
   *
   * @generated
   * @ordered
   */
  protected boolean nullable_set_ = false;

  /**
   * The cached value of the '{@link #getAnyAttribute() Any Attribute}' attribute list.
   *
   *
   * @see #getAnyAttribute()
   * @generated
   * @ordered
   */

  protected Sequence anyAttribute = null;

  /**
   *
   *
   * @generated
   */
  public PropertyImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  public commonj.sdo.Type getStaticType()
  {
    return ((ModelFactoryImpl)ModelFactory.INSTANCE).getProperty();
  }

  /**
   *
   *
   * @generated
   */
  public List getAliasName()
  {
    if (aliasName == null)
    {
      aliasName = createPropertyList(ListKind.DATATYPE, String.class, ALIAS_NAME, 0);
    }
    return aliasName;
  }
  /**
   *
   *
   * @generated
   */
  public Sequence getAny()
  {
    if (any == null)
    {
      any = createSequence(INTERNAL_ANY);
    }
    return any;
  }
  /**
   *
   *
   * @generated
   */
  public String getName()
  {
    return name;
  }
  /**
   *
   *
   * @generated
   */
  public void setName(String newName)
  {
    String oldName = name;
    name = newName;
    boolean oldName_set_ = name_set_;
    name_set_ = true;
    if (isNotifying())
      notify(ChangeKind.SET, INTERNAL_NAME, oldName, name, !oldName_set_);
  }

  /**
   *
   *
   * @generated
   */
  public void unsetName()
  {
    String oldName = name;
    boolean oldName_set_ = name_set_;
    name = NAME_DEFAULT_;
    name_set_ = false;
    if (isNotifying())
      notify(ChangeKind.UNSET, INTERNAL_NAME, oldName, NAME_DEFAULT_, oldName_set_);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSetName()
  {
    return name_set_;
  }

  /**
   *
   *
   * @generated
   */
  public boolean isMany()
  {
    return many;
  }
  /**
   *
   *
   * @generated
   */
  public void setMany(boolean newMany)
  {
    boolean oldMany = many;
    many = newMany;
    boolean oldMany_set_ = many_set_;
    many_set_ = true;
    if (isNotifying())
      notify(ChangeKind.SET, INTERNAL_MANY, oldMany, many, !oldMany_set_);
  }

  /**
   *
   *
   * @generated
   */
  public void unsetMany()
  {
    boolean oldMany = many;
    boolean oldMany_set_ = many_set_;
    many = MANY_DEFAULT_;
    many_set_ = false;
    if (isNotifying())
      notify(ChangeKind.UNSET, INTERNAL_MANY, oldMany, MANY_DEFAULT_, oldMany_set_);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSetMany()
  {
    return many_set_;
  }

  /**
   *
   *
   * @generated
   */
  public boolean isContainment()
  {
    return containment;
  }
  /**
   *
   *
   * @generated
   */
  public void setContainment(boolean newContainment)
  {
    boolean oldContainment = containment;
    containment = newContainment;
    boolean oldContainment_set_ = containment_set_;
    containment_set_ = true;
    if (isNotifying())
      notify(ChangeKind.SET, INTERNAL_CONTAINMENT, oldContainment, containment, !oldContainment_set_);
  }

  /**
   *
   *
   * @generated
   */
  public void unsetContainment()
  {
    boolean oldContainment = containment;
    boolean oldContainment_set_ = containment_set_;
    containment = CONTAINMENT_DEFAULT_;
    containment_set_ = false;
    if (isNotifying())
      notify(ChangeKind.UNSET, INTERNAL_CONTAINMENT, oldContainment, CONTAINMENT_DEFAULT_, oldContainment_set_);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSetContainment()
  {
    return containment_set_;
  }

  /**
   *
   *
   * @generated
   */
  public String getDefault_()
  {
    return default_;
  }
  /**
   *
   *
   * @generated
   */
  public void setDefault_(String newDefault)
  {
    String oldDefault = default_;
    default_ = newDefault;
    boolean oldDefault_set_ = default_set_;
    default_set_ = true;
    if (isNotifying())
      notify(ChangeKind.SET, INTERNAL_DEFAULT, oldDefault, default_, !oldDefault_set_);
  }

  /**
   *
   *
   * @generated
   */
  public void unsetDefault()
  {
    String oldDefault = default_;
    boolean oldDefault_set_ = default_set_;
    default_ = DEFAULT_DEFAULT_;
    default_set_ = false;
    if (isNotifying())
      notify(ChangeKind.UNSET, INTERNAL_DEFAULT, oldDefault, DEFAULT_DEFAULT_, oldDefault_set_);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSetDefault()
  {
    return default_set_;
  }

  /**
   *
   *
   * @generated
   */
  public boolean isReadOnly()
  {
    return readOnly;
  }
  /**
   *
   *
   * @generated
   */
  public void setReadOnly(boolean newReadOnly)
  {
    boolean oldReadOnly = readOnly;
    readOnly = newReadOnly;
    boolean oldReadOnly_set_ = readOnly_set_;
    readOnly_set_ = true;
    if (isNotifying())
      notify(ChangeKind.SET, INTERNAL_READ_ONLY, oldReadOnly, readOnly, !oldReadOnly_set_);
  }

  /**
   *
   *
   * @generated
   */
  public void unsetReadOnly()
  {
    boolean oldReadOnly = readOnly;
    boolean oldReadOnly_set_ = readOnly_set_;
    readOnly = READ_ONLY_DEFAULT_;
    readOnly_set_ = false;
    if (isNotifying())
      notify(ChangeKind.UNSET, INTERNAL_READ_ONLY, oldReadOnly, READ_ONLY_DEFAULT_, oldReadOnly_set_);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSetReadOnly()
  {
    return readOnly_set_;
  }

  /**
   *
   *
   * @generated
   */
  public Type getType_()
  {
    if (type != null && isProxy(type))
    {
      Object oldType = type;
      type = (Type)resolveProxy(oldType);
      if (type != oldType)
      {
        if (isNotifying())
          notify(ChangeKind.RESOLVE, INTERNAL_TYPE, oldType, type);
      }
    }
    return type;
  }
  /**
   *
   *
   * @generated
   */
  public Type basicGetType()
  {
    return type;
  }

  /**
   *
   *
   * @generated
   */
  public void setType(Type newType)
  {
    Type oldType = type;
    type = newType;
    boolean oldType_set_ = type_set_;
    type_set_ = true;
    if (isNotifying())
      notify(ChangeKind.SET, INTERNAL_TYPE, oldType, type, !oldType_set_);
  }

  /**
   *
   *
   * @generated
   */
  public void unsetType()
  {
    Type oldType = type;
    boolean oldType_set_ = type_set_;
    type = null;
    type_set_ = false;
    if (isNotifying())
      notify(ChangeKind.UNSET, INTERNAL_TYPE, oldType, null, oldType_set_);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSetType()
  {
    return type_set_;
  }

  /**
   *
   *
   * @generated
   */
  public Property getOpposite_()
  {
    if (opposite != null && isProxy(opposite))
    {
      Object oldOpposite = opposite;
      opposite = (Property)resolveProxy(oldOpposite);
      if (opposite != oldOpposite)
      {
        if (isNotifying())
          notify(ChangeKind.RESOLVE, INTERNAL_OPPOSITE, oldOpposite, opposite);
      }
    }
    return opposite;
  }
  /**
   *
   *
   * @generated
   */
  public Property basicGetOpposite()
  {
    return opposite;
  }

  /**
   *
   *
   * @generated
   */
  public void setOpposite_(Property newOpposite)
  {
    Property oldOpposite = opposite;
    opposite = newOpposite;
    boolean oldOpposite_set_ = opposite_set_;
    opposite_set_ = true;
    if (isNotifying())
      notify(ChangeKind.SET, INTERNAL_OPPOSITE, oldOpposite, opposite, !oldOpposite_set_);
  }

  /**
   *
   *
   * @generated
   */
  public void unsetOpposite()
  {
    Property oldOpposite = opposite;
    boolean oldOpposite_set_ = opposite_set_;
    opposite = null;
    opposite_set_ = false;
    if (isNotifying())
      notify(ChangeKind.UNSET, INTERNAL_OPPOSITE, oldOpposite, null, oldOpposite_set_);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSetOpposite()
  {
    return opposite_set_;
  }

  /**
   *
   *
   * @generated
   */
  public boolean isNullable()
  {
    return nullable;
  }
  /**
   *
   *
   * @generated
   */
  public void setNullable(boolean newNullable)
  {
    boolean oldNullable = nullable;
    nullable = newNullable;
    boolean oldNullable_set_ = nullable_set_;
    nullable_set_ = true;
    if (isNotifying())
      notify(ChangeKind.SET, INTERNAL_NULLABLE, oldNullable, nullable, !oldNullable_set_);
  }

  /**
   *
   *
   * @generated
   */
  public void unsetNullable()
  {
    boolean oldNullable = nullable;
    boolean oldNullable_set_ = nullable_set_;
    nullable = NULLABLE_DEFAULT_;
    nullable_set_ = false;
    if (isNotifying())
      notify(ChangeKind.UNSET, INTERNAL_NULLABLE, oldNullable, NULLABLE_DEFAULT_, oldNullable_set_);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSetNullable()
  {
    return nullable_set_;
  }

  /**
   *
   *
   * @generated
   */
  public Sequence getAnyAttribute()
  {
    if (anyAttribute == null)
    {
      anyAttribute = createSequence(INTERNAL_ANY_ATTRIBUTE);
    }
    return anyAttribute;
  }
  /**
   *
   *
   * @generated
   */
  public ChangeContext inverseRemove(Object otherEnd, int propertyIndex, ChangeContext changeContext)
  {
    switch (propertyIndex)
    {
      case ANY:
        return removeFromSequence(getAny(), otherEnd, changeContext);
      case ANY_ATTRIBUTE:
        return removeFromSequence(getAnyAttribute(), otherEnd, changeContext);
    }
    return super.inverseRemove(otherEnd, propertyIndex, changeContext);
  }

  /**
   *
   *
   * @generated
   */
  public Object get(int propertyIndex, boolean resolve)
  {
    switch (propertyIndex)
    {
      case ALIAS_NAME:
        return getAliasName();
      case ANY:
        // XXX query introduce coreType as an argument? -- semantic = if true -- coreType - return the core EMF object if value is a non-EMF wrapper/view
        //if (coreType)
        return getAny();
      case NAME:
        return getName();
      case MANY:
        return isMany() ? Boolean.TRUE : Boolean.FALSE;
      case CONTAINMENT:
        return isContainment() ? Boolean.TRUE : Boolean.FALSE;
      case DEFAULT:
        return getDefault_();
      case READ_ONLY:
        return isReadOnly() ? Boolean.TRUE : Boolean.FALSE;
      case TYPE:
        if (resolve) return getType_();
        return basicGetType();
      case OPPOSITE:
        if (resolve) return getOpposite_();
        return basicGetOpposite();
      case NULLABLE:
        return isNullable() ? Boolean.TRUE : Boolean.FALSE;
      case ANY_ATTRIBUTE:
        // XXX query introduce coreType as an argument? -- semantic = if true -- coreType - return the core EMF object if value is a non-EMF wrapper/view
        //if (coreType)
        return getAnyAttribute();
    }
    return super.get(propertyIndex, resolve);
  }

  /**
   *
   *
   * @generated
   */
  public void set(int propertyIndex, Object newValue)
  {
    switch (propertyIndex)
    {
      case ALIAS_NAME:
        getAliasName().clear();
        getAliasName().addAll((Collection)newValue);
        return;
      case ANY:
      	setSequence(getAny(), newValue);
        return;
      case NAME:
        setName((String)newValue);
        return;
      case MANY:
        setMany(((Boolean)newValue).booleanValue());
        return;
      case CONTAINMENT:
        setContainment(((Boolean)newValue).booleanValue());
        return;
      case DEFAULT:
        setDefault_((String)newValue);
        return;
      case READ_ONLY:
        setReadOnly(((Boolean)newValue).booleanValue());
        return;
      case TYPE:
        setType((Type)newValue);
        return;
      case OPPOSITE:
        setOpposite_((Property)newValue);
        return;
      case NULLABLE:
        setNullable(((Boolean)newValue).booleanValue());
        return;
      case ANY_ATTRIBUTE:
      	setSequence(getAnyAttribute(), newValue);
        return;
    }
    super.set(propertyIndex, newValue);
  }

  /**
   *
   *
   * @generated
   */
  public void unset(int propertyIndex)
  {
    switch (propertyIndex)
    {
      case ALIAS_NAME:
        getAliasName().clear();
        return;
      case ANY:
        unsetSequence(getAny());
        return;
      case NAME:
        unsetName();
        return;
      case MANY:
        unsetMany();
        return;
      case CONTAINMENT:
        unsetContainment();
        return;
      case DEFAULT:
        unsetDefault();
        return;
      case READ_ONLY:
        unsetReadOnly();
        return;
      case TYPE:
        unsetType();
        return;
      case OPPOSITE:
        unsetOpposite();
        return;
      case NULLABLE:
        unsetNullable();
        return;
      case ANY_ATTRIBUTE:
        unsetSequence(getAnyAttribute());
        return;
    }
    super.unset(propertyIndex);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSet(int propertyIndex)
  {
    switch (propertyIndex)
    {
      case ALIAS_NAME:
        return aliasName != null && !aliasName.isEmpty();
      case ANY:
        return any != null && !isSequenceEmpty(getAny());
      case NAME:
        return isSetName();
      case MANY:
        return isSetMany();
      case CONTAINMENT:
        return isSetContainment();
      case DEFAULT:
        return isSetDefault();
      case READ_ONLY:
        return isSetReadOnly();
      case TYPE:
        return isSetType();
      case OPPOSITE:
        return isSetOpposite();
      case NULLABLE:
        return isSetNullable();
      case ANY_ATTRIBUTE:
        return anyAttribute != null && !isSequenceEmpty(getAnyAttribute());
    }
    return super.isSet(propertyIndex);
  }

  /**
   *
   *
   * @generated
   */
  public String toString()
  {
    if (isProxy(this)) return super.toString();

    StringBuffer result = new StringBuffer(super.toString());
    result.append(" (aliasName: ");
    result.append(aliasName);
    result.append(", any: ");
    result.append(any);
    result.append(", name: ");
    if (name_set_) result.append(name); else result.append("<unset>");
    result.append(", many: ");
    if (many_set_) result.append(many); else result.append("<unset>");
    result.append(", containment: ");
    if (containment_set_) result.append(containment); else result.append("<unset>");
    result.append(", default: ");
    if (default_set_) result.append(default_); else result.append("<unset>");
    result.append(", readOnly: ");
    if (readOnly_set_) result.append(readOnly); else result.append("<unset>");
    result.append(", nullable: ");
    if (nullable_set_) result.append(nullable); else result.append("<unset>");
    result.append(", anyAttribute: ");
    result.append(anyAttribute);
    result.append(')');
    return result.toString();
  }

} //PropertyImpl


text:
package eu.ydp.empiria.player.client.module.test.reset;

import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import eu.ydp.empiria.player.client.controller.flow.FlowManager;
import eu.ydp.empiria.player.client.controller.flow.request.FlowRequest;
import eu.ydp.empiria.player.client.controller.workmode.PlayerWorkMode;
import eu.ydp.empiria.player.client.controller.workmode.PlayerWorkModeService;
import eu.ydp.empiria.player.client.module.test.reset.view.TestResetButtonView;
import eu.ydp.empiria.player.client.util.events.internal.bus.EventsBus;
import eu.ydp.empiria.player.client.util.events.internal.reset.LessonResetEvent;
import eu.ydp.empiria.player.client.util.events.internal.reset.LessonResetEventTypes;
import eu.ydp.gwtutil.client.event.factory.Command;

public class TestResetButtonPresenter {

    private final TestResetButtonView testResetButtonView;
    private final FlowManager flowManager;
    private final PlayerWorkModeService playerWorkModeService;
    private boolean locked;
    private final EventsBus eventsBus;

    @Inject
    public TestResetButtonPresenter(TestResetButtonView testResetButtonView, FlowManager flowManager, PlayerWorkModeService playerWorkModeService,
                                    EventsBus eventsBus) {
        this.testResetButtonView = testResetButtonView;
        this.flowManager = flowManager;
        this.playerWorkModeService = playerWorkModeService;
        this.eventsBus = eventsBus;
        attachHandler();
    }

    private void attachHandler() {
        testResetButtonView.addHandler(new Command() {
            @Override
            public void execute(NativeEvent event) {
                if (!locked) {
                    changeWorkModeToTest();
                    navigateToFirstItem();
                    resetLesson();
                }
            }

        });
    }

    public Widget getView() {
        return testResetButtonView.asWidget();
    }

    public void lock() {
        locked = true;
        testResetButtonView.lock();
    }

    public void unlock() {
        locked = false;
        testResetButtonView.unlock();
    }

    public void enablePreviewMode() {
        lock();
        testResetButtonView.enablePreviewMode();
    }

    private void changeWorkModeToTest() {
        playerWorkModeService.tryToUpdateWorkMode(PlayerWorkMode.TEST);
    }

    private void navigateToFirstItem() {
        flowManager.invokeFlowRequest(new FlowRequest.NavigateFirstItem());
    }

    protected void resetLesson() {
        eventsBus.fireEvent(new LessonResetEvent(LessonResetEventTypes.RESET));
    }
}