text:
package controller

import (
	"fmt"

	"github.com/golang/glog"

	errors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/client-go/tools/record"
	kapi "k8s.io/kubernetes/pkg/api"

	builddefaults "github.com/openshift/origin/pkg/build/admission/defaults"
	buildoverrides "github.com/openshift/origin/pkg/build/admission/overrides"
	buildapi "github.com/openshift/origin/pkg/build/api"
	buildclient "github.com/openshift/origin/pkg/build/client"
	"github.com/openshift/origin/pkg/build/controller/common"
	"github.com/openshift/origin/pkg/build/controller/policy"
	strategy "github.com/openshift/origin/pkg/build/controller/strategy"
	buildutil "github.com/openshift/origin/pkg/build/util"
	imageapi "github.com/openshift/origin/pkg/image/api"
)

// BuildController watches build resources and manages their state
type BuildController struct {
	BuildUpdater      buildclient.BuildUpdater
	BuildLister       buildclient.BuildLister
	PodManager        podManager
	BuildStrategy     BuildStrategy
	ImageStreamClient imageStreamClient
	Recorder          record.EventRecorder
	RunPolicies       []policy.RunPolicy
	BuildDefaults     builddefaults.BuildDefaults
	BuildOverrides    buildoverrides.BuildOverrides
}

// BuildStrategy knows how to create a pod spec for a pod which can execute a build.
type BuildStrategy interface {
	CreateBuildPod(build *buildapi.Build) (*kapi.Pod, error)
}

type podManager interface {
	CreatePod(namespace string, pod *kapi.Pod) (*kapi.Pod, error)
	DeletePod(namespace string, pod *kapi.Pod) error
	GetPod(namespace, name string) (*kapi.Pod, error)
}

type imageStreamClient interface {
	GetImageStream(namespace, name string) (*imageapi.ImageStream, error)
}

// CancelBuild updates a build status to Cancelled, after its associated pod is deleted.
func (bc *BuildController) CancelBuild(build *buildapi.Build) error {
	if !isBuildCancellable(build) {
		glog.V(4).Infof("Build %s/%s can be cancelled only if it has pending/running status, not %s.", build.Namespace, build.Name, build.Status.Phase)
		return nil
	}

	glog.V(4).Infof("Cancelling build %s/%s.", build.Namespace, build.Name)

	pod, err := bc.PodManager.GetPod(build.Namespace, buildapi.GetBuildPodName(build))
	if err != nil {
		if !errors.IsNotFound(err) {
			return fmt.Errorf("Failed to get pod for build %s/%s: %v", build.Namespace, build.Name, err)
		}
	} else {
		err := bc.PodManager.DeletePod(build.Namespace, pod)
		if err != nil && !errors.IsNotFound(err) {
			return fmt.Errorf("Couldn't delete build pod %s/%s: %v", build.Namespace, pod.Name, err)
		}
	}

	build.Status.Phase = buildapi.BuildPhaseCancelled
	common.SetBuildCompletionTimeAndDuration(build)
	bc.Recorder.Eventf(build, kapi.EventTypeNormal, buildapi.BuildCancelledEventReason, fmt.Sprintf(buildapi.BuildCancelledEventMessage, build.Namespace, build.Name))
	// set the status details for the cancelled build before updating the build
	// object.
	build.Status.Reason = buildapi.StatusReasonCancelledBuild
	build.Status.Message = buildapi.StatusMessageCancelledBuild
	if err := bc.BuildUpdater.Update(build.Namespace, build); err != nil {
		return fmt.Errorf("Failed to update build %s/%s: %v", build.Namespace, build.Name, err)
	}

	glog.V(4).Infof("Build %s/%s was successfully cancelled.", build.Namespace, build.Name)

	common.HandleBuildCompletion(build, bc.RunPolicies)

	return nil
}

// HandleBuild deletes pods for cancelled builds and takes new builds and puts
// them in the pending state after creating a corresponding pod
func (bc *BuildController) HandleBuild(build *buildapi.Build) error {
	// these builds are processed/updated/etc by the jenkins sync plugin
	if build.Spec.Strategy.JenkinsPipelineStrategy != nil {
		glog.V(4).Infof("Ignoring build with jenkins pipeline strategy")
		return nil
	}
	glog.V(4).Infof("Handling build %s/%s (%s)", build.Namespace, build.Name, build.Status.Phase)

	// A cancelling event was triggered for the build, delete its pod and update build status.
	if build.Status.Cancelled && build.Status.Phase != buildapi.BuildPhaseCancelled {
		glog.V(5).Infof("Marking build %s/%s as cancelled", build.Namespace, build.Name)
		if err := bc.CancelBuild(build); err != nil {
			build.Status.Reason = buildapi.StatusReasonCancelBuildFailed
			build.Status.Message = buildapi.StatusMessageCancelBuildFailed
			if err = bc.BuildUpdater.Update(build.Namespace, build); err != nil {
				utilruntime.HandleError(fmt.Errorf("Failed to update build %s/%s: %v", build.Namespace, build.Name, err))
			}
			return fmt.Errorf("Failed to cancel build %s/%s: %v, will retry", build.Namespace, build.Name, err)
		}
	}

	// Handle only new builds from this point
	if build.Status.Phase != buildapi.BuildPhaseNew {
		return nil
	}

	runPolicy := policy.ForBuild(build, bc.RunPolicies)
	if runPolicy == nil {
		return fmt.Errorf("unable to determine build scheduler for %s/%s", build.Namespace, build.Name)
	}

	// The runPolicy decides whether to execute this build or not.
	if run, err := runPolicy.IsRunnable(build); err != nil || !run {
		return err
	}

	if err := bc.nextBuildPhase(build); err != nil {
		return err
	}

	if err := bc.BuildUpdater.Update(build.Namespace, build); err != nil {
		// This is not a retryable error because the build has been created.  The worst case
		// outcome of not updating the buildconfig is that we might rerun a build for the
		// same "new" imageid change in the future, which is better than guaranteeing we
		// run the build 2+ times by retrying it here.
		glog.V(2).Infof("Failed to record changes to build %s/%s: %v", build.Namespace, build.Name, err)
	}
	return nil
}

// nextBuildPhase updates build with any appropriate changes, or returns an error if
// the change cannot occur. When returning nil, be sure to set build.Status and optionally
// build.Message.
func (bc *BuildController) nextBuildPhase(build *buildapi.Build) error {
	// If a cancelling event was triggered for the build, update build status.
	if build.Status.Cancelled {
		glog.V(4).Infof("Cancelling build %s/%s.", build.Namespace, build.Name)
		build.Status.Phase = buildapi.BuildPhaseCancelled
		return nil
	}

	// Set the output Docker image reference.
	ref, err := bc.resolveOutputDockerImageReference(build)
	if err != nil {
		build.Status.Reason = buildapi.StatusReasonInvalidOutputReference
		build.Status.Message = buildapi.StatusMessageInvalidOutputRef
		return err
	}
	build.Status.OutputDockerImageReference = ref

	// Make a copy to avoid mutating the build from this point on.
	copy, err := kapi.Scheme.Copy(build)
	if err != nil {
		return fmt.Errorf("unable to copy build: %v", err)
	}
	buildCopy := copy.(*buildapi.Build)

	// TODO(rhcarvalho)
	// The S2I and Docker builders expect build.Spec.Output.To to contain a
	// resolved reference to a Docker image. Since build.Spec is immutable, we
	// change a copy (that is never persisted) and pass it to
	// bc.BuildStrategy.CreateBuildPod. We should make the builders use
	// build.Status.OutputDockerImageReference, what will make copying the build
	// unnecessary.
	if build.Spec.Output.To != nil && len(build.Spec.Output.To.Name) != 0 {
		buildCopy.Spec.Output.To = &kapi.ObjectReference{
			Kind: "DockerImage",
			Name: ref,
		}
	}

	// Invoke the strategy to get a build pod.
	podSpec, err := bc.BuildStrategy.CreateBuildPod(buildCopy)
	if err != nil {
		build.Status.Reason = buildapi.StatusReasonCannotCreateBuildPodSpec
		build.Status.Message = buildapi.StatusMessageCannotCreateBuildPodSpec
		if strategy.IsFatal(err) {
			return &strategy.FatalError{Reason: fmt.Sprintf("failed to create a build pod spec for build %s/%s: %v", build.Namespace, build.Name, err)}
		}
		return fmt.Errorf("failed to create a build pod spec for build %s/%s: %v", build.Namespace, build.Name, err)
	}
	if err := bc.BuildDefaults.ApplyDefaults(podSpec); err != nil {
		return fmt.Errorf("failed to apply build defaults for build %s/%s: %v", build.Namespace, build.Name, err)
	}
	if err := bc.BuildOverrides.ApplyOverrides(podSpec); err != nil {
		return fmt.Errorf("failed to apply build overrides for build %s/%s: %v", build.Namespace, build.Name, err)
	}

	glog.V(4).Infof("Pod %s for build %s/%s is about to be created", podSpec.Name, build.Namespace, build.Name)

	if _, err := bc.PodManager.CreatePod(build.Namespace, podSpec); err != nil {
		if errors.IsAlreadyExists(err) {
			bc.Recorder.Eventf(build, kapi.EventTypeWarning, "FailedCreate", "Pod already exists: %s/%s", podSpec.Namespace, podSpec.Name)
			glog.V(4).Infof("Build pod already existed: %#v", podSpec)

			// If the existing pod was created before this build, switch to Error state.
			existingPod, err := bc.PodManager.GetPod(podSpec.Namespace, podSpec.Name)
			if err == nil && existingPod.CreationTimestamp.Before(build.CreationTimestamp) {
				build.Status.Phase = buildapi.BuildPhaseError
				build.Status.Reason = buildapi.StatusReasonBuildPodExists
				build.Status.Message = buildapi.StatusMessageBuildPodExists
			}
			return nil
		}
		// Log an event if the pod is not created (most likely due to quota denial).
		bc.Recorder.Eventf(build, kapi.EventTypeWarning, "FailedCreate", "Error creating: %v", err)
		build.Status.Reason = buildapi.StatusReasonCannotCreateBuildPod
		build.Status.Message = buildapi.StatusMessageCannotCreateBuildPod
		return fmt.Errorf("failed to create build pod: %v", err)
	}
	common.SetBuildPodNameAnnotation(build, podSpec.Name)
	glog.V(4).Infof("Created pod for build: %#v", podSpec)

	// Set the build phase, which will be persisted.
	build.Status.Phase = buildapi.BuildPhasePending
	build.Status.Reason = ""
	build.Status.Message = ""
	return nil
}

// resolveOutputDockerImageReference returns a reference to a Docker image
// computed from the buid.Spec.Output.To reference.
func (bc *BuildController) resolveOutputDockerImageReference(build *buildapi.Build) (string, error) {
	outputTo := build.Spec.Output.To
	if outputTo == nil || outputTo.Name == "" {
		return "", nil
	}
	var ref string
	switch outputTo.Kind {
	case "DockerImage":
		ref = outputTo.Name
	case "ImageStream", "ImageStreamTag":
		// TODO(smarterclayton): security, ensure that the reference image stream is actually visible
		namespace := outputTo.Namespace
		if len(namespace) == 0 {
			namespace = build.Namespace
		}

		var tag string
		streamName := outputTo.Name
		if outputTo.Kind == "ImageStreamTag" {
			var ok bool
			streamName, tag, ok = imageapi.SplitImageStreamTag(streamName)
			if !ok {
				return "", fmt.Errorf("the referenced image stream tag is invalid: %s", outputTo.Name)
			}
			tag = ":" + tag
		}
		stream, err := bc.ImageStreamClient.GetImageStream(namespace, streamName)
		if err != nil {
			if errors.IsNotFound(err) {
				return "", fmt.Errorf("the referenced output image stream %s/%s does not exist", namespace, streamName)
			}
			return "", fmt.Errorf("the referenced output image stream %s/%s could not be found by build %s/%s: %v", namespace, streamName, build.Namespace, build.Name, err)
		}
		if len(stream.Status.DockerImageRepository) == 0 {
			e := fmt.Errorf("the image stream %s/%s cannot be used as the output for build %s/%s because the integrated Docker registry is not configured and no external registry was defined", namespace, outputTo.Name, build.Namespace, build.Name)
			bc.Recorder.Eventf(build, kapi.EventTypeWarning, "invalidOutput", "Error starting build: %v", e)
			return "", e
		}
		ref = fmt.Sprintf("%s%s", stream.Status.DockerImageRepository, tag)
	}
	return ref, nil
}

// isBuildCancellable checks for build status and returns true if the condition is checked.
func isBuildCancellable(build *buildapi.Build) bool {
	return build.Status.Phase == buildapi.BuildPhaseNew || build.Status.Phase == buildapi.BuildPhasePending || build.Status.Phase == buildapi.BuildPhaseRunning
}

// BuildDeleteController watches for builds being deleted and cleans up associated pods
type BuildDeleteController struct {
	PodManager podManager
}

// HandleBuildDeletion deletes a build pod if the corresponding build has been deleted
func (bc *BuildDeleteController) HandleBuildDeletion(build *buildapi.Build) error {
	glog.V(4).Infof("Handling deletion of build %s", build.Name)
	if build.Spec.Strategy.JenkinsPipelineStrategy != nil {
		glog.V(4).Infof("Ignoring build with jenkins pipeline strategy")
		return nil
	}
	podName := buildapi.GetBuildPodName(build)
	pod, err := bc.PodManager.GetPod(build.Namespace, podName)
	if err != nil && !errors.IsNotFound(err) {
		glog.V(2).Infof("Failed to find pod with name %s for build %s in namespace %s due to error: %v", podName, build.Name, build.Namespace, err)
		return err
	}
	if pod == nil {
		glog.V(2).Infof("Did not find pod with name %s for build %s in namespace %s", podName, build.Name, build.Namespace)
		return nil
	}
	if buildName := buildapi.GetBuildName(pod); buildName != build.Name {
		glog.V(2).Infof("Not deleting pod %s/%s because the build label %s does not match the build name %s", pod.Namespace, podName, buildName, build.Name)
		return nil
	}
	err = bc.PodManager.DeletePod(build.Namespace, pod)
	if err != nil && !errors.IsNotFound(err) {
		glog.V(2).Infof("Failed to delete pod %s/%s for build %s due to error: %v", build.Namespace, podName, build.Name, err)
		return err
	}
	return nil
}

// buildKey returns a build object that can be used to lookup a build
// in the cache store, given a pod for the build
func buildKey(pod *kapi.Pod) *buildapi.Build {
	return &buildapi.Build{
		ObjectMeta: metav1.ObjectMeta{
			Name:      buildutil.GetBuildName(pod),
			Namespace: pod.Namespace,
		},
	}
}

redpajama_set_name: RedPajamaGithub


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

[System.Serializable]
public class DataLogic
{
    public int slot;
    public GameData.GameState state;

    public DataLogic()
    {
    }

    public void InitData()
    {
        state = GameData.LoadGame(slot);
    }

    public void SetEnergy(float e)
    {
        state.energy = e;
    }

    public void SetAmmo(float m)
    {
        state.energy = m;
    }

    public void SetPlayerPos()
    {
        state.playerPosition = GameObject.FindGameObjectWithTag("Player").transform.position;
    }

    public void SaveState()
    {
        SetPlayerPos();

        GameData.gameState = state;
        GameData.SaveGame(slot);
    }

    public void LoadState()
    {
        GameData.LoadGame(slot);
    }

    public void NewGameState()
    {
        GameData.NewGame(slot);
    }
}


text:
package predicate // import "v2ray.com/core/common/predicate"

type Predicate func() bool

func (v Predicate) And(predicate Predicate) Predicate {
	return All(v, predicate)
}

func (v Predicate) Or(predicate Predicate) Predicate {
	return Any(v, predicate)
}

func All(predicates ...Predicate) Predicate {
	return func() bool {
		for _, p := range predicates {
			if !p() {
				return false
			}
		}
		return true
	}
}

func Any(predicates ...Predicate) Predicate {
	return func() bool {
		for _, p := range predicates {
			if p() {
				return true
			}
		}
		return false
	}
}

func Not(predicate Predicate) Predicate {
	return func() bool {
		return !predicate()
	}
}


text:
package org.jboss.arquillian.daemon.protocol.arquillian;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.arquillian.container.test.spi.TestDeployment;
import org.jboss.arquillian.container.test.spi.client.deployment.DeploymentPackager;
import org.jboss.arquillian.container.test.spi.client.deployment.ProtocolArchiveProcessor;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;

/**
 * {@link DeploymentPackager} to merge auxiliar archive contents with the archive provided by the user
 *
 * @author Andrew Lee Rubinger
 */
public enum DaemonDeploymentPackager implements DeploymentPackager {

    INSTANCE;

    private static final Logger log = Logger.getLogger(DaemonDeploymentPackager.class.getName());

    /**
     * {@inheritDoc}
     *
     * @see org.jboss.arquillian.container.test.spi.client.deployment.DeploymentPackager#generateDeployment(org.jboss.arquillian
     *      .container.test.spi.TestDeployment, java.util.Collection)
     */
    @Override
    public Archive<?> generateDeployment(final TestDeployment testDeployment,
        final Collection<ProtocolArchiveProcessor> processors) {
        // Merge auxiliary archives with the declared for ARQ and testrunner support
        final JavaArchive archive = testDeployment.getApplicationArchive().as(JavaArchive.class);
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Archive before additional packaging: " + archive.toString(true));
        }
        for (final Archive<?> auxArchive : testDeployment.getAuxiliaryArchives()) {
            archive.merge(auxArchive);
        }
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Archive after additional packaging: " + archive.toString(true));
        }

        return archive;

    }
}


text:
.. Copyright (c) 2016, Ruslan Baratov
.. All rights reserved.

.. _contributing:

Contributing
------------

There are many ways to contribute to Hunter:

- Documentation
- There is a newer version of an existing package? `Notify us <https://github.com/ruslo/hunter/issues>`__ or send a pull request with an updated version.
- Missing a package in Hunter? :ref:`Add a new package <creating new>`
- `Resolve Issues <https://github.com/ruslo/hunter/issues>`__

  - Can you provide an answer to an open question?
  - Can you reproduce the error?
  - Is the issue still relevant? Maybe the issue can be closed.

When contributing please follow the style guides:

- `Git <http://0.readthedocs.org/en/latest/git.html>`__
- `CMake <http://0.readthedocs.org/en/latest/cmake.html>`__

.. note::

     The minimum version of CMake for using Hunter is ``3.0``.
     Please check that you're not using commands from newer versions
     (`see documentation for 3.0 <http://www.cmake.org/cmake/help/v3.0/>`__).

.. note::

    Before adding or updating a package in Hunter, the package is tested.
    Tests are done to check if the source can be downloaded, built and linked.
    Head over to our
    `repository for per package CI testing contribution <https://github.com/ingenue/hunter/branches/all?utf8=%E2%9C%93&query=pkg.>`__
    to see more.

.. note::

  If you're planning to introduce nontrivial feature it's better to
  discuss design first, it will save a lot of time for both you and developers.

Reporting bugs
~~~~~~~~~~~~~~

Hunter is CMake-based package manager so it's assumed that CMake is installed
and working correctly. Before reporting bugs please check:

* Appropriate version of CMake is installed.
  See :doc:`CMake version for Hunter </quick-start/cmake>`.

* Verify CMake, build tools and C/C++ compilers you're planning to use.
  E.g. try to build simple CMake project (check
  `this document <http://cgold.readthedocs.io/en/latest/first-step.html>`__
  in case you have troubles):

  .. code-block:: cmake

    # CMakeLists.txt

    cmake_minimum_required(VERSION 3.0)
    project(foo)

    add_executable(foo foo.cpp)

  .. code-block:: cpp

    // foo.cpp

    #include <iostream>

    int main() {
      std::cout << "Hello world!" << std::endl;
    }

* If you are experiencing some download error please check F.A.Q.:
  :doc:`How to fix download error? </faq/how-to-fix-download-error>`

If everything seems OK:

* Run build again with :ref:`HUNTER_STATUS_DEBUG=ON <hunter_status_debug>`
* Make sure you're not using :ref:`HUNTER_NO_TOOLCHAIN_ID_RECALCULATION <hunter no toolchain id recalculation>`
* Take a look at **first** error reported by Hunter. If Hunter reports chain
  of errors the last error you see is **not relevant**!
* Update to `latest Hunter URL/SHA1 <https://github.com/ruslo/hunter/releases>`__
  and check that issue you have hit is not already fixed/reported
* Check this document if the first error you see is ``external.build.failed``:

  * https://github.com/ruslo/hunter/wiki/error.external.build.failed
* Remove irrelevant code from your example and report one problem at a time.
  Try to construct `SSCCE <http://www.sscce.org/>`__. If you need more files
  than just ``CMakeLists.txt`` it's better to create separate GitHub repository
  for easy copying of your example. It will be nice if you can reproduce the
  issue with the CI system like AppVeyor/Travis.

* **Do not remove** ``~/.hunter`` repository to try to fix the issue! Hunter
  designed to be correct and reproducible, there should be no stale/rotten
  artifacts inside that can affect his work. If the ``rm -rf ~/.hunter`` step
  fix the issue for you it means that either you are using Hunter wrongly or
  there is a bug somewhere. If you want to figure out what is the origin
  of the problem please do keep ``~/.hunter`` directory.

* Open an `issue <https://github.com/ruslo/hunter/issues/new>`__ and provide
  next info:

  * CMake version you're using ``cmake --version``. CMake build from source?
  * OS (Linux, OSX, Windows)
  * Command line you're using on generate step, e.g.

    .. code-block:: none

      cmake -H. -B_builds "-GVisual Studio 14 2015"

  * Are you using toolchain?
  * Add log until **first error** reported by Hunter


text:
require 'problem_destroy'

class ResolvedProblemClearer

  ##
  # Clear all problem already resolved
  #
  def execute
    nb_problem_resolved.tap { |nb|
      if nb > 0
        criteria.each do |problem|
          ProblemDestroy.new(problem).execute
        end
        repair_database
      end
    }
  end

  private

  def nb_problem_resolved
    @count ||= criteria.count
  end

  def criteria
    @criteria = Problem.resolved
  end

  def repair_database
    Mongoid.default_session.command :repairDatabase => 1
  end
end


text:
using System;

namespace VBin
{
    /// <summary>
    /// Helper class for creating new app domains while running from vbin.
    /// In the new app domain the vbin AssemblyResolve event wont have been configured. So any
    /// attempt to load a type will only look on the disk for the assembly and thus fail.
    /// This class is used by IVBinAssemblyResolver.CreateAndUnwrapAppDomain to firstly setup vbin
    /// and then return the type that the user requested
    /// </summary>
    public class AppDomainCreationHelper : MarshalByRefObject
    {
        private static IVBinAssemblyResolver g_resolver;

        public AppDomainCreationHelper( long version )
        {
            g_resolver = VBinProgram.Initialise( new string[] { "-v=" + version, "." } );
        }

        /// <summary>
        /// Create an instance of the type specified in the new app domain
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public object Create( string assembly, string typeName )
        {
            var idx = assembly.IndexOf( "," );

            if( idx > 0 )
            {
                assembly = assembly.Substring( 0, idx );
            }

            var asm = g_resolver.GetAssembly( assembly );
            var type = asm.GetType( typeName, true );
            var obj = Activator.CreateInstance( type );
            return obj;
        }
    }
}


text:
const path = require('path');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: {
    getFleet: './get-fleet.js',
    getInventory: './get-inventory.js',
    getGps: './get-gps.js',
    postFleet: './post-fleet.js',
    postInventory: './post-inventory.js',
    postGps: './post-gps.js',
  },
  loader: {
    test: /\.js$/,
    exclude: /(node_modules|bower_components|public\/)/,
    loader: "babel-loader"
  },
  externals: {
    'aws-sdk': 'commonjs aws-sdk'
  },
  plugins: [
    new UglifyJSPlugin(),
  ],
  output: {
    filename: '[name].lambda.js',
    path: path.resolve(__dirname, 'dist')
  }
};


text:
package log15

import (
	"bytes"
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"time"
)

const (
	timeFormat     = "2006-01-02T15:04:05-0700"
	termTimeFormat = "01-02|15:04:05"
	floatFormat    = 'f'
	termMsgJust    = 40
)

// Format  is the interface implemented by StreamHandler formatters.
type Format interface {
	Format(r *Record) []byte
}

// FormatFunc returns a new Format object which uses
// the given function to perform record formatting.
func FormatFunc(f func(*Record) []byte) Format {
	return formatFunc(f)
}

type formatFunc func(*Record) []byte

func (f formatFunc) Format(r *Record) []byte {
	return f(r)
}

// TerminalFormat formats log records optimized for human readability on
// a terminal with color-coded level output and terser human friendly timestamp.
// This format should only be used for interactive programs or while developing.
//
//     [TIME] [LEVEL] MESSAGE key=value key=value ...
//
// Example:
//
//     [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002
//
func TerminalFormat() Format {
	return FormatFunc(func(r *Record) []byte {
		var color = 0
		switch r.Lvl {
		case LvlCrit:
			color = 35
		case LvlError:
			color = 31
		case LvlWarn:
			color = 33
		case LvlInfo:
			color = 32
		case LvlDebug:
			color = 36
		}

		b := &bytes.Buffer{}
		lvl := strings.ToUpper(r.Lvl.String())
		if color > 0 {
			fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %s ", color, lvl, r.Time.Format(termTimeFormat), r.Msg)
		} else {
			fmt.Fprintf(b, "[%s] [%s] %s ", lvl, r.Time.Format(termTimeFormat), r.Msg)
		}

		// try to justify the log output for short messages
		if len(r.Ctx) > 0 && len(r.Msg) < termMsgJust {
			b.Write(bytes.Repeat([]byte{' '}, termMsgJust-len(r.Msg)))
		}

		// print the keys logfmt style
		logfmt(b, r.Ctx, color)
		return b.Bytes()
	})
}

// LogfmtFormat prints records in logfmt format, an easy machine-parseable but human-readable
// format for key/value pairs.
//
// For more details see: http://godoc.org/github.com/kr/logfmt
//
func LogfmtFormat() Format {
	return FormatFunc(func(r *Record) []byte {
		common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg}
		buf := &bytes.Buffer{}
		logfmt(buf, append(common, r.Ctx...), 0)
		return buf.Bytes()
	})
}

func logfmt(buf *bytes.Buffer, ctx []interface{}, color int) {
	for i := 0; i < len(ctx); i += 2 {
		if i != 0 {
			buf.WriteByte(' ')
		}

		k, ok := ctx[i].(string)
		v := formatLogfmtValue(ctx[i+1])
		if !ok {
			k, v = errorKey, formatLogfmtValue(k)
		}

		// XXX: we should probably check that all of your key bytes aren't invalid
		if color > 0 {
			fmt.Fprintf(buf, "\x1b[%dm%s\x1b[0m=%s", color, k, v)
		} else {
			buf.WriteString(k)
			buf.WriteByte('=')
			buf.WriteString(v)
		}
	}

	buf.WriteByte('\n')
}

// JsonFormat formats log records as JSON objects separated by newlines.
// It is the equivalent of JsonFormatEx(false, true).
func JsonFormat() Format {
	return JsonFormatEx(false, true)
}

// JsonFormatEx formats log records as JSON objects. If pretty is true,
// records will be pretty-printed. If lineSeparated is true, records
// will be logged with a new line between each record.
func JsonFormatEx(pretty, lineSeparated bool) Format {
	jsonMarshal := json.Marshal
	if pretty {
		jsonMarshal = func(v interface{}) ([]byte, error) {
			return json.MarshalIndent(v, "", "    ")
		}
	}

	return FormatFunc(func(r *Record) []byte {
		props := make(map[string]interface{})

		props[r.KeyNames.Time] = r.Time
		props[r.KeyNames.Lvl] = r.Lvl.String()
		props[r.KeyNames.Msg] = r.Msg

		for i := 0; i < len(r.Ctx); i += 2 {
			k, ok := r.Ctx[i].(string)
			if !ok {
				props[errorKey] = fmt.Sprintf("%+v is not a string key", r.Ctx[i])
			}
			props[k] = formatJSONValue(r.Ctx[i+1])
		}

		b, err := jsonMarshal(props)
		if err != nil {
			b, _ = jsonMarshal(map[string]string{
				errorKey: err.Error(),
			})
			return b
		}

		if lineSeparated {
			b = append(b, '\n')
		}

		return b
	})
}

func formatShared(value interface{}) (result interface{}) {
	defer func() {
		if err := recover(); err != nil {
			if v := reflect.ValueOf(value); v.Kind() == reflect.Ptr && v.IsNil() {
				result = "nil"
			} else {
				panic(err)
			}
		}
	}()

	switch v := value.(type) {
	case time.Time:
		return v.Format(timeFormat)

	case error:
		return v.Error()

	case fmt.Stringer:
		return v.String()

	default:
		return v
	}
}

func formatJSONValue(value interface{}) interface{} {
	value = formatShared(value)

	switch value.(type) {
	case int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64, string:
		return value
	case interface{}, map[string]interface{}, []interface{}:
		return value
	default:
		return fmt.Sprintf("%+v", value)
	}
}

// formatValue formats a value for serialization
func formatLogfmtValue(value interface{}) string {
	if value == nil {
		return "nil"
	}

	if t, ok := value.(time.Time); ok {
		// Performance optimization: No need for escaping since the provided
		// timeFormat doesn't have any escape characters, and escaping is
		// expensive.
		return t.Format(timeFormat)
	}
	value = formatShared(value)
	switch v := value.(type) {
	case bool:
		return strconv.FormatBool(v)
	case float32:
		return strconv.FormatFloat(float64(v), floatFormat, 3, 64)
	case float64:
		return strconv.FormatFloat(v, floatFormat, 3, 64)
	case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
		return fmt.Sprintf("%d", value)
	case string:
		return escapeString(v)
	default:
		return escapeString(fmt.Sprintf("%+v", value))
	}
}

var stringBufPool = sync.Pool{
	New: func() interface{} { return new(bytes.Buffer) },
}

func escapeString(s string) string {
	needsQuotes := false
	needsEscape := false
	for _, r := range s {
		if r <= ' ' || r == '=' || r == '"' {
			needsQuotes = true
		}
		if r == '\\' || r == '"' || r == '\n' || r == '\r' || r == '\t' {
			needsEscape = true
		}
	}
	if needsEscape == false && needsQuotes == false {
		return s
	}
	e := stringBufPool.Get().(*bytes.Buffer)
	e.WriteByte('"')
	for _, r := range s {
		switch r {
		case '\\', '"':
			e.WriteByte('\\')
			e.WriteByte(byte(r))
		case '\n':
			e.WriteString("\\n")
		case '\r':
			e.WriteString("\\r")
		case '\t':
			e.WriteString("\\t")
		default:
			e.WriteRune(r)
		}
	}
	e.WriteByte('"')
	var ret string
	if needsQuotes {
		ret = e.String()
	} else {
		ret = string(e.Bytes()[1 : e.Len()-1])
	}
	e.Reset()
	stringBufPool.Put(e)
	return ret
}


text:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Sloth.UnitTests.Core
{
    public class MessageOnlyWindow : Form
    {
        public bool NullEventReceived { get; set; }

        public MessageOnlyWindow()
        {
            NullEventReceived = false;
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            ChangeToMessageOnlyWindow();
        }

        private void ChangeToMessageOnlyWindow()
        {
            IntPtr HWND_MESSAGE = new IntPtr(-3);
            NativeMethods.SetParent(this.Handle, HWND_MESSAGE);
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x0)
            {
                NullEventReceived = true;
            }
            base.WndProc(ref m);
        }

        internal static class NativeMethods
        {
            [DllImport("user32.dll")]
            internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        }
    }
}


text:
FROM openjdk:12-alpine
COPY ./grabber.jar /tmp/grabber.jar
ENTRYPOINT ["java", "-jar", "/tmp/grabber.jar"]


text:
from __future__ import annotations

import logging
from typing import (
    Any, Awaitable, Callable, Dict, List, Optional, Tuple,
    Union, TYPE_CHECKING)

from opentrons.calibration_storage import get
from opentrons.calibration_storage.types import TipLengthCalNotFound
from opentrons.calibration_storage import helpers
from opentrons.config import feature_flags as ff
from opentrons.hardware_control import robot_calibration as robot_cal
from opentrons.hardware_control import ThreadManager, CriticalPoint
from opentrons.hardware_control.pipette import Pipette
from opentrons.protocol_api import labware
from opentrons.protocols.geometry import deck
from opentrons.types import Mount, Point, Location

from robot_server.robot.calibration.constants import \
    TIP_RACK_LOOKUP_BY_MAX_VOL
from robot_server.service.errors import RobotServerError
from opentrons.util import linal

from robot_server.service.session.models.command import (
    CalibrationCommand, DeckCalibrationCommand)
from robot_server.robot.calibration.constants import (
    SHORT_TRASH_DECK, STANDARD_DECK, MOVE_TO_DECK_SAFETY_BUFFER,
    MOVE_TO_TIP_RACK_SAFETY_BUFFER, POINT_ONE_ID, POINT_TWO_ID,
    POINT_THREE_ID)
import robot_server.robot.calibration.util as uf
from .constants import (
    DeckCalibrationState as State,
    JOG_TO_DECK_SLOT,
    TIP_RACK_SLOT,
    MOVE_POINT_STATE_MAP,
    SAVE_POINT_STATE_MAP)
from .state_machine import DeckCalibrationStateMachine
from ..errors import CalibrationError
from ..helper_classes import (
    RequiredLabware,
    AttachedPipette)

if TYPE_CHECKING:
    from .dev_types import SavedPoints, ExpectedPoints

MODULE_LOG = logging.getLogger(__name__)

"""
A collection of functions that allow a consumer to prepare and update
calibration data associated with the orientations of the robot's deck
and gantry system.
"""

# TODO: BC 2020-07-08: type all command logic here with actual Model type
COMMAND_HANDLER = Callable[..., Awaitable]

COMMAND_MAP = Dict[str, COMMAND_HANDLER]

def tuplefy_cal_point_dicts(
        pt_dicts: Union[ExpectedPoints, SavedPoints]) -> linal.SolvePoints:
    return (
        tuple(pt_dicts[POINT_ONE_ID]),  # type: ignore
        tuple(pt_dicts[POINT_TWO_ID]),
        tuple(pt_dicts[POINT_THREE_ID])
        )

class DeckCalibrationUserFlow:
    def __init__(self,
                 hardware: ThreadManager):
        self._hardware = hardware
        self._hw_pipette, self._mount = self._select_target_pipette()

        deck_load_name = SHORT_TRASH_DECK if ff.short_fixed_trash() \
            else STANDARD_DECK
        self._deck = deck.Deck(load_name=deck_load_name)
        self._tip_rack = self._get_tip_rack_lw()
        self._deck[TIP_RACK_SLOT] = self._tip_rack

        self._current_state = State.sessionStarted
        self._state_machine = DeckCalibrationStateMachine()

        self._tip_origin_pt: Optional[Point] = None
        self._z_height_reference: Optional[float] = None
        self._expected_points = self._build_expected_points_dict()
        self._saved_points: SavedPoints = {}

        self._command_map: COMMAND_MAP = {
            CalibrationCommand.load_labware: self.load_labware,
            CalibrationCommand.jog: self.jog,
            CalibrationCommand.pick_up_tip: self.pick_up_tip,
            CalibrationCommand.invalidate_tip: self.invalidate_tip,
            CalibrationCommand.save_offset: self.save_offset,
            CalibrationCommand.move_to_tip_rack: self.move_to_tip_rack,
            CalibrationCommand.move_to_deck: self.move_to_deck,
            CalibrationCommand.move_to_point_one: self.move_to_point_one,
            DeckCalibrationCommand.move_to_point_two: self.move_to_point_two,
            DeckCalibrationCommand.move_to_point_three: self.move_to_point_three,  # noqa: E501
            CalibrationCommand.exit: self.exit_session,
        }

    @property
    def hardware(self) -> ThreadManager:
        return self._hardware

    @property
    def current_state(self) -> State:
        return self._current_state

    def get_pipette(self) -> Optional[AttachedPipette]:
        # TODO(mc, 2020-09-17): s/tip_length/tipLength
        # TODO(mc, 2020-09-17): type of pipette_id does not match expected
        # type of AttachedPipette.serial
        return AttachedPipette(  # type: ignore[call-arg]
            model=self._hw_pipette.model,
            name=self._hw_pipette.name,
            tip_length=self._hw_pipette.config.tip_length,
            mount=str(self._mount),
            serial=self._hw_pipette.pipette_id)  # type: ignore[arg-type]

    def get_required_labware(self) -> List[RequiredLabware]:
        lw = self._get_tip_rack_lw()
        return [RequiredLabware.from_lw(lw)]

    def _set_current_state(self, to_state: State):
        self._current_state = to_state

    def _select_target_pipette(self) -> Tuple[Pipette, Mount]:
        """
        Select pipette for calibration based on:
        1: smaller max volume
        2: single-channel over multi
        3: right mount over left
        """
        if not any(self._hardware._attached_instruments.values()):
            raise RobotServerError(
                definition=CalibrationError.NO_PIPETTE_ATTACHED,
                flow='Deck Calibration')
        pips = {m: p for m, p in self._hardware._attached_instruments.items()
                if p}
        if len(pips) == 1:
            for mount, pip in pips.items():
                return pip, mount

        right_pip = pips[Mount.RIGHT]
        left_pip = pips[Mount.LEFT]
        if right_pip.config.max_volume > left_pip.config.max_volume or \
                right_pip.config.channels > left_pip.config.channels:
            return left_pip, Mount.LEFT
        else:
            return right_pip, Mount.RIGHT

    def _get_tip_rack_lw(self) -> labware.Labware:
        pip_vol = self._hw_pipette.config.max_volume
        lw_load_name = TIP_RACK_LOOKUP_BY_MAX_VOL[str(pip_vol)].load_name
        return labware.load(
            lw_load_name, self._deck.position_for(TIP_RACK_SLOT))

    def _initialize_deck(self):
        tip_rack_lw = self._get_tip_rack_lw()
        self._deck[TIP_RACK_SLOT] = tip_rack_lw

    def _build_expected_points_dict(self) -> ExpectedPoints:
        pos_1 = self._deck.get_calibration_position(POINT_ONE_ID).position
        pos_2 = self._deck.get_calibration_position(POINT_TWO_ID).position
        pos_3 = self._deck.get_calibration_position(POINT_THREE_ID).position
        exp_pt: ExpectedPoints = {
            POINT_ONE_ID: Point(*pos_1)._replace(z=1.0),
            POINT_TWO_ID: Point(*pos_2)._replace(z=1.0),
            POINT_THREE_ID: Point(*pos_3)._replace(z=1.0)
        }
        return exp_pt

    async def handle_command(self,
                             name: Any,
                             data: Dict[Any, Any]):
        """
        Handle a client command

        :param name: Name of the command
        :param data: Data supplied in command
        :return: None
        """
        next_state = self._state_machine.get_next_state(self._current_state,
                                                        name)

        handler = self._command_map.get(name)
        if handler is not None:
            await handler(**data)
        self._set_current_state(next_state)
        MODULE_LOG.debug(
            f'DeckCalUserFlow handled command {name}, transitioned'
            f'from {self._current_state} to {next_state}')

    def _get_critical_point_override(self) -> Optional[CriticalPoint]:
        return (CriticalPoint.FRONT_NOZZLE if
                self._hw_pipette.config.channels == 8 else None)

    async def _get_current_point(
            self,
            critical_point: CriticalPoint = None) -> Point:
        return await self._hardware.gantry_position(self._mount,
                                                    critical_point)

    async def load_labware(self):
        pass

    async def jog(self, vector):
        await self._hardware.move_rel(mount=self._mount,
                                      delta=Point(*vector))

    async def move_to_tip_rack(self):
        point = self._tip_rack.wells()[0].top().point + \
                MOVE_TO_TIP_RACK_SAFETY_BUFFER
        to_loc = Location(point, None)
        await self._move(to_loc)

    async def move_to_deck(self):
        deck_pt = self._deck.get_slot_center(JOG_TO_DECK_SLOT)
        ydim = self._deck.get_slot_definition(
            JOG_TO_DECK_SLOT)['boundingBox']['yDimension']
        new_pt = deck_pt - Point(0, (ydim/2), deck_pt.z) + \
            MOVE_TO_DECK_SAFETY_BUFFER
        to_loc = Location(new_pt, None)
        await self._move(to_loc)

    def _get_move_to_point_loc_by_state(self) -> Location:
        assert self._z_height_reference is not None, \
            "saveOffset has not been called yet"
        pt_id = MOVE_POINT_STATE_MAP[self._current_state]
        coords = self._deck.get_calibration_position(pt_id).position
        loc = Location(Point(*coords), None)
        return loc.move(point=Point(0, 0, self._z_height_reference))

    async def move_to_point_one(self):
        await self._move(self._get_move_to_point_loc_by_state())

    async def move_to_point_two(self):
        await self._move(self._get_move_to_point_loc_by_state())

    async def move_to_point_three(self):
        await self._move(self._get_move_to_point_loc_by_state())

    async def save_offset(self):
        cur_pt = await self._get_current_point(critical_point=None)
        if self.current_state == State.joggingToDeck:
            self._z_height_reference = cur_pt.z
        else:
            pt_id = SAVE_POINT_STATE_MAP[self._current_state]
            self._saved_points[pt_id] = cur_pt

            if self._current_state == State.savingPointThree:
                self._save_attitude_matrix()

    def _save_attitude_matrix(self):
        e = tuplefy_cal_point_dicts(self._expected_points)
        a = tuplefy_cal_point_dicts(self._saved_points)
        tiprack_hash = helpers.hash_labware_def(self._tip_rack._definition)
        pip_id = self._hw_pipette.pipette_id
        assert pip_id
        robot_cal.save_attitude_matrix(expected=e, actual=a, pipette_id=pip_id,
                                       tiprack_hash=tiprack_hash)

    def _get_tip_length(self) -> float:
        pip_id = self._hw_pipette.pipette_id
        assert pip_id
        try:
            return get.load_tip_length_calibration(pip_id,
                                                   self._tip_rack._definition,
                                                   '')['tipLength']
        except TipLengthCalNotFound:
            tip_overlap = self._hw_pipette.config.tip_overlap.get(
                self._tip_rack.uri,
                self._hw_pipette.config.tip_overlap['default'])
            tip_length = self._tip_rack.tip_length
            return tip_length - tip_overlap

    async def pick_up_tip(self):
        await uf.pick_up_tip(self, tip_length=self._get_tip_length())

    async def invalidate_tip(self):
        await uf.invalidate_tip(self)

    async def _return_tip(self):
        await uf.return_tip(self, tip_length=self._get_tip_length())

    async def _move(self, to_loc: Location):
        await uf.move(self, to_loc)

    async def exit_session(self):
        await self.move_to_tip_rack()
        await self._return_tip()


text:
Request:
```http
POST /2.3/orders/ HTTP/1.1
Content-Type: application/json

{
    "accessId": "STTA0001",
    "service": "BB-100-10",
    "operation": "ACTIVATE",
    "forcedTakeover": false,
    "equipment": [
        { "vendorId": "CH_BROADBAND" }
    ],
    "spReference": ""
}
```

Response:
```http
HTTP/1.1 201 CREATED
Last-Modified: Fri, 31 Aug 2012 12:03:28 GMT
Location: /2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061
Content-Type: application/json

{
    "path": "/pubapi.php/2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061",
    "accessId": "STTA0001",
    "service": "BB-100-10",
    "operation": "ACTIVATE",
    "state": "RECEIVED",
    "message": ""
}
```

## Orderläggning, Exempel: Avaktivering

Request:
```http
POST /2.3/orders/ HTTP/1.1
Content-Type: application/json

{
    "accessId": "STTA0001",
    "service": "BB-100-10",
    "operation": "DEACTIVATE"
}
```

Response:
```http
HTTP/1.1 201 CREATED
Last-Modified: Fri, 31 Aug 2012 12:03:28 GMT
Location: /2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061
Content-Type: application/json

{
    "path": "/pubapi.php/2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061",
    "accessId": "STTA0001",
    "service": "BB-100-10",
    "operation": "DEACTIVATE",
    "state": "RECEIVED",
    "message": ""
}
```

## Orderläggning - Fältbeskrivningar

            Fält
            Förklaring

                accessId

                Ett, per kommunikationsoperatör, unikt ID på en access.
Får enbart bestå av tecknen a-z, A-Z, 0-9. text, obligatoriskt, max 32 tecken, [a-zA-Z0-9]+

                service

                Anger teknisk tjänst som skall aktiveras/avaktiveras på accessen.

                Värden för tekniska tjänster är KO-specifika och erhålls genom Feasibility-APIt. text, obligatoriskt

                operation

               Anger om tjänsten skall aktiveras eller avaktiveras.

               Giltiga värden: "ACTIVATE", "DEACTIVATE". text, obligatoriskt

                forcedTakeover

                Anger om anropande TLs beställning skall ersätta annan Service Providers aktiva tjänster. Det behöver enbart fungera om Feasibility indikerat att funktionen skall fungera. Det gäller enbart för ACTIVATE-ordrar. Skall inte skickas vid DEACTIVATE.
Stöd för forcedTakeover är inte obligatoriskt, men i de fall det inte stöds skall tjänsten ändå kunna ta emot en fullständig beställning med "forcedTakeover: false".
                boolean (true/false), obligatoriskt för ACTIVATE

                equipment

                Equipment innehåller en lista över den utrustning som kan användas för att avgöra vilken tjänst/KO en tjänst tillhör hos kunden.

                Ett use-case är vid Single-Play-Telefoni, där en TL använder en trådlös router för enbart Telefoni. Då behöver KO kunna avgöra att VendorId CH_BROADBAND skall användas för Telefoni istället för bredband.

                Listan är per tjänst, och den fullständiga listan skall alltid skickas vid varje aktivering.

                Vid avaktivering skall listan av equipment rensas.

                När en order enbart avser ändring av utrustning kan KO välja att starta en order för det, eller svara direkt med att det är utfört.

                equipment.vendorId

                text, obligatoriskt

                Exempel: "CH_BROADBAND"

                spReference

                `spReference` anger TLs referens på tjänsten. Används av TL för korrelering.

                Sträng, max 255 tecken

Gemensamt för alla fält är att de måste finnas i JSON-strukturen och inte vara null.

## Felhantering och beteende vid orderläggning

Vid order med korrekt format och korrekt innehåll skall svaret se ut på följande sätt:

```http
HTTP/1.1 201 CREATED
Content-Type: application/json
Location: /2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061

{
    "path": "/pubapi.php/2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061",
    "accessId": "STTA0001",
    "service": "BB-100-10",
    "operation": "ACTIVATE",
    "state": "RECEIVED",
    "message": ""
}
```

Vid en inkorrekt order skall svar ske direkt med "400 Bad Request".

Det skall ske vid:

* Felaktig JSON
* Saknade fält
* Felaktigt innehåll i fält
* Felaktigt AccessId
* Felaktig Service för acceses.

```http
HTTP/1.1 400 Bad Request
Content-Type: application/json

{ "cause": "Unknown service: 'INTERNET_FLUGA'" }
```

Om en annan tjänst med samma tjänstetyp redan är aktiv.
Exempel: Bredband 100/100 är aktivt vid beställning av Bredband 10/10.:

```http
HTTP/1.1 400 Bad Request
Content-Type: application/json

{ "cause": "Another Service of ServiceType 'Broadband' is already active." }
```

Om tjänsten redan har en aktiv order:

```http
HTTP/1.1 200 OK
Content-Type: application/json

{
    "path": "/pubapi.php/2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061",
    "accessId": "STTA0001",
    "service": "BB-100-10",
    "operation": "ACTIVATE",
    "state": "RECEIVED",
    "message": ""
}
```

Om tjänsten redan är aktiv vid `ACTIVATE`, eller inaktiv vid `DEACTIVATE`:

```http
HTTP/1.1 200 OK
Content-Type: application/json

{
    "accessId": "STTA0001",
    "service": "BB-100-10",
    "operation": "ACTIVATE",
    "state": "DONE_SUCCESS",
    "message": ""
}
```

Om tjänsten (tjänstetypen) inte går att beställa för att den är tagen av en annan Service Provider:

```http
HTTP/1.1 400 Bad Request
Content-Type: application/json

{ "cause": "ServiceType is already claimed by other Service Provider." }
```

## Hämtning av Order Status - Exempel

Request:
```http
GET /2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061 HTTP/1.1
```

Response:
```http
HTTP/1.1 200 OK
Content-Type: application/json

{
    "path": "/pubapi.php/2.3/orders/ec4bc754-6a30-11e2-a585-4fc569183061",
    "accessId": "STTA0001",
    "service": "BB-100-10",
    "operation": "ACTIVATE",
    "state": "RECEIVED",
    "message": ""
}
```

## Hämtning av Order Status - Fältbeskrivningar

            Fält
            Förklaring

                path

               Path till order. Anges alltid från /. text, obligatoriskt

                state

               Anger orderns status. Statusen är "RECEIVED" tills tjänsten är aktiverad eller har misslyckats. När ordern lyckas skall state bli "DONE_SUCCESS". När ordern misslyckas skall state uppdateras till "DONE_FAILED". Ordern får sedan aldrig ändra state.

               Giltiga värden: "RECEIVED", "DONE_SUCCESS", "DONE_FAILED". text, obligatoriskt

                message

               Om en order misslyckas (state == "DONE_FAILED"), kan message användas för att beskriva varför. Fältet används inte annars. Fältet skall alltid finnas men får vara tomt. text, obligatoriskt*


text:
package org.ow2.chameleon.fuchsia.raspberry.pi.internal;

import org.osgi.framework.Filter;
import org.ow2.chameleon.fuchsia.core.FuchsiaUtils;
import org.ow2.chameleon.fuchsia.core.declaration.ImportDeclaration;
import org.ow2.chameleon.fuchsia.core.exceptions.BinderException;
import org.ow2.chameleon.fuchsia.core.exceptions.InvalidFilterException;

import java.util.Map;

import static org.ow2.chameleon.fuchsia.core.declaration.Constants.ID;
import static org.ow2.chameleon.fuchsia.raspberry.pi.internal.Constants.IMPORTER_GPIO_NAME;
import static org.ow2.chameleon.fuchsia.raspberry.pi.internal.Constants.IMPORTER_GPIO_PIN;

/**
 * Makes easier to access the Declaration metadata.
 */
public final class GPIOImportDeclarationWrapper {

    private static Filter declarationFilter = buildFilter();

    private String id;
    private String pin;
    private String name;

    private GPIOImportDeclarationWrapper() {

    }

    private static Filter buildFilter() {
        Filter filter;
        String stringFilter = String.format("(&(%s=*)(%s=*)(%s=*))", ID, IMPORTER_GPIO_NAME, IMPORTER_GPIO_PIN);
        try {
            filter = FuchsiaUtils.getFilter(stringFilter);
        } catch (InvalidFilterException e) {
            throw new IllegalStateException(e);
        }
        return filter;
    }

    public static GPIOImportDeclarationWrapper create(ImportDeclaration importDeclaration) throws BinderException {
        Map<String, Object> metadata = importDeclaration.getMetadata();
        if (!declarationFilter.matches(metadata)) {
            throw new BinderException("Not enough information provided to create GPIO Importer");
        }

        GPIOImportDeclarationWrapper wrapper = new GPIOImportDeclarationWrapper();

        wrapper.id = (String) metadata.get(ID);
        wrapper.pin = (String) metadata.get(IMPORTER_GPIO_PIN);
        wrapper.name = (String) metadata.get(IMPORTER_GPIO_NAME);

        return wrapper;
    }

    public String getId() {
        return id;
    }

    public String getPin() {
        return pin;
    }

    public String getName() {
        return name;
    }
}


text:
package com.microsoft.azure.management.streamanalytics.v2016_03_01.implementation;

import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.StreamingJob;
import rx.Observable;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.Sku;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.OutputStartMode;
import org.joda.time.DateTime;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.EventsOutOfOrderPolicy;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.OutputErrorPolicy;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.CompatibilityLevel;
import java.util.List;
import java.util.ArrayList;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.Function;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.Input;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.Output;
import com.microsoft.azure.management.streamanalytics.v2016_03_01.Transformation;

class StreamingJobImpl extends GroupableResourceCoreImpl<StreamingJob, StreamingJobInner, StreamingJobImpl, StreamAnalyticsManager> implements StreamingJob, StreamingJob.Definition, StreamingJob.Update {
    StreamingJobImpl(String name, StreamingJobInner inner, StreamAnalyticsManager manager) {
        super(name, inner, manager);
    }

    @Override
    public Observable<StreamingJob> createResourceAsync() {
        StreamingJobsInner client = this.manager().inner().streamingJobs();
        return client.createOrReplaceAsync(this.resourceGroupName(), this.name(), this.inner())
            .map(innerToFluentMap(this));
    }

    @Override
    public Observable<StreamingJob> updateResourceAsync() {
        StreamingJobsInner client = this.manager().inner().streamingJobs();
        return client.updateAsync(this.resourceGroupName(), this.name(), this.inner())
            .map(innerToFluentMap(this));
    }

    @Override
    protected Observable<StreamingJobInner> getInnerAsync() {
        StreamingJobsInner client = this.manager().inner().streamingJobs();
        return client.getByResourceGroupAsync(this.resourceGroupName(), this.name());
    }

    @Override
    public boolean isInCreateMode() {
        return this.inner().id() == null;
    }

    @Override
    public CompatibilityLevel compatibilityLevel() {
        return this.inner().compatibilityLevel();
    }

    @Override
    public DateTime createdDate() {
        return this.inner().createdDate();
    }

    @Override
    public String dataLocale() {
        return this.inner().dataLocale();
    }

    @Override
    public String etag() {
        return this.inner().etag();
    }

    @Override
    public Integer eventsLateArrivalMaxDelayInSeconds() {
        return this.inner().eventsLateArrivalMaxDelayInSeconds();
    }

    @Override
    public Integer eventsOutOfOrderMaxDelayInSeconds() {
        return this.inner().eventsOutOfOrderMaxDelayInSeconds();
    }

    @Override
    public EventsOutOfOrderPolicy eventsOutOfOrderPolicy() {
        return this.inner().eventsOutOfOrderPolicy();
    }

    @Override
    public List<Function> functions() {
        List<Function> lst = new ArrayList<Function>();
        if (this.inner().functions() != null) {
            for (FunctionInner inner : this.inner().functions()) {
                lst.add( new FunctionImpl(inner, manager()));
            }
        }
        return lst;
    }

    @Override
    public List<Input> inputs() {
        List<Input> lst = new ArrayList<Input>();
        if (this.inner().inputs() != null) {
            for (InputInner inner : this.inner().inputs()) {
                lst.add( new InputImpl(inner, manager()));
            }
        }
        return lst;
    }

    @Override
    public String jobId() {
        return this.inner().jobId();
    }

    @Override
    public String jobState() {
        return this.inner().jobState();
    }

    @Override
    public DateTime lastOutputEventTime() {
        return this.inner().lastOutputEventTime();
    }

    @Override
    public OutputErrorPolicy outputErrorPolicy() {
        return this.inner().outputErrorPolicy();
    }

    @Override
    public List<Output> outputs() {
        List<Output> lst = new ArrayList<Output>();
        if (this.inner().outputs() != null) {
            for (OutputInner inner : this.inner().outputs()) {
                lst.add( new OutputImpl(inner, manager()));
            }
        }
        return lst;
    }

    @Override
    public OutputStartMode outputStartMode() {
        return this.inner().outputStartMode();
    }

    @Override
    public DateTime outputStartTime() {
        return this.inner().outputStartTime();
    }

    @Override
    public String provisioningState() {
        return this.inner().provisioningState();
    }

    @Override
    public Sku sku() {
        return this.inner().sku();
    }

    @Override
    public Transformation transformation() {
        TransformationInner inner = this.inner().transformation();
        if (inner != null) {
            return  new TransformationImpl(inner, manager());
        } else {
            return null;
        }
    }

    @Override
    public StreamingJobImpl withCompatibilityLevel(CompatibilityLevel compatibilityLevel) {
        this.inner().withCompatibilityLevel(compatibilityLevel);
        return this;
    }

    @Override
    public StreamingJobImpl withDataLocale(String dataLocale) {
        this.inner().withDataLocale(dataLocale);
        return this;
    }

    @Override
    public StreamingJobImpl withEventsLateArrivalMaxDelayInSeconds(Integer eventsLateArrivalMaxDelayInSeconds) {
        this.inner().withEventsLateArrivalMaxDelayInSeconds(eventsLateArrivalMaxDelayInSeconds);
        return this;
    }

    @Override
    public StreamingJobImpl withEventsOutOfOrderMaxDelayInSeconds(Integer eventsOutOfOrderMaxDelayInSeconds) {
        this.inner().withEventsOutOfOrderMaxDelayInSeconds(eventsOutOfOrderMaxDelayInSeconds);
        return this;
    }

    @Override
    public StreamingJobImpl withEventsOutOfOrderPolicy(EventsOutOfOrderPolicy eventsOutOfOrderPolicy) {
        this.inner().withEventsOutOfOrderPolicy(eventsOutOfOrderPolicy);
        return this;
    }

    @Override
    public StreamingJobImpl withFunctions(List<FunctionInner> functions) {
        this.inner().withFunctions(functions);
        return this;
    }

    @Override
    public StreamingJobImpl withInputs(List<InputInner> inputs) {
        this.inner().withInputs(inputs);
        return this;
    }

    @Override
    public StreamingJobImpl withOutputErrorPolicy(OutputErrorPolicy outputErrorPolicy) {
        this.inner().withOutputErrorPolicy(outputErrorPolicy);
        return this;
    }

    @Override
    public StreamingJobImpl withOutputs(List<OutputInner> outputs) {
        this.inner().withOutputs(outputs);
        return this;
    }

    @Override
    public StreamingJobImpl withOutputStartMode(OutputStartMode outputStartMode) {
        this.inner().withOutputStartMode(outputStartMode);
        return this;
    }

    @Override
    public StreamingJobImpl withOutputStartTime(DateTime outputStartTime) {
        this.inner().withOutputStartTime(outputStartTime);
        return this;
    }

    @Override
    public StreamingJobImpl withSku(Sku sku) {
        this.inner().withSku(sku);
        return this;
    }

    @Override
    public StreamingJobImpl withTransformation(TransformationInner transformation) {
        this.inner().withTransformation(transformation);
        return this;
    }

}


text:
package eu.scasefp7.eclipse.core.ui.preferences.internal;

/**
 * @author emaorli
 *
 */
public class DomainEntry {
	private String name = null;
	private DomainEntry[] children = null;
	private DomainEntry parent = null;
	private int	id;

	/**
	 * Create the object using supplied values.
	 *
	 * @param id for the domain
	 * @param name of the domain
	 * @param children of the domain
	 */
	public DomainEntry (int id, String name, DomainEntry[] children) {
		setId(id);
		setName(name);
		setChildren(children);
	}

	/**
	 * Create the object using supplied values.
	 *
	 * @param id of the domain
	 * @param name of the domain
	 */
	public DomainEntry (int id, String name) {
		setId(id);
		setName(name);
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the children
	 */
	public DomainEntry[] getChildren() {
		return children;
	}
	/**
	 * @param children the children to set
	 */
	public void setChildren(DomainEntry[] children) {
		this.children = children;

		for(int ix=0; ix<children.length; ix++) {
			children[ix].setParent(this);
		}
	}
	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the parent
	 */
	public DomainEntry getParent() {
		return parent;
	}

	/**
	 * @param parent the parent to set
	 */
	public void setParent(DomainEntry parent) {
		this.parent = parent;
	}

	/**
	 * @return true if the entry has children
	 */
	public boolean hasChildren() {
		return this.getChildren() != null && this.getChildren().length > 0;
	}

}


text:
package com.google.android.exoplayer2;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Pair;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectorResult;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * An {@link ExoPlayer} implementation. Instances can be obtained from {@link ExoPlayerFactory}.
 */
/* package */ final class ExoPlayerImpl implements ExoPlayer {

  private static final String TAG = "ExoPlayerImpl";

  private final Renderer[] renderers;
  private final TrackSelector trackSelector;
  private final TrackSelectorResult emptyTrackSelectorResult;
  private final Handler eventHandler;
  private final ExoPlayerImplInternal internalPlayer;
  private final Handler internalPlayerHandler;
  private final CopyOnWriteArraySet<Player.EventListener> listeners;
  private final Timeline.Window window;
  private final Timeline.Period period;

  private boolean playWhenReady;
  private @RepeatMode int repeatMode;
  private boolean shuffleModeEnabled;
  private int pendingOperationAcks;
  private boolean hasPendingPrepare;
  private boolean hasPendingSeek;
  private PlaybackParameters playbackParameters;
  private @Nullable ExoPlaybackException playbackError;

  // Playback information when there is no pending seek/set source operation.
  private PlaybackInfo playbackInfo;

  // Playback information when there is a pending seek/set source operation.
  private int maskingWindowIndex;
  private int maskingPeriodIndex;
  private long maskingWindowPositionMs;

  /**
   * Constructs an instance. Must be called from a thread that has an associated {@link Looper}.
   *
   * @param renderers The {@link Renderer}s that will be used by the instance.
   * @param trackSelector The {@link TrackSelector} that will be used by the instance.
   * @param loadControl The {@link LoadControl} that will be used by the instance.
   * @param clock The {@link Clock} that will be used by the instance.
   */
  @SuppressLint("HandlerLeak")
  public ExoPlayerImpl(
      Renderer[] renderers, TrackSelector trackSelector, LoadControl loadControl, Clock clock) {
    Log.i(TAG, "Init " + Integer.toHexString(System.identityHashCode(this)) + " ["
        + ExoPlayerLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "]");
    Assertions.checkState(renderers.length > 0);
    this.renderers = Assertions.checkNotNull(renderers);
    this.trackSelector = Assertions.checkNotNull(trackSelector);
    this.playWhenReady = false;
    this.repeatMode = Player.REPEAT_MODE_OFF;
    this.shuffleModeEnabled = false;
    this.listeners = new CopyOnWriteArraySet<>();
    emptyTrackSelectorResult =
        new TrackSelectorResult(
            new RendererConfiguration[renderers.length],
            new TrackSelection[renderers.length],
            null);
    window = new Timeline.Window();
    period = new Timeline.Period();
    playbackParameters = PlaybackParameters.DEFAULT;
    Looper eventLooper = Looper.myLooper() != null ? Looper.myLooper() : Looper.getMainLooper();
    eventHandler = new Handler(eventLooper) {
      @Override
      public void handleMessage(Message msg) {
        ExoPlayerImpl.this.handleEvent(msg);
      }
    };
    playbackInfo =
        new PlaybackInfo(
            Timeline.EMPTY,
            /* startPositionUs= */ 0,
            TrackGroupArray.EMPTY,
            emptyTrackSelectorResult);
    internalPlayer =
        new ExoPlayerImplInternal(
            renderers,
            trackSelector,
            emptyTrackSelectorResult,
            loadControl,
            playWhenReady,
            repeatMode,
            shuffleModeEnabled,
            eventHandler,
            this,
            clock);
    internalPlayerHandler = new Handler(internalPlayer.getPlaybackLooper());
  }

  @Override
  public VideoComponent getVideoComponent() {
    return null;
  }

  @Override
  public TextComponent getTextComponent() {
    return null;
  }

  @Override
  public Looper getPlaybackLooper() {
    return internalPlayer.getPlaybackLooper();
  }

  @Override
  public void addListener(Player.EventListener listener) {
    listeners.add(listener);
  }

  @Override
  public void removeListener(Player.EventListener listener) {
    listeners.remove(listener);
  }

  @Override
  public int getPlaybackState() {
    return playbackInfo.playbackState;
  }

  @Override
  public @Nullable ExoPlaybackException getPlaybackError() {
    return playbackError;
  }

  @Override
  public void prepare(MediaSource mediaSource) {
    prepare(mediaSource, true, true);
  }

  @Override
  public void prepare(MediaSource mediaSource, boolean resetPosition, boolean resetState) {
    playbackError = null;
    PlaybackInfo playbackInfo =
        getResetPlaybackInfo(
            resetPosition, resetState, /* playbackState= */ Player.STATE_BUFFERING);
    // Trigger internal prepare first before updating the playback info and notifying external
    // listeners to ensure that new operations issued in the listener notifications reach the
    // player after this prepare. The internal player can't change the playback info immediately
    // because it uses a callback.
    hasPendingPrepare = true;
    pendingOperationAcks++;
    internalPlayer.prepare(mediaSource, resetPosition, resetState);
    updatePlaybackInfo(
        playbackInfo,
        /* positionDiscontinuity= */ false,
        /* ignored */ DISCONTINUITY_REASON_INTERNAL,
        TIMELINE_CHANGE_REASON_RESET,
        /* seekProcessed= */ false);
  }

  @Override
  public void setPlayWhenReady(boolean playWhenReady) {
    if (this.playWhenReady != playWhenReady) {
      this.playWhenReady = playWhenReady;
      internalPlayer.setPlayWhenReady(playWhenReady);
      PlaybackInfo playbackInfo = this.playbackInfo;
      for (Player.EventListener listener : listeners) {
        listener.onPlayerStateChanged(playWhenReady, playbackInfo.playbackState);
      }
    }
  }

  @Override
  public boolean getPlayWhenReady() {
    return playWhenReady;
  }

  @Override
  public void setRepeatMode(@RepeatMode int repeatMode) {
    if (this.repeatMode != repeatMode) {
      this.repeatMode = repeatMode;
      internalPlayer.setRepeatMode(repeatMode);
      for (Player.EventListener listener : listeners) {
        listener.onRepeatModeChanged(repeatMode);
      }
    }
  }

  @Override
  public @RepeatMode int getRepeatMode() {
    return repeatMode;
  }

  @Override
  public void setShuffleModeEnabled(boolean shuffleModeEnabled) {
    if (this.shuffleModeEnabled != shuffleModeEnabled) {
      this.shuffleModeEnabled = shuffleModeEnabled;
      internalPlayer.setShuffleModeEnabled(shuffleModeEnabled);
      for (Player.EventListener listener : listeners) {
        listener.onShuffleModeEnabledChanged(shuffleModeEnabled);
      }
    }
  }

  @Override
  public boolean getShuffleModeEnabled() {
    return shuffleModeEnabled;
  }

  @Override
  public boolean isLoading() {
    return playbackInfo.isLoading;
  }

  @Override
  public void seekToDefaultPosition() {
    seekToDefaultPosition(getCurrentWindowIndex());
  }

  @Override
  public void seekToDefaultPosition(int windowIndex) {
    seekTo(windowIndex, C.TIME_UNSET);
  }

  @Override
  public void seekTo(long positionMs) {
    seekTo(getCurrentWindowIndex(), positionMs);
  }

  @Override
  public void seekTo(int windowIndex, long positionMs) {
    Timeline timeline = playbackInfo.timeline;
    if (windowIndex < 0 || (!timeline.isEmpty() && windowIndex >= timeline.getWindowCount())) {
      throw new IllegalSeekPositionException(timeline, windowIndex, positionMs);
    }
    hasPendingSeek = true;
    pendingOperationAcks++;
    if (isPlayingAd()) {
      // TODO: Investigate adding support for seeking during ads. This is complicated to do in
      // general because the midroll ad preceding the seek destination must be played before the
      // content position can be played, if a different ad is playing at the moment.
      Log.w(TAG, "seekTo ignored because an ad is playing");
      eventHandler
          .obtainMessage(
              ExoPlayerImplInternal.MSG_PLAYBACK_INFO_CHANGED,
              /* operationAcks */ 1,
              /* positionDiscontinuityReason */ C.INDEX_UNSET,
              playbackInfo)
          .sendToTarget();
      return;
    }
    maskingWindowIndex = windowIndex;
    if (timeline.isEmpty()) {
      maskingWindowPositionMs = positionMs == C.TIME_UNSET ? 0 : positionMs;
      maskingPeriodIndex = 0;
    } else {
      long windowPositionUs = positionMs == C.TIME_UNSET
          ? timeline.getWindow(windowIndex, window).getDefaultPositionUs() : C.msToUs(positionMs);
      Pair<Integer, Long> periodIndexAndPositon =
          timeline.getPeriodPosition(window, period, windowIndex, windowPositionUs);
      maskingWindowPositionMs = C.usToMs(windowPositionUs);
      maskingPeriodIndex = periodIndexAndPositon.first;
    }
    internalPlayer.seekTo(timeline, windowIndex, C.msToUs(positionMs));
    for (Player.EventListener listener : listeners) {
      listener.onPositionDiscontinuity(DISCONTINUITY_REASON_SEEK);
    }
  }

  @Override
  public void setPlaybackParameters(@Nullable PlaybackParameters playbackParameters) {
    if (playbackParameters == null) {
      playbackParameters = PlaybackParameters.DEFAULT;
    }
    internalPlayer.setPlaybackParameters(playbackParameters);
  }

  @Override
  public PlaybackParameters getPlaybackParameters() {
    return playbackParameters;
  }

  @Override
  public void setSeekParameters(@Nullable SeekParameters seekParameters) {
    if (seekParameters == null) {
      seekParameters = SeekParameters.DEFAULT;
    }
    internalPlayer.setSeekParameters(seekParameters);
  }

  @Override
  public @Nullable Object getCurrentTag() {
    int windowIndex = getCurrentWindowIndex();
    return windowIndex > playbackInfo.timeline.getWindowCount()
        ? null
        : playbackInfo.timeline.getWindow(windowIndex, window, /* setTag= */ true).tag;
  }

  @Override
  public void stop() {
    stop(/* reset= */ false);
  }

  @Override
  public void stop(boolean reset) {
    if (reset) {
      playbackError = null;
    }
    PlaybackInfo playbackInfo =
        getResetPlaybackInfo(
            /* resetPosition= */ reset,
            /* resetState= */ reset,
            /* playbackState= */ Player.STATE_IDLE);
    // Trigger internal stop first before updating the playback info and notifying external
    // listeners to ensure that new operations issued in the listener notifications reach the
    // player after this stop. The internal player can't change the playback info immediately
    // because it uses a callback.
    pendingOperationAcks++;
    internalPlayer.stop(reset);
    updatePlaybackInfo(
        playbackInfo,
        /* positionDiscontinuity= */ false,
        /* ignored */ DISCONTINUITY_REASON_INTERNAL,
        TIMELINE_CHANGE_REASON_RESET,
        /* seekProcessed= */ false);
  }

  @Override
  public void release() {
    Log.i(TAG, "Release " + Integer.toHexString(System.identityHashCode(this)) + " ["
        + ExoPlayerLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "] ["
        + ExoPlayerLibraryInfo.registeredModules() + "]");
    internalPlayer.release();
    eventHandler.removeCallbacksAndMessages(null);
  }

  @Override
  public void sendMessages(ExoPlayerMessage... messages) {
    for (ExoPlayerMessage message : messages) {
      createMessage(message.target).setType(message.messageType).setPayload(message.message).send();
    }
  }

  @Override
  public PlayerMessage createMessage(Target target) {
    return new PlayerMessage(
        internalPlayer,
        target,
        playbackInfo.timeline,
        getCurrentWindowIndex(),
        internalPlayerHandler);
  }

  @Override
  public void blockingSendMessages(ExoPlayerMessage... messages) {
    List<PlayerMessage> playerMessages = new ArrayList<>();
    for (ExoPlayerMessage message : messages) {
      playerMessages.add(
          createMessage(message.target)
              .setType(message.messageType)
              .setPayload(message.message)
              .send());
    }
    boolean wasInterrupted = false;
    for (PlayerMessage message : playerMessages) {
      boolean blockMessage = true;
      while (blockMessage) {
        try {
          message.blockUntilDelivered();
          blockMessage = false;
        } catch (InterruptedException e) {
          wasInterrupted = true;
        }
      }
    }
    if (wasInterrupted) {
      // Restore the interrupted status.
      Thread.currentThread().interrupt();
    }
  }

  @Override
  public int getCurrentPeriodIndex() {
    if (shouldMaskPosition()) {
      return maskingPeriodIndex;
    } else {
      return playbackInfo.periodId.periodIndex;
    }
  }

  @Override
  public int getCurrentWindowIndex() {
    if (shouldMaskPosition()) {
      return maskingWindowIndex;
    } else {
      return playbackInfo.timeline.getPeriod(playbackInfo.periodId.periodIndex, period).windowIndex;
    }
  }

  @Override
  public int getNextWindowIndex() {
    Timeline timeline = playbackInfo.timeline;
    return timeline.isEmpty() ? C.INDEX_UNSET
        : timeline.getNextWindowIndex(getCurrentWindowIndex(), repeatMode, shuffleModeEnabled);
  }

  @Override
  public int getPreviousWindowIndex() {
    Timeline timeline = playbackInfo.timeline;
    return timeline.isEmpty() ? C.INDEX_UNSET
        : timeline.getPreviousWindowIndex(getCurrentWindowIndex(), repeatMode, shuffleModeEnabled);
  }

  @Override
  public long getDuration() {
    Timeline timeline = playbackInfo.timeline;
    if (timeline.isEmpty()) {
      return C.TIME_UNSET;
    }
    if (isPlayingAd()) {
      MediaPeriodId periodId = playbackInfo.periodId;
      timeline.getPeriod(periodId.periodIndex, period);
      long adDurationUs = period.getAdDurationUs(periodId.adGroupIndex, periodId.adIndexInAdGroup);
      return C.usToMs(adDurationUs);
    } else {
      return timeline.getWindow(getCurrentWindowIndex(), window).getDurationMs();
    }
  }

  @Override
  public long getCurrentPosition() {
    if (shouldMaskPosition()) {
      return maskingWindowPositionMs;
    } else {
      return playbackInfoPositionUsToWindowPositionMs(playbackInfo.positionUs);
    }
  }

  @Override
  public long getBufferedPosition() {
    // TODO - Implement this properly.
    if (shouldMaskPosition()) {
      return maskingWindowPositionMs;
    } else {
      return playbackInfoPositionUsToWindowPositionMs(playbackInfo.bufferedPositionUs);
    }
  }

  @Override
  public int getBufferedPercentage() {
    long position = getBufferedPosition();
    long duration = getDuration();
    return position == C.TIME_UNSET || duration == C.TIME_UNSET ? 0
        : (duration == 0 ? 100 : Util.constrainValue((int) ((position * 100) / duration), 0, 100));
  }

  @Override
  public boolean isCurrentWindowDynamic() {
    Timeline timeline = playbackInfo.timeline;
    return !timeline.isEmpty() && timeline.getWindow(getCurrentWindowIndex(), window).isDynamic;
  }

  @Override
  public boolean isCurrentWindowSeekable() {
    Timeline timeline = playbackInfo.timeline;
    return !timeline.isEmpty() && timeline.getWindow(getCurrentWindowIndex(), window).isSeekable;
  }

  @Override
  public boolean isPlayingAd() {
    return !shouldMaskPosition() && playbackInfo.periodId.isAd();
  }

  @Override
  public int getCurrentAdGroupIndex() {
    return isPlayingAd() ? playbackInfo.periodId.adGroupIndex : C.INDEX_UNSET;
  }

  @Override
  public int getCurrentAdIndexInAdGroup() {
    return isPlayingAd() ? playbackInfo.periodId.adIndexInAdGroup : C.INDEX_UNSET;
  }

  @Override
  public long getContentPosition() {
    if (isPlayingAd()) {
      playbackInfo.timeline.getPeriod(playbackInfo.periodId.periodIndex, period);
      return period.getPositionInWindowMs() + C.usToMs(playbackInfo.contentPositionUs);
    } else {
      return getCurrentPosition();
    }
  }

  @Override
  public int getRendererCount() {
    return renderers.length;
  }

  @Override
  public int getRendererType(int index) {
    return renderers[index].getTrackType();
  }

  @Override
  public TrackGroupArray getCurrentTrackGroups() {
    return playbackInfo.trackGroups;
  }

  @Override
  public TrackSelectionArray getCurrentTrackSelections() {
    return playbackInfo.trackSelectorResult.selections;
  }

  @Override
  public Timeline getCurrentTimeline() {
    return playbackInfo.timeline;
  }

  @Override
  public Object getCurrentManifest() {
    return playbackInfo.manifest;
  }

  // Not private so it can be called from an inner class without going through a thunk method.
  /* package */ void handleEvent(Message msg) {
    switch (msg.what) {
      case ExoPlayerImplInternal.MSG_PLAYBACK_INFO_CHANGED:
        handlePlaybackInfo(
            (PlaybackInfo) msg.obj,
            /* operationAcks= */ msg.arg1,
            /* positionDiscontinuity= */ msg.arg2 != C.INDEX_UNSET,
            /* positionDiscontinuityReason= */ msg.arg2);
        break;
      case ExoPlayerImplInternal.MSG_PLAYBACK_PARAMETERS_CHANGED:
        PlaybackParameters playbackParameters = (PlaybackParameters) msg.obj;
        if (!this.playbackParameters.equals(playbackParameters)) {
          this.playbackParameters = playbackParameters;
          for (Player.EventListener listener : listeners) {
            listener.onPlaybackParametersChanged(playbackParameters);
          }
        }
        break;
      case ExoPlayerImplInternal.MSG_ERROR:
        ExoPlaybackException playbackError = (ExoPlaybackException) msg.obj;
        this.playbackError = playbackError;
        for (Player.EventListener listener : listeners) {
          listener.onPlayerError(playbackError);
        }
        break;
      default:
        throw new IllegalStateException();
    }
  }

  private void handlePlaybackInfo(
      PlaybackInfo playbackInfo,
      int operationAcks,
      boolean positionDiscontinuity,
      @DiscontinuityReason int positionDiscontinuityReason) {
    pendingOperationAcks -= operationAcks;
    if (pendingOperationAcks == 0) {
      if (playbackInfo.startPositionUs == C.TIME_UNSET) {
        // Replace internal unset start position with externally visible start position of zero.
        playbackInfo =
            playbackInfo.fromNewPosition(
                playbackInfo.periodId, /* startPositionUs= */ 0, playbackInfo.contentPositionUs);
      }
      if ((!this.playbackInfo.timeline.isEmpty() || hasPendingPrepare)
          && playbackInfo.timeline.isEmpty()) {
        // Update the masking variables, which are used when the timeline becomes empty.
        maskingPeriodIndex = 0;
        maskingWindowIndex = 0;
        maskingWindowPositionMs = 0;
      }
      @Player.TimelineChangeReason
      int timelineChangeReason =
          hasPendingPrepare
              ? Player.TIMELINE_CHANGE_REASON_PREPARED
              : Player.TIMELINE_CHANGE_REASON_DYNAMIC;
      boolean seekProcessed = hasPendingSeek;
      hasPendingPrepare = false;
      hasPendingSeek = false;
      updatePlaybackInfo(
          playbackInfo,
          positionDiscontinuity,
          positionDiscontinuityReason,
          timelineChangeReason,
          seekProcessed);
    }
  }

  private PlaybackInfo getResetPlaybackInfo(
      boolean resetPosition, boolean resetState, int playbackState) {
    if (resetPosition) {
      maskingWindowIndex = 0;
      maskingPeriodIndex = 0;
      maskingWindowPositionMs = 0;
    } else {
      maskingWindowIndex = getCurrentWindowIndex();
      maskingPeriodIndex = getCurrentPeriodIndex();
      maskingWindowPositionMs = getCurrentPosition();
    }
    return new PlaybackInfo(
        resetState ? Timeline.EMPTY : playbackInfo.timeline,
        resetState ? null : playbackInfo.manifest,
        playbackInfo.periodId,
        playbackInfo.startPositionUs,
        playbackInfo.contentPositionUs,
        playbackState,
        /* isLoading= */ false,
        resetState ? TrackGroupArray.EMPTY : playbackInfo.trackGroups,
        resetState ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult);
  }

  private void updatePlaybackInfo(
      PlaybackInfo newPlaybackInfo,
      boolean positionDiscontinuity,
      @Player.DiscontinuityReason int positionDiscontinuityReason,
      @Player.TimelineChangeReason int timelineChangeReason,
      boolean seekProcessed) {
    boolean timelineOrManifestChanged =
        playbackInfo.timeline != newPlaybackInfo.timeline
            || playbackInfo.manifest != newPlaybackInfo.manifest;
    boolean playbackStateChanged = playbackInfo.playbackState != newPlaybackInfo.playbackState;
    boolean isLoadingChanged = playbackInfo.isLoading != newPlaybackInfo.isLoading;
    boolean trackSelectorResultChanged =
        playbackInfo.trackSelectorResult != newPlaybackInfo.trackSelectorResult;
    playbackInfo = newPlaybackInfo;
    if (timelineOrManifestChanged || timelineChangeReason == TIMELINE_CHANGE_REASON_PREPARED) {
      for (Player.EventListener listener : listeners) {
        listener.onTimelineChanged(
            playbackInfo.timeline, playbackInfo.manifest, timelineChangeReason);
      }
    }
    if (positionDiscontinuity) {
      for (Player.EventListener listener : listeners) {
        listener.onPositionDiscontinuity(positionDiscontinuityReason);
      }
    }
    if (trackSelectorResultChanged) {
      trackSelector.onSelectionActivated(playbackInfo.trackSelectorResult.info);
      for (Player.EventListener listener : listeners) {
        listener.onTracksChanged(
            playbackInfo.trackGroups, playbackInfo.trackSelectorResult.selections);
      }
    }
    if (isLoadingChanged) {
      for (Player.EventListener listener : listeners) {
        listener.onLoadingChanged(playbackInfo.isLoading);
      }
    }
    if (playbackStateChanged) {
      for (Player.EventListener listener : listeners) {
        listener.onPlayerStateChanged(playWhenReady, playbackInfo.playbackState);
      }
    }
    if (seekProcessed) {
      for (Player.EventListener listener : listeners) {
        listener.onSeekProcessed();
      }
    }
  }

  private long playbackInfoPositionUsToWindowPositionMs(long positionUs) {
    long positionMs = C.usToMs(positionUs);
    if (!playbackInfo.periodId.isAd()) {
      playbackInfo.timeline.getPeriod(playbackInfo.periodId.periodIndex, period);
      positionMs += period.getPositionInWindowMs();
    }
    return positionMs;
  }

  private boolean shouldMaskPosition() {
    return playbackInfo.timeline.isEmpty() || pendingOperationAcks > 0;
  }
}