text:
module Graphene {
    export class Physics {
        private _lastRunTimestamp: number = 0;
        private _instance: Instance;
        private _config: Config;
        private _quadTree: QuadTree = null;
        private _control: Control;

        constructor(instance: Instance, control: Control) {
            this._instance = instance;
            this._config = instance.Config;
            this._control = control;
        }

        public update(timestamp: number): void {
            const step: number = 1000 / this._config.TPS;
            let delta: number = this._lastRunTimestamp === 0 ? step : timestamp - this._lastRunTimestamp;
            if (delta > step * 100) {
                console.log('Physics could not keep up. Skipping ' + Math.floor(delta / step) + ' Physics ticks.');
                delta = step * 100;
            }
            for (; delta >= step; delta -= step) {
                this._control.onPhysicsStart();
                this._quadTree = null;
                this.applyForce();
                this.applyAtomWallCollisions();
                this.checkAtomAtomCollisions();
                this.moveAtoms();
                this.applyLinks();
                this._control.onPhysicsStop();
            }
            this._lastRunTimestamp = timestamp - delta; // If we skip parts of a step run it next time
        }

        private applyAtomWallCollisions(): void {
            if (!this._config.WallCollisions) { return; }
            const friction: number = this._config.WallFriction;
            const width: number = this._instance.Width;
            const height: number = this._instance.Height;

            const outSideBoxX: Function = function (atom: Atom): boolean {
                return (atom.Position.X - atom.Size < 0 && atom.Vector.X < 0)
                    || (atom.Position.X + atom.Size >= width && atom.Vector.X > 0);
            };
            const outSideBoxY: Function = function (atom: Atom): boolean {
                return (atom.Position.Y - atom.Size < 0 && atom.Vector.Y < 0)
                    || (atom.Position.Y + atom.Size >= height && atom.Vector.Y > 0);
            };

            for (const atom of this._instance.Atoms) {
                if (outSideBoxX(atom)) {
                    atom.Vector = new Vector(atom.Vector.X * -1, atom.Vector.Y);
                }
                if (outSideBoxY(atom)) {
                    atom.Vector = new Vector(atom.Vector.X, atom.Vector.Y * -1);
                }
                while (outSideBoxX(atom) || outSideBoxY(atom)) {
                    const v: Vector = atom.Vector.scaleBy(this.getSpeedFactor() * 0.1);
                    atom.Position.X += v.X;
                    atom.Position.Y += v.Y;
                }
            }

        }

        private applyAtomAtomCollision(atom1: Atom, atom2: Atom): void {
            const dist: number = atom1.Size + atom2.Size;
            let cnt: number = 0;
            while (dist > atom1.distanceTo(atom2)) { // Move back to point of actual collision
                atom1.Position.X += -atom1.Vector.X * this.getSpeedFactor() * 0.1;
                atom1.Position.Y += -atom1.Vector.Y * this.getSpeedFactor() * 0.1;
                atom2.Position.X += -atom2.Vector.X * this.getSpeedFactor() * 0.1;
                atom2.Position.Y += -atom2.Vector.Y * this.getSpeedFactor() * 0.1;
                ++cnt;
            }
            const calcVsAndVe: Function = function (nd1: Atom, nd2: Atom): any { // vS in Richtung der Stoßnormalen, vE Orthogonal
                let n: Vector = Vector.fromAtoms(nd1, nd2);
                n = n.scaleTo(nd1.Size);
                const alph: number = nd1.Vector.angle(n);
                let vS: Vector = new Vector(n.X, n.Y);
                vS = vS.scaleTo(nd1.Vector.length() * Math.cos(alph));
                const x: number = nd1.Vector.X - vS.X;
                const y: number = nd1.Vector.Y - vS.X / n.X * n.Y;
                const vE: Vector = new Vector(x, y);
                return { vS: vS, vE: vE };
            };
            const obj1: any = calcVsAndVe(atom1, atom2);
            const vS1: Vector = obj1.vS; const vE1: Vector = obj1.vE;
            const obj2: any = calcVsAndVe(atom2, atom1);
            const vS2: Vector = obj2.vS; const vE2: Vector = obj2.vE;

            // Resultierender Vektor parallel zu Stoßnormalen
            const friction: number = this._config.AtomFriction;
            const calcU: Function = function (v1: Vector, v2: Vector, m1: number, m2: number): Vector {
                const X: number = (m1 * v1.X + m2 * (2 * v2.X - v1.X)) / (m1 + m2);
                const Y: number = (m1 * v1.Y + m2 * (2 * v2.Y - v1.Y)) / (m1 + m2);
                return new Vector(X, Y).scaleBy(friction);
            };
            const uS1: Vector = calcU(vS1, vS2, atom1.Mass, atom2.Mass);
            const uS2: Vector = calcU(vS2, vS1, atom2.Mass, atom1.Mass);
            atom1.Vector = uS1.add(vE1);
            atom2.Vector = uS2.add(vE2);
        }

        private applyForce(): void {
            const g: Vector = new Vector(this._instance.Config.Gravity.X, this._instance.Config.Gravity.Y);
            if (g.length() > 0) {
                for (const atom of this._instance.Atoms) {
                    atom.Vector = atom.Vector.add(g.scaleBy(this.getSpeedFactor()));
                }
            }
            const electricalForce: number = this._config.ElectricalForce;
            if (electricalForce > 0 || electricalForce < 0) {
                for (const a of this._instance.Atoms) {
                    for (let i: number = a.Id + 1; i < this._instance.Atoms.length; ++i) {
                        const a2: Atom = this._instance.Atoms[i];
                        const v: Vector = Vector.fromAtoms(a, a2).invert();
                        const d: number = v.length();
                        const f: number = electricalForce * a.Charge * a2.Charge / Math.pow(d, 2);
                        const v1: Vector = v.scaleTo(f);
                        const v2: Vector = v1.invert();
                        a.Vector = a.Vector.add(v1);
                        a2.Vector = a2.Vector.add(v2);
                    }
                }
            }
        }

        private applyLinks(): void {
            const len: number = this._instance.Atoms.length;
            const maxLinkLength: number = this._config.MaxLinkLength;
            const maxLinks: number = this._config.MaxLinksPerAtom > 0 ? this._config.MaxLinksPerAtom : Number.MAX_VALUE;
            if (this._instance.Links.length !== len) {
                this._instance.Links.length = len;
            }
            this._instance.Atoms.forEach((atom: Atom) => atom.Links = 0);
            for (const a1 of this._instance.Atoms) {
                for (let i: number = a1.Id + 1; i < len; ++i) {
                    const a2: Atom = this._instance.Atoms[i];
                    if (this._instance.Links[a1.Id] == null || this._instance.Links[a1.Id].length !== len) {
                        this._instance.Links[a1.Id] = new Array<boolean>(len);
                    }
                    if (a1.distanceTo(a2) <= maxLinkLength && a1.Links < maxLinks && a2.Links < maxLinks) {
                        a1.Links++; a2.Links++;
                        this._instance.Links[a1.Id][a2.Id] = true;
                    } else {
                        this._instance.Links[a1.Id][a2.Id] = false;
                    }
                }
            }
        }

        private checkAtomAtomCollisions(): void {
            if (!this._config.AtomCollisions) { return; }
            const q: QuadTree = this.QuadTree;
            for (const nd of this._instance.Atoms) {
                const collisionNds: Atom[] = q.getItems(nd.Position.X, nd.Position.Y);
                for (const colNd of collisionNds) {
                    if (colNd.Id > nd.Id && nd.collidesWith(colNd)) {
                        this.applyAtomAtomCollision(nd, colNd);
                    }
                }
            }
        }

        private getSpeedFactor(): number {
            return 1 / this._config.TPS;
        }

        private moveAtoms(): void {
            const sf: number = this.getSpeedFactor();
            for (const atom of this._instance.Atoms) {
                if (!atom.PhysicsLocked) {
                    atom.Position.X += atom.Vector.X * sf;
                    atom.Position.Y += atom.Vector.Y * sf;
                }
            }
        }

        public get QuadTree(): QuadTree {
            if (this._quadTree == null) {
                this._quadTree = new QuadTree(0, new Rectangle(0, 0, this._instance.Width, this._instance.Height));
                this._quadTree.addItems(this._instance.Atoms);
            }
            return this._quadTree;
        }
    }
}


text:
#if DEBUG

/**
 * Wrapper for XInput
 * Provided by http://www.pluralsight.com/blogs/dbox/archive/2005/12/10/17384.aspx
 * Modified by Jean-Philippe Steinmetz <caskater47@gmail.com>
 **/

namespace Microsoft.DirectX.XInput
{
    using System;
    using System.Runtime.InteropServices;
    using System.ComponentModel;

    public enum XInputDeviceType : byte
    {
        GamePad = 1
    }
    public enum XInputDeviceSubtype : byte
    {
        GamePad = 1
    }
    [Flags]
    public enum XInputCapabilityFlags : ushort
    {
        VoiceSupported = 4
    }

    [Flags]
    public enum XInputButtons : ushort
    {
        DPadUp = 0x1,
        DPadDown = 0x2,
        DPadLeft = 0x4,
        DPadRight = 0x8,
        Start = 0x10,
        Back = 0x20,
        LeftThumb = 0x40,
        RightThumb = 0x80,
        LeftShoulder = 0x100,
        RightShoulder = 0x200,
        A = 0x1000,
        B = 0x2000,
        X = 0x4000,
        Y = 0x8000
    }

    [Serializable]
    public struct XInputCapabilities
    {
        public XInputDeviceType Type;
        public XInputDeviceSubtype SubType;
        public XInputCapabilityFlags Flags;
        public XInputGamepad Gamepad;
        public XInputVibration Vibration;

        public override string ToString()
        {
            return string.Format("({0} {1} {2} {3} {4})", Type, SubType, Flags, Gamepad, Vibration);
        }
    }

    [Serializable]
    public struct XInputGamepad
    {
        public XInputButtons Buttons;
        public byte LeftTrigger;
        public byte RightTrigger;
        public short LeftThumbX;
        public short LeftThumbY;
        public short RightThumbX;
        public short RightThumbY;

        public bool IsAButtonDown
        {
            get { return (Buttons & XInputButtons.A) != 0; }
        }
        public bool IsBButtonDown
        {
            get { return (Buttons & XInputButtons.B) != 0; }
        }
        public bool IsXButtonDown
        {
            get { return (Buttons & XInputButtons.X) != 0; }
        }
        public bool IsYButtonDown
        {
            get { return (Buttons & XInputButtons.Y) != 0; }
        }
        public bool IsStartButtonDown
        {
            get { return (Buttons & XInputButtons.Start) != 0; }
        }
        public bool IsBackButtonDown
        {
            get { return (Buttons & XInputButtons.Back) != 0; }
        }
        public bool IsDPadLeftButtonDown
        {
            get { return (Buttons & XInputButtons.DPadLeft) != 0; }
        }
        public bool IsDPadRightButtonDown
        {
            get { return (Buttons & XInputButtons.DPadRight) != 0; }
        }
        public bool IsDPadUpButtonDown
        {
            get { return (Buttons & XInputButtons.DPadUp) != 0; }
        }
        public bool IsDPadDownButtonDown
        {
            get { return (Buttons & XInputButtons.DPadDown) != 0; }
        }
        public bool IsLeftThumbButtonDown
        {
            get { return (Buttons & XInputButtons.LeftThumb) != 0; }
        }
        public bool IsRightThumbButtonDown
        {
            get { return (Buttons & XInputButtons.RightThumb) != 0; }
        }
        public bool IsLeftShoulderButtonDown
        {
            get { return (Buttons & XInputButtons.LeftShoulder) != 0; }
        }
        public bool IsRightShoulderButtonDown
        {
            get { return (Buttons & XInputButtons.RightShoulder) != 0; }
        }

        public override bool Equals(object obj)
        {
            if (obj is XInputGamepad)
                return Equals((XInputGamepad)obj);
            return false;
        }

        public override int GetHashCode()
        {
            return (int)Buttons + LeftTrigger + RightTrigger;
        }

        public bool Equals(XInputGamepad rhs)
        {
            return
                Buttons == rhs.Buttons
                && LeftTrigger == rhs.LeftTrigger
                && RightTrigger == rhs.RightTrigger
                && LeftThumbX == rhs.LeftThumbX
                && LeftThumbY == rhs.LeftThumbY
                && RightThumbX == rhs.RightThumbX
                && RightThumbY == rhs.RightThumbY;
        }

        public override string ToString()
        {
            return string.Format("({0} {1} {2} {3} {4} {5} {6})", Buttons, LeftTrigger, RightTrigger, LeftThumbX, LeftThumbY, RightThumbX, RightThumbY);
        }
    }

    [Serializable]
    public struct XInputState
    {
        public uint PacketNumber;
        public XInputGamepad Gamepad;

        public bool Equals(XInputState rhs)
        {
            return PacketNumber == rhs.PacketNumber
                    && Gamepad.Equals(rhs.Gamepad);
        }

        public override bool Equals(object obj)
        {
            if (obj is XInputState)
                return Equals((XInputState)obj);
            return false;
        }

        public override int GetHashCode()
        {
            return (int)PacketNumber;
        }

        public override string ToString()
        {
            return string.Format("({0} {1})", PacketNumber, Gamepad);
        }
    }

    [Serializable]
    public struct XInputVibration
    {
        public ushort LeftMotorSpeed;
        public ushort RightMotorSpeed;

        public XInputVibration(ushort left, ushort right)
        {
            LeftMotorSpeed = left;
            RightMotorSpeed = right;
        }
    }

    public static class XInputMethods
    {
        // Get the capabilities of controller 0, 1, 2, or 3
        public static void GetCapabilities(int controllerNumber, out XInputCapabilities caps)
        {
            ProcessResult(
                XInputGetCapabilities(controllerNumber, 0, out caps)
                );
        }

        // Poll the state of the controller's buttons, thumbsticks, and triggers
        public static void GetState(int controllerNumber, out XInputState state)
        {
            ProcessResult(
                XInputGetState(controllerNumber, out state)
                );
        }

        // Set the vibration speed of a controller
        public static void SetVibration(int controllerNumber, ushort leftSpeed, ushort rightSpeed)
        {
            XInputVibration vibe = new XInputVibration(leftSpeed, rightSpeed);
            ProcessResult(
                XInputSetState(controllerNumber, ref vibe)
                );
        }

        // Get the DirectSound guids for sending/receiving audio to the controller's headset
        public static void GetAudioGuids(int controllerNumber, out Guid renderGuid, out Guid captureGuid)
        {
            ProcessResult(XInputGetDSoundAudioDeviceGuids(controllerNumber, out renderGuid, out captureGuid));
        }

        static void ProcessResult(uint err)
        {
            if (err != 0)
                throw new Win32Exception((int)err);
        }

        const string DllName = "XInput9_1_0.dll";

        [DllImport(DllName)]
        extern static uint XInputGetState(
            int index,  // [in] Index of the gamer associated with the device
            out XInputState state // [out] Receives the current state
        );

        [DllImport(DllName)]
        extern static uint XInputSetState(
            int index,  // [in] Index of the gamer associated with the device
            ref XInputVibration vibration// [in, out] The vibration information to send to the controller
        );

        [DllImport(DllName)]
        extern static uint XInputGetCapabilities(
            int dwUserIndex,   // [in] Index of the gamer associated with the device
            uint dwFlags,       // [in] Input flags that identify the device type
            out XInputCapabilities capabilities  // [out] Receives the capabilities
        );

        [DllImport(DllName)]
        extern static uint XInputGetDSoundAudioDeviceGuids(
            int dwUserIndex,          // [in] Index of the gamer associated with the device
            out Guid soundRenderGuid,    // [out] DSound device ID for render
            out Guid SoundCaptureGuid    // [out] DSound device ID for capture
        );
    }
}

#endif

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include <exception>

namespace trikKernel {

/// Base class for all exceptions in TRIKRuntime.
class TrikRuntimeException : public std::exception
{
public:
	virtual ~TrikRuntimeException() {}
};

}


text:
using System;
using System.Diagnostics;
using System.Globalization;

namespace Octokit
{
    /// <summary>
    /// Used to create a new release.
    /// </summary>
    /// <remarks>
    /// API: https://developer.github.com/v3/repos/releases/#create-a-release
    /// </remarks>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class NewRelease
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NewRelease"/> class.
        /// </summary>
        /// <param name="tagName">Name of the tag to create in the repository for this release.</param>
        public NewRelease(string tagName)
        {
            Ensure.ArgumentNotNullOrEmptyString(tagName, "tagName");
            TagName = tagName;
        }

        /// <summary>
        /// Gets the name of the tag.
        /// </summary>
        /// <value>
        /// The name of the tag.
        /// </value>
        public string TagName { get; private set; }

        /// <summary>
        /// Specifies the commitish value that determines where the Git tag is created from. Can be any branch or
        /// commit SHA. Unused if the Git tag already exists. Default: the repository's default branch
        /// (usually master).
        /// </summary>
        /// <value>
        /// The target commitish.
        /// </value>
        public string TargetCommitish { get; set; }

        /// <summary>
        /// Gets or sets the name of the release.
        /// </summary>
        /// <value>
        /// The name.
        /// </value>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the text describing the contents of the tag.
        /// </summary>
        /// <value>
        /// The body.
        /// </value>
        public string Body { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="NewRelease"/> is a draft (unpublished).
        /// Default: false
        /// </summary>
        /// <value>
        ///   <c>true</c> if draft; otherwise, <c>false</c>.
        /// </value>
        public bool Draft { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="NewRelease"/> is prerelease.
        /// </summary>
        /// <value>
        ///   <c>true</c> if prerelease; otherwise, <c>false</c>.
        /// </value>
        public bool Prerelease { get; set; }

        internal string DebuggerDisplay
        {
            get
            {
                return String.Format(CultureInfo.InvariantCulture, "Name: {0} TagName: {1}", Name, TagName);
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Callopisma hegetschweileri Müll. Arg.

### Remarks
null


text:
<!doctype html>

  <meta charset='utf-8'>
  <title>go web server example</title>

go web server example

 Help (this page)

 File Server (dir value from config file)

 Redirect (to example.com)

 NotFound Handler (should get a 404 error)

 Debug Info (POST form)

 Debug Info (GET request)

 Ajax Callback

 Function Adapter


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import functools
import getpass
import hashlib
import os
import pkgutil
import shutil
import sys
from collections import OrderedDict, defaultdict

from twitter.common.collections import OrderedSet
from twitter.common.config import Properties

from pants.backend.core.tasks.scm_publish import Namedver, ScmPublishMixin, Semver
from pants.backend.jvm.ivy_utils import IvyUtils
from pants.backend.jvm.ossrh_publication_metadata import OSSRHPublicationMetadata
from pants.backend.jvm.targets.jarable import Jarable
from pants.backend.jvm.targets.scala_library import ScalaLibrary
from pants.backend.jvm.tasks.jar_task import JarTask
from pants.base.address import Address
from pants.base.address_lookup_error import AddressLookupError
from pants.base.build_environment import get_buildroot, get_scm
from pants.base.build_file import BuildFile
from pants.base.build_file_parser import BuildFileParser
from pants.base.build_graph import sort_targets
from pants.base.exceptions import TaskError
from pants.base.generator import Generator, TemplateData
from pants.base.target import Target
from pants.ivy.bootstrapper import Bootstrapper
from pants.ivy.ivy import Ivy
from pants.option.options import Options
from pants.util.dirutil import safe_mkdir, safe_open, safe_rmtree
from pants.util.strutil import ensure_text

class PushDb(object):

  @staticmethod
  def load(path):
    """Loads a pushdb maintained in a properties file at the given path."""
    with open(path, 'r') as props:
      properties = Properties.load(props)
      return PushDb(properties)

  class Entry(object):

    def __init__(self, sem_ver, named_ver, named_is_latest, sha, fingerprint):
      """Records the most recent push/release of an artifact.

      :param Semver sem_ver: The last semantically versioned release (or Semver(0.0.0))
      :param Namedver named_ver: The last named release of this entry (or None)
      :param boolean named_is_latest: True if named_ver is the latest, false if sem_ver is
      :param string sha: The last Git SHA (or None)
      :param string fingerprint: A unique hash for the most recent version of the target.
      """
      self.sem_ver = sem_ver
      self.named_ver = named_ver
      self.named_is_latest = named_is_latest
      self.sha = sha
      self.fingerprint = fingerprint

    def version(self):
      if self.named_is_latest:
        return self.named_ver
      else:
        return self.sem_ver

    def with_sem_ver(self, sem_ver):
      """Returns a clone of this entry with the given sem_ver marked as the latest."""
      return PushDb.Entry(sem_ver, self.named_ver, False, self.sha, self.fingerprint)

    def with_named_ver(self, named_ver):
      """Returns a clone of this entry with the given name_ver marked as the latest."""
      return PushDb.Entry(self.sem_ver, named_ver, True, self.sha, self.fingerprint)

    def with_sha_and_fingerprint(self, sha, fingerprint):
      """Returns a clone of this entry with the given sha and fingerprint."""
      return PushDb.Entry(self.sem_ver, self.named_ver, self.named_is_latest, sha, fingerprint)

    def __repr__(self):
      return '<{}, {}, {}, {}, {}, {}>'.format(
        self.__class__.__name__, self.sem_ver, self.named_ver, self.named_is_latest,
        self.sha, self.fingerprint)

  def __init__(self, props=None):
    self._props = props or OrderedDict()

  def get_entry(self, target):
    """Given an internal target, return a PushDb.Entry, which might contain defaults."""
    db_get, _ = self._accessors_for_target(target)

    major = int(db_get('revision.major', '0'))
    minor = int(db_get('revision.minor', '0'))
    patch = int(db_get('revision.patch', '0'))
    snapshot = str(db_get('revision.snapshot', 'false')).lower() == 'true'
    named_version = db_get('revision.named_version', None)
    named_is_latest = str(db_get('revision.named_is_latest', 'false')).lower() == 'true'
    sha = db_get('revision.sha', None)
    fingerprint = db_get('revision.fingerprint', None)
    sem_ver = Semver(major, minor, patch, snapshot=snapshot)
    named_ver = Namedver(named_version) if named_version else None
    return self.Entry(sem_ver, named_ver, named_is_latest, sha, fingerprint)

  def set_entry(self, target, pushdb_entry):
    pe = pushdb_entry
    _, db_set = self._accessors_for_target(target)
    db_set('revision.major', pe.sem_ver.major)
    db_set('revision.minor', pe.sem_ver.minor)
    db_set('revision.patch', pe.sem_ver.patch)
    db_set('revision.snapshot', str(pe.sem_ver.snapshot).lower())
    if pe.named_ver:
      db_set('revision.named_version', pe.named_ver.version())
    db_set('revision.named_is_latest', str(pe.named_is_latest).lower())
    db_set('revision.sha', pe.sha)
    db_set('revision.fingerprint', pe.fingerprint)

  def _accessors_for_target(self, target):
    jar_dep, _, exported = target.get_artifact_info()
    if not exported:
      raise ValueError

    def key(prefix):
      return '{}.{}%{}'.format(prefix, jar_dep.org, jar_dep.name)

    def getter(prefix, default=None):
      return self._props.get(key(prefix), default)

    def setter(prefix, value):
      self._props[key(prefix)] = value

    return getter, setter

  def dump(self, path):
    """Saves the pushdb as a properties file to the given path."""
    with open(path, 'w') as props:
      Properties.dump(self._props, props)

class DependencyWriter(object):
  """
    Builds up a template data representing a target and applies this to a template to produce a
    dependency descriptor.
  """

  @staticmethod
  def create_exclude(exclude):
    return TemplateData(org=exclude.org, name=exclude.name)

  def __init__(self, get_db, template_relpath, template_package_name=None):
    self.get_db = get_db
    self.template_package_name = template_package_name or __name__
    self.template_relpath = template_relpath

  def write(self, target, path, confs=None, extra_confs=None, classifier=None):
    # TODO(John Sirois): a dict is used here to de-dup codegen targets which have both the original
    # codegen target - say java_thrift_library - and the synthetic generated target (java_library)
    # Consider reworking codegen tasks to add removal of the original codegen targets when rewriting
    # the graph
    dependencies = OrderedDict()
    internal_codegen = {}
    configurations = set(confs or [])
    for internal_dep in target_internal_dependencies(target):
      jar = self._as_versioned_jar(internal_dep)
      dependencies[(jar.org, jar.name)] = self.internaldep(jar, internal_dep, classifier=classifier)
      if internal_dep.is_codegen:
        internal_codegen[jar.name] = jar.name
    for jar in target.jar_dependencies:
      if jar.rev:
        dependencies[(jar.org, jar.name, classifier)] = self.jardep(jar, classifier=classifier)
        configurations |= set(jar._configurations)

    target_jar = self.internaldep(self._as_versioned_jar(target),
                                  target,
                                  classifier=classifier,
                                  configurations=list(configurations))
    target_jar = target_jar.extend(dependencies=dependencies.values())

    template_kwargs = self.templateargs(target_jar, confs, extra_confs, classifier)
    with safe_open(path, 'w') as output:
      template = pkgutil.get_data(self.template_package_name, self.template_relpath)
      Generator(template, **template_kwargs).write(output)

  def templateargs(self, target_jar, confs=None, extra_confs=None, classifier=None):
    """
      Subclasses must return a dict for use by their template given the target jar template data
      and optional specific ivy configurations.
    """
    raise NotImplementedError()

  def internaldep(self, jar_dependency, target, configurations=None, classifier=None):
    """
      Subclasses must return a template data for the given internal target (provided in jar
      dependency form).
    """
    raise NotImplementedError()

  def _as_versioned_jar(self, internal_target):
    """Fetches the jar representation of the given target, and applies the latest pushdb version."""
    jar, _, _ = internal_target.get_artifact_info()
    pushdb_entry = self.get_db(internal_target).get_entry(internal_target)
    jar.rev = pushdb_entry.version().version()
    return jar

  def jardep(self, jar_dependency, classifier=None):
    """Subclasses must return a template data for the given external jar dependency."""
    raise NotImplementedError()

class PomWriter(DependencyWriter):

  def __init__(self, get_db, tag):
    super(PomWriter, self).__init__(
        get_db,
        os.path.join('templates', 'jar_publish', 'pom.mustache'))
    self._tag = tag

  def templateargs(self, target_jar, confs=None, extra_confs=None, classifier=None):
    return dict(project=target_jar)

  def jardep(self, jar, classifier=None):
    return TemplateData(
      classifiers=self.classifiers(classifier, jar.artifacts),
      artifact_id=jar.name,
      group_id=jar.org,
      version=jar.rev,
      scope='compile',
      excludes=[self.create_exclude(exclude) for exclude in jar.excludes if exclude.name])

  @staticmethod
  def classifiers(classifier, artifacts):
    """Find a list of plausible classifiers.

    :param classifier: the starting classifier
    :param artifacts: a sequence of IvyArtifact's
    :return: list like [TemplateData(classifier='sources'), TemplateData(classifier='javadoc')]
    """
    s = set()
    if classifier:
      s.add(classifier)
    s.update([i.classifier for i in artifacts if i.classifier])

    # We sort this for testing: having a test fail because the order changed isn't helpful.

    return map(lambda x: TemplateData(classifier=x), sorted(s))

  def internaldep(self, jar_dependency, target, configurations=None, classifier=None):
    template_data = self.jardep(jar_dependency, classifier=classifier)
    if isinstance(target.provides.publication_metadata, OSSRHPublicationMetadata):
      pom = target.provides.publication_metadata

      # Forming the project name from the coordinates like this is acceptable as a fallback when
      # the user supplies no project name.
      # See: http://central.sonatype.org/pages/requirements.html#project-name-description-and-url
      name = pom.name or '{}:{}'.format(jar_dependency.org, jar_dependency.name)

      template_data = template_data.extend(name=name,
                                           description=pom.description,
                                           url=pom.url,
                                           licenses=pom.licenses,
                                           scm=pom.scm.tagged(self._tag),
                                           developers=pom.developers)
    return template_data

class IvyWriter(DependencyWriter):
  JAVADOC_CONFIG = 'javadoc'
  SOURCES_CONFIG = 'sources'
  DEFAULT_CONFIG = 'default'

  def __init__(self, get_db):
    super(IvyWriter, self).__init__(
        get_db,
        IvyUtils.IVY_TEMPLATE_PATH,
        template_package_name=IvyUtils.IVY_TEMPLATE_PACKAGE_NAME)

  def templateargs(self, target_jar, confs=None, extra_confs=None, classifier=None):
    return dict(lib=target_jar.extend(
        publications=set(confs or []),
        extra_publications=extra_confs if extra_confs else {},
        overrides=None))

  def _jardep(self, jar, transitive=True, configurations='default', classifier=None):
    return TemplateData(
        org=jar.org,
        module=jar.name,
        version=jar.rev,
        mutable=False,
        force=jar.force,
        excludes=[self.create_exclude(exclude) for exclude in jar.excludes],
        transitive=transitive,
        artifacts=jar.artifacts,
        classifier=classifier,
        configurations=configurations)

  def jardep(self, jar, classifier=None):
    return self._jardep(jar,
                        transitive=jar.transitive,
                        configurations=jar._configurations,
                        classifier=classifier)

  def internaldep(self, jar_dependency, target, configurations=None, classifier=None):
    return self._jardep(jar_dependency, configurations=configurations, classifier=classifier)

def coordinate(org, name, rev=None):
  return '{}#{};{}'.format(org, name, rev) if rev else '{}#{}'.format(org, name)

def jar_coordinate(jar, rev=None):
  return coordinate(jar.org, jar.name, rev or jar.rev)

def pushdb_coordinate(jar, entry):
  return jar_coordinate(jar, rev=entry.version().version())

def target_internal_dependencies(target):
  """Returns internal Jarable dependencies that were "directly" declared.

  Directly declared deps are those that are explicitly listed in the definition of a
  target, rather than being depended on transitively. But in order to walk through
  aggregator targets such as `target`, `dependencies`, or `jar_library`, this recursively
  descends the dep graph and stops at Jarable instances."""
  for dep in target.dependencies:
    if isinstance(dep, Jarable):
      yield dep
    else:
      for childdep in target_internal_dependencies(dep):
        yield childdep

class JarPublish(ScmPublishMixin, JarTask):
  """Publish jars to a maven repository.

  At a high-level, pants uses `Apache Ivy <http://ant.apache.org/ivy/>`_ to
  publish artifacts to Maven-style repositories. Pants performs prerequisite
  tasks like compiling, creating jars, and generating ``pom.xml`` files then
  invokes Ivy to actually publish the artifacts, so publishing is largely
  configured in ``ivysettings.xml``. ``BUILD`` and ``pants.ini`` files
  primarily provide linkage between publishable targets and the
  Ivy ``resolvers`` used to publish them.

  The following target types are publishable:
  `java_library <build_dictionary.html#java_library>`_,
  `scala_library <build_dictionary.html#scala_library>`_,
  `java_thrift_library <build_dictionary.html#java_thrift_library>`_,
  `annotation_processor <build_dictionary.html#annotation_processor>`_.
  Targets to publish and their dependencies must be publishable target
  types and specify the ``provides`` argument. One exception is
  `jar <build_dictionary.html#jar>`_\s - pants will generate a pom file that
  depends on the already-published jar.

  Example usage: ::

     # By default pants will perform a dry-run.
     ./pants clean-all publish src/java/com/twitter/mybird

     # Actually publish.
     ./pants clean-all publish src/java/com/twitter/mybird --no-publish-dryrun

  Please see ``./pants publish -h`` for a detailed description of all
  publishing options.

  Publishing can be configured with the following options:

  * ``--repos`` - Required dictionary of settings for repos that may be pushed to.
  * ``--jvm-options`` - Optional list of JVM command-line args when invoking Ivy.
  * ``--restrict-push-branches`` - Optional list of branches to restrict publishing to.

  Example repos dictionary: ::

     repos = {
       # repository target name is paired with this key
       'myrepo': {
         # ivysettings.xml resolver to use for publishing
         'resolver': 'maven.example.com',
         # ivy configurations to publish
         'confs': ['default', 'sources', 'javadoc'],
         # address of a Credentials target to use when publishing
         'auth': 'address/of/credentials:target',
         # help message if unable to initialize the Credentials target.
         'help': 'Please check your credentials and try again.',
       },
     }
  """

  @classmethod
  def register_options(cls, register):
    super(JarPublish, cls).register_options(register)

    # TODO(John Sirois): Support a preview mode that outputs a file with entries like:
    # artifact id:
    # revision:
    # publish: (true|false)
    # changelog:
    #
    # Allow re-running this goal with the file as input to support forcing an arbitrary set of
    # revisions and supply of hand edited changelogs.

    register('--dryrun', default=True, action='store_true',
             help='Run through a push without actually pushing artifacts, editing publish dbs or '
                  'otherwise writing data')
    register('--commit', default=True, action='store_true',
             help='Commit the push db. Turn off for local testing.')
    register('--local', metavar='<PATH>',
             help='Publish jars to a maven repository on the local filesystem at this path.')
    register('--local-snapshot', default=True, action='store_true',
             help='If --local is specified, publishes jars with -SNAPSHOT revision suffixes.')
    register('--named-snapshot', default=None,
             help='Publish all artifacts with the given snapshot name, replacing their version. '
                  'This is not Semantic Versioning compatible, but is easier to consume in cases '
                  'where many artifacts must align.')
    register('--transitive', default=True, action='store_true',
             help='Publish the specified targets and all their internal dependencies transitively.')
    register('--force', default=False, action='store_true',
             help='Force pushing jars even if there have been no changes since the last push.')
    register('--override', action='append',
             help='Specifies a published jar revision override in the form: '
                  '([org]#[name]|[target spec])=[new revision] '
                  'For example, to specify 2 overrides: '
                  '--override=com.foo.bar#baz=0.1.2  --override=src/java/com/foo/bar/qux=1.0.0')
    register('--restart-at',
             help='Restart a fail push at the given jar.  Jars can be identified by '
                  'maven coordinate [org]#[name] or target. '
                  'For example: --restart-at=com.twitter.common#quantity '
                  'Or: --restart-at=src/java/com/twitter/common/base')
    register('--ivy_settings', advanced=True, default=None,
             help='Specify a custom ivysettings.xml file to be used when publishing.')
    register('--jvm-options', advanced=True, type=Options.list,
             help='Use these jvm options when running Ivy.')
    register('--repos', advanced=True, type=Options.dict,
             help='Settings for repositories that can be pushed to. See '
                  'https://pantsbuild.github.io/publish.html for details.')
    register('--publish-extras', advanced=True, type=Options.dict,
             help='Extra products to publish. See '
                  'https://pantsbuild.github.io/dev_tasks_publish_extras.html for details.')
    register('--individual-plugins', advanced=True, default=False, type=bool,
             help='Extra products to publish as a individual artifact.')
    register('--push-postscript', advanced=True, default=None,
             help='A post-script to add to pushdb commit messages and push tag commit messages.')
    register('--changelog', default=True, action='store_true',
             help='A changelog.txt file will be created and printed to the console for each artifact '
                  'published')

  @classmethod
  def prepare(cls, options, round_manager):
    super(JarPublish, cls).prepare(options, round_manager)
    round_manager.require('jars')
    round_manager.require('javadoc')
    round_manager.require('scaladoc')

  def __init__(self, *args, **kwargs):
    super(JarPublish, self).__init__(*args, **kwargs)
    self.cachedir = os.path.join(self.workdir, 'cache')

    self._jvm_options = self.get_options().jvm_options

    self.scm = get_scm()
    self.log = self.context.log

    if self.get_options().local:
      local_repo = dict(
        resolver='publish_local',
        path=os.path.abspath(os.path.expanduser(self.get_options().local)),
        confs=['default'],
        auth=None
      )
      self.repos = defaultdict(lambda: local_repo)
      self.commit = False
      self.local_snapshot = self.get_options().local_snapshot
    else:
      self.repos = self.get_options().repos
      if not self.repos:
        raise TaskError("This repo is not configured to publish externally! Please configure per\n"
                        "http://pantsbuild.github.io/publish.html#authenticating-to-the-artifact-repository,\n"
                        "or re-run with the '--publish-local' flag.")
      for repo, data in self.repos.items():
        auth = data.get('auth')
        if auth:
          credentials = next(iter(self.context.resolve(auth)))
          user = credentials.username(data['resolver'])
          password = credentials.password(data['resolver'])
          self.context.log.debug('Found auth for repo={} user={}'.format(repo, user))
          self.repos[repo]['username'] = user
          self.repos[repo]['password'] = password
      self.commit = self.get_options().commit
      self.push_postscript = self.get_options().push_postscript or ''
      self.local_snapshot = False

    self.named_snapshot = self.get_options().named_snapshot
    if self.named_snapshot:
      self.named_snapshot = Namedver.parse(self.named_snapshot)

    self.dryrun = self.get_options().dryrun
    self.transitive = self.get_options().transitive
    self.force = self.get_options().force
    self.publish_changelog = self.get_options().changelog

    def parse_jarcoordinate(coordinate):
      components = coordinate.split('#', 1)
      if len(components) == 2:
        org, name = components
        return org, name
      else:
        try:
          # TODO(Eric Ayers) This code is suspect.  Target.get() is a very old method and almost certainly broken.
          # Refactor to use methods from BuildGraph or BuildFileAddressMapper
          address = Address.parse(get_buildroot(), coordinate)
          target = Target.get(address)
          if not target:
            siblings = Target.get_all_addresses(address.build_file)
            prompt = 'did you mean' if len(siblings) == 1 else 'maybe you meant one of these'
            raise TaskError('{} => {}?:\n    {}'.format(address, prompt,
                                                        '\n    '.join(str(a) for a in siblings)))
          if not target.is_exported:
            raise TaskError('{} is not an exported target'.format(coordinate))
          return target.provides.org, target.provides.name
        except (BuildFile.BuildFileError, BuildFileParser.BuildFileParserError, AddressLookupError) as e:
          raise TaskError('{message}\n  Problem with BUILD file  at {coordinate}'
          .format(message=e, coordinate=coordinate))

    self.overrides = {}
    if self.get_options().override:
      if self.named_snapshot:
        raise TaskError('Options --named-snapshot and --override are mutually exclusive!')

      def parse_override(override):
        try:
          coordinate, rev = override.split('=', 1)
          try:
            # overrides imply semantic versioning
            rev = Semver.parse(rev)
          except ValueError as e:
            raise TaskError('Invalid version {}: {}'.format(rev, e))
          return parse_jarcoordinate(coordinate), rev
        except ValueError:
          raise TaskError('Invalid override: {}'.format(override))

      self.overrides.update(parse_override(o) for o in self.get_options().override)

    self.restart_at = None
    if self.get_options().restart_at:
      self.restart_at = parse_jarcoordinate(self.get_options().restart_at)

  def confirm_push(self, coord, version):
    """Ask the user if a push should be done for a particular version of a
       particular coordinate.   Return True if the push should be done"""
    try:
      isatty = os.isatty(sys.stdin.fileno())
    except ValueError:
      # In tests, sys.stdin might not have a fileno
      isatty = False
    if not isatty:
      return True
    push = raw_input('\nPublish {} with revision {} ? [y|N] '.format(
      coord, version
    ))
    print('\n')
    return push.strip().lower() == 'y'

  def _copy_artifact(self, tgt, jar, version, typename, suffix='', extension='jar',
                     artifact_ext='', override_name=None):
    """Copy the products for a target into the artifact path for the jar/version"""
    genmap = self.context.products.get(typename)
    product_mapping = genmap.get(tgt)
    if product_mapping is None:
      if self.get_options().individual_plugins:
        return
      raise ValueError("No product mapping in {} for {}. "
                       "You may need to run some other task first".format(typename, tgt))
    for basedir, jars in product_mapping.items():
      for artifact in jars:
        path = self.artifact_path(jar, version, name=override_name, suffix=suffix,
                                  extension=extension, artifact_ext=artifact_ext)
        safe_mkdir(os.path.dirname(path))
        shutil.copy(os.path.join(basedir, artifact), path)

  def _ivy_jvm_options(self, repo):
    """Get the JVM options for ivy authentication, if needed."""
    # Get authentication for the publish repo if needed.
    if not repo.get('auth'):
      return self._jvm_options

    jvm_options = self._jvm_options
    user = repo.get('username')
    password = repo.get('password')
    if user and password:
      jvm_options.append('-Dlogin={}'.format(user))
      jvm_options.append('-Dpassword={}'.format(password))
    else:
      raise TaskError('Unable to publish to {}. {}'
                      .format(repo.get('resolver'), repo.get('help', '')))
    return jvm_options

  def publish(self, ivyxml_path, jar, entry, repo, published):
    """Run ivy to publish a jar.  ivyxml_path is the path to the ivy file; published
    is a list of jars published so far (including this one). entry is a pushdb entry."""
    jvm_options = self._ivy_jvm_options(repo)
    resolver = repo['resolver']
    path = repo.get('path')

    try:
      ivy = Bootstrapper.default_ivy()
    except Bootstrapper.Error as e:
      raise TaskError('Failed to push {0}! {1}'.format(pushdb_coordinate(jar, entry), e))

    ivysettings = self.generate_ivysettings(ivy, published, publish_local=path)
    args = [
      '-settings', ivysettings,
      '-ivy', ivyxml_path,
      '-deliverto', '{}/[organisation]/[module]/ivy-[revision].xml'.format(self.workdir),
      '-publish', resolver,
      '-publishpattern', '{}/[organisation]/[module]/'
                         '[artifact]-[revision](-[classifier]).[ext]'.format(self.workdir),
      '-revision', entry.version().version(),
      '-m2compatible',
    ]

    # TODO(John Sirois): global logging options should be hidden behind some sort of log manager
    # that we can:
    # a.) obtain a handle to (dependency injection or manual plumbing)
    # b.) query for log detail, ie: `if log_manager.is_verbose:`
    if self.get_options().level == 'debug':
      args.append('-verbose')

    if self.local_snapshot:
      args.append('-overwrite')

    try:
      ivy.execute(jvm_options=jvm_options, args=args,
                  workunit_factory=self.context.new_workunit, workunit_name='ivy-publish')
    except Ivy.Error as e:
      raise TaskError('Failed to push {0}! {1}'.format(pushdb_coordinate(jar, entry), e))

  def execute(self):
    self.check_clean_master(commit=(not self.dryrun and self.commit))

    exported_targets = self.exported_targets()
    self.check_targets(exported_targets)

    pushdbs = {}

    def get_db(tgt):
      # TODO(tdesai) Handle resource type in get_db.
      if tgt.provides is None:
        raise TaskError('trying to publish target {!r} which does not provide an artifact'.format(tgt))
      dbfile = tgt.provides.repo.push_db(tgt)
      result = pushdbs.get(dbfile)
      if not result:
        # Create an empty pushdb if no dbfile exists.
        if (os.path.exists(dbfile)):
          db = PushDb.load(dbfile)
        else:
          safe_mkdir(os.path.dirname(dbfile))
          db = PushDb()
        try:
          repo = self.repos[tgt.provides.repo.name]
        except KeyError:
          raise TaskError('Repository {0} has no entry in the --repos option.'.format(
            tgt.provides.repo.name))
        result = (db, dbfile, repo)
        pushdbs[dbfile] = result
      return result

    def get_pushdb(tgt):
      return get_db(tgt)[0]

    def fingerprint_internal(tgt):
      pushdb = get_pushdb(tgt)
      entry = pushdb.get_entry(tgt)
      return entry.fingerprint or '0.0.0'

    def stage_artifact(tgt, jar, version, tag, changelog, confs=None, artifact_ext='',
                       extra_confs=None, classifier=''):
      def path(name=None, suffix='', extension='jar'):
        return self.artifact_path(jar, version, name=name, suffix=suffix, extension=extension,
                                  artifact_ext=artifact_ext)

      if self.publish_changelog:
        with safe_open(path(suffix='-CHANGELOG', extension='txt'), 'wb') as changelog_file:
          changelog_file.write(changelog.encode('utf-8'))
      ivyxml = path(name='ivy', extension='xml')

      IvyWriter(get_pushdb).write(tgt, ivyxml, confs=confs, extra_confs=extra_confs,
                                  classifier=classifier)
      PomWriter(get_pushdb, tag).write(tgt, path(extension='pom'), extra_confs=extra_confs,
                                       classifier=classifier)

      return ivyxml

    def stage_artifacts(tgt, jar, version, tag, changelog):
      if self.get_options().individual_plugins:
        return stage_individual_plugins(tgt, jar, version, tag, changelog)
      DEFAULT_IVY_TYPE = 'jar'
      DEFAULT_CLASSIFIER = ''
      DEFAULT_EXTENSION = 'jar'

      self._copy_artifact(tgt, jar, version, typename='jars')
      self.create_source_jar(tgt, jar, version)
      doc_jar = self.create_doc_jar(tgt, jar, version)

      confs = set(repo['confs'])
      extra_confs = []

      # Process any extra jars that might have been previously generated for this target, or a
      # target that it was derived from.
      for extra_product, extra_config in (self.get_options().publish_extras or {}).items():
        override_name = jar.name
        if 'override_name' in extra_config:
          # If the supplied string has a '{target_provides_name}' in it, replace it with the
          # current jar name. If not, the string will be taken verbatim.
          override_name = extra_config['override_name'].format(target_provides_name=jar.name)

        classifier = DEFAULT_CLASSIFIER
        suffix = ''
        ivy_type = DEFAULT_IVY_TYPE
        if 'classifier' in extra_config:
          classifier = extra_config['classifier']
          suffix = "-{0}".format(classifier)
          ivy_type = classifier

        extension = DEFAULT_EXTENSION
        if 'extension' in extra_config:
          extension = extra_config['extension']
          if ivy_type == DEFAULT_IVY_TYPE:
            ivy_type = extension

        # A lot of flexibility is allowed in naming the extra artifact. Because the name must be
        # unique, some extra logic is required to ensure that the user supplied at least one
        # non-default value (thus ensuring a uniquely-named artifact in the end).
        if override_name == jar.name and classifier == DEFAULT_CLASSIFIER and extension == DEFAULT_EXTENSION:
          raise TaskError("publish_extra for '{0}' must override one of name, classifier or "
                          "extension with a non-default value.".format(extra_product))

        ivy_tmpl_key = classifier or '{}-{}'.format(override_name, extension)

        # Build a list of targets to check. This list will consist of the current target, plus the
        # entire derived_from chain.
        target_list = [tgt]
        target = tgt
        while target.derived_from != target:
          target_list.append(target.derived_from)
          target = target.derived_from
        for cur_tgt in target_list:
          if self.context.products.get(extra_product).has(cur_tgt):
            self._copy_artifact(cur_tgt, jar, version, typename=extra_product,
                                suffix=suffix, extension=extension,
                                override_name=override_name)
            confs.add(ivy_tmpl_key)
            # Supply extra data about this jar into the Ivy template, so that Ivy will publish it
            # to the final destination.
            extra_confs.append({'name': override_name,
                                'type': ivy_type,
                                'conf': ivy_tmpl_key,
                                'classifier': classifier,
                                'ext': extension})

      confs.add(IvyWriter.SOURCES_CONFIG)
      # don't request docs unless they are available for all transitive targets
      # TODO: doc products should be checked by an independent jar'ing task, and
      # conditionally enabled; see https://github.com/pantsbuild/pants/issues/568
      if doc_jar and self._java_doc(tgt) and self._scala_doc(tgt):
        confs.add(IvyWriter.JAVADOC_CONFIG)
      return stage_artifact(tgt, jar, version, tag, changelog, confs, extra_confs=extra_confs)

    # TODO Remove this once we fix https://github.com/pantsbuild/pants/issues/1229
    def stage_individual_plugins(tgt, jar, version, tag_name, changelog):
      DEFAULT_IVY_TYPE = 'jar'
      DEFAULT_CLASSIFIER = ''
      DEFAULT_CONF = 'default'
      DEFAULT_EXT = 'jar'
      product_config = {
        'jars': {
          'classifier': '',
          },
      }
      product_config.update(self.get_options().publish_extras or {})
      for product, config in product_config.items():
        if self.context.products.get(product).has(tgt):
          classifier = config.get('classifier', DEFAULT_CLASSIFIER)
          suffix = '-' + classifier if classifier else ''
          self._copy_artifact(tgt, jar, version, suffix=suffix, typename=product)
          extra_confs = {}
          if product == 'jars':
            confs = set(repo['confs'])
            self.create_source_jar(tgt, jar, version)
            doc_jar = self.create_doc_jar(tgt, jar, version)
            confs.add(IvyWriter.SOURCES_CONFIG)
            if doc_jar and self._java_doc(tgt) and self._scala_doc(tgt):
              confs.add(IvyWriter.JAVADOC_CONFIG)
          else:
            confs = [classifier, DEFAULT_CONF]
            extra_confs = {'name': None,
                           'type': config.get('ivy_type', DEFAULT_IVY_TYPE),
                           'classifier': classifier,
                           'conf': confs,
                           'ext': DEFAULT_EXT}
          return stage_artifact(tgt, jar, version, tag_name, changelog, confs,
                              extra_confs=extra_confs, classifier=classifier)
      raise ValueError('No product mapping in {0} for {1}. '
                       'You may need to run some other task first'.format(product_config.keys(),
                                                                          tgt))

    if self.overrides:
      print('\nPublishing with revision overrides:')
      for (org, name), rev in self.overrides.items():
        print('{0}={1}'.format(coordinate(org, name), rev))

    head_sha = self.scm.commit_id

    safe_rmtree(self.workdir)
    published = []
    skip = (self.restart_at is not None)
    for target in exported_targets:
      pushdb, dbfile, repo = get_db(target)
      oldentry = pushdb.get_entry(target)

      # the jar version is ignored here, since it is overridden below with the new entry
      jar, _, _ = target.get_artifact_info()
      published.append(jar)

      if skip and (jar.org, jar.name) == self.restart_at:
        skip = False
      # select the next version: either a named version, or semver via the pushdb/overrides
      if self.named_snapshot:
        newentry = oldentry.with_named_ver(self.named_snapshot)
      else:
        override = self.overrides.get((jar.org, jar.name))
        sem_ver = override if override else oldentry.sem_ver.bump()
        if self.local_snapshot:
          sem_ver = sem_ver.make_snapshot()

        if sem_ver <= oldentry.sem_ver:
          raise TaskError('Requested version {} must be greater than the current version {}'.format(
            sem_ver, oldentry.sem_ver
          ))
        newentry = oldentry.with_sem_ver(sem_ver)

      newfingerprint = self.fingerprint(target, fingerprint_internal)
      newentry = newentry.with_sha_and_fingerprint(head_sha, newfingerprint)
      no_changes = newentry.fingerprint == oldentry.fingerprint

      changelog = ''
      if self.publish_changelog:
        if no_changes:
          changelog = 'No changes for {0} - forced push.\n'.format(pushdb_coordinate(jar, oldentry))
        else:
          changelog = self.changelog(target, oldentry.sha) or 'Direct dependencies changed.\n'

      org = jar.org
      name = jar.name
      rev = newentry.version().version()
      tag_name = '{org}-{name}-{rev}'.format(org=org, name=name, rev=rev) if self.commit else None

      if no_changes and not self.force:
        print('No changes for {0}'.format(pushdb_coordinate(jar, oldentry)))
        stage_artifacts(target, jar, oldentry.version().version(), tag_name, changelog)
      elif skip:
        print('Skipping {} to resume at {}'.format(
          jar_coordinate(jar, (newentry.version() if self.force else oldentry.version()).version()),
          coordinate(self.restart_at[0], self.restart_at[1])
        ))
        stage_artifacts(target, jar, oldentry.version().version(), tag_name, changelog)
      else:
        if not self.dryrun:
          # Confirm push looks good
          if self.publish_changelog:
            if no_changes:
              print(changelog)
            else:
              # The changelog may contain non-ascii text, but the print function can, under certain
              # circumstances, incorrectly detect the output encoding to be ascii and thus blow up on
              # non-ascii changelog characters.  Here we explicitly control the encoding to avoid
              # the print function's mis-interpretation.
              # TODO(John Sirois): Consider introducing a pants/util `print_safe` helper for this.
              message = '\nChanges for {} since {} @ {}:\n\n{}\n'.format(
                  coordinate(jar.org, jar.name), oldentry.version(), oldentry.sha, changelog)
              # The stdout encoding can be detected as None when running without a tty (common in
              # tests), in which case we want to force encoding with a unicode-supporting codec.
              encoding = sys.stdout.encoding or 'utf-8'
              sys.stdout.write(message.encode(encoding))
          if not self.confirm_push(coordinate(jar.org, jar.name), newentry.version()):
            raise TaskError('User aborted push')

        pushdb.set_entry(target, newentry)
        ivyxml = stage_artifacts(target, jar, rev, tag_name, changelog)

        if self.dryrun:
          print('Skipping publish of {0} in test mode.'.format(pushdb_coordinate(jar, newentry)))
        else:
          self.publish(ivyxml, jar=jar, entry=newentry, repo=repo, published=published)

          if self.commit:
            coord = coordinate(org, name, rev)

            pushdb.dump(dbfile)

            self.publish_pushdb_changes_to_remote_scm(
              pushdb_file=dbfile,
              coordinate=coord,
              tag_name=tag_name,
              tag_message='Publish of {coordinate} initiated by {user} {cause}'.format(
                coordinate=coord,
                user=getpass.getuser(),
                cause='with forced revision' if (org, name) in self.overrides else '(autoinc)',
              ),
              postscript=self.push_postscript
            )

  def artifact_path(self, jar, version, name=None, suffix='', extension='jar', artifact_ext=''):
    return os.path.join(self.workdir, jar.org, jar.name + artifact_ext,
                        '{}{}-{}{}.{}'.format((name or jar.name),
                                              artifact_ext if name != 'ivy' else '',
                                              version,
                                              suffix,
                                              extension))

  def check_targets(self, targets):
    invalid = defaultdict(lambda: defaultdict(set))
    derived_by_target = defaultdict(set)

    def collect_invalid(publish_target, walked_target):
      for derived_target in walked_target.derived_from_chain:
        derived_by_target[derived_target].add(walked_target)
      if not walked_target.has_sources() or not walked_target.sources_relative_to_buildroot():
        invalid[publish_target][walked_target].add('No sources.')
      if not walked_target.is_exported:
        invalid[publish_target][walked_target].add('Does not provide a binary artifact.')

    for target in targets:
      target.walk(functools.partial(collect_invalid, target),
                  predicate=lambda t: isinstance(t, Jarable))

    # When walking the graph of a publishable target, we may encounter families of sibling targets
    # that form a derivation chain.  As long as one of these siblings is publishable, we can
    # proceed and publish a valid graph.
    for publish_target, invalid_targets in list(invalid.items()):
      for invalid_target, reasons in list(invalid_targets.items()):
        derived_from_set = derived_by_target[invalid_target]
        if derived_from_set - set(invalid_targets.keys()):
          invalid_targets.pop(invalid_target)
      if not invalid_targets:
        invalid.pop(publish_target)

    if invalid:
      msg = list()

      def first_address(pair):
        first, _ = pair
        return str(first.address)

      for publish_target, invalid_targets in sorted(invalid.items(), key=first_address):
        msg.append('\n  Cannot publish {} due to:'.format(publish_target.address))
        for invalid_target, reasons in sorted(invalid_targets.items(), key=first_address):
          for reason in sorted(reasons):
            msg.append('\n    {} - {}'.format(invalid_target.address, reason))

      raise TaskError('The following errors must be resolved to publish.{}'.format(''.join(msg)))

  def exported_targets(self):
    candidates = set()
    if self.transitive:
      candidates.update(self.context.targets())
    else:
      candidates.update(self.context.target_roots)

      def get_synthetic(lang, target):
        mappings = self.context.products.get(lang).get(target)
        if mappings:
          for key, generated in mappings.items():
            for synthetic in generated:
              yield synthetic

      # Handle the case where a code gen target is in the listed roots and thus the publishable
      # target is a synthetic twin generated by a code gen task upstream.
      for candidate in self.context.target_roots:
        candidates.update(get_synthetic('java', candidate))
        candidates.update(get_synthetic('scala', candidate))

    def exportable(tgt):
      return tgt in candidates and tgt.is_exported

    return OrderedSet(filter(exportable,
                             reversed(sort_targets(filter(exportable, candidates)))))

  def fingerprint(self, target, fingerprint_internal):
    sha = hashlib.sha1()
    sha.update(target.invalidation_hash())

    # TODO(Tejal Desai): pantsbuild/pants/65: Remove java_sources attribute for ScalaLibrary
    if isinstance(target, ScalaLibrary):
      for java_source in sorted(target.java_sources):
        sha.update(java_source.invalidation_hash())

    # TODO(John Sirois): handle resources

    for jarsig in sorted([jar_coordinate(j) for j in target.jar_dependencies if j.rev]):
      sha.update(jarsig)

    # TODO(tdesai) Handle resource type in get_db.
    internal_dependencies = sorted(target_internal_dependencies(target), key=lambda t: t.id)
    for internal_target in internal_dependencies:
      fingerprint = fingerprint_internal(internal_target)
      sha.update(fingerprint)

    return sha.hexdigest()

  def changelog(self, target, sha):
    return ensure_text(self.scm.changelog(from_commit=sha,
                                          files=target.sources_relative_to_buildroot()))

  def fetch_ivysettings(self, ivy):
    if self.get_options().ivy_settings:
      return self.get_options().ivy_settings
    elif ivy.ivy_settings is None:
      raise TaskError('An ivysettings.xml with writeable resolvers is required for publishing, '
                      'but none was configured.')
    else:
      return ivy.ivy_settings

  def generate_ivysettings(self, ivy, publishedjars, publish_local=None):
    template_relpath = os.path.join('templates', 'jar_publish', 'ivysettings.mustache')
    template = pkgutil.get_data(__name__, template_relpath)
    with safe_open(os.path.join(self.workdir, 'ivysettings.xml'), 'w') as wrapper:
      generator = Generator(template,
                            ivysettings=self.fetch_ivysettings(ivy),
                            dir=self.workdir,
                            cachedir=self.cachedir,
                            published=[TemplateData(org=jar.org, name=jar.name)
                                       for jar in publishedjars],
                            publish_local=publish_local)
      generator.write(wrapper)
      return wrapper.name

  def create_source_jar(self, target, open_jar, version):
    # TODO(Tejal Desai) pantsbuild/pants/65: Avoid creating 2 jars with java sources for a
    # scala_library with java_sources. Currently publish fails fast if scala_library owning
    # java sources pointed by java_library target also provides an artifact. However, jar_create
    # ends up creating 2 jars one scala and other java both including the java_sources.

    def abs_and_relative_sources(target):
      abs_source_root = os.path.join(get_buildroot(), target.target_base)
      for source in target.sources_relative_to_source_root():
        yield os.path.join(abs_source_root, source), source

    jar_path = self.artifact_path(open_jar, version, suffix='-sources')
    with self.open_jar(jar_path, overwrite=True, compressed=True) as open_jar:
      for abs_source, rel_source in abs_and_relative_sources(target):
        open_jar.write(abs_source, rel_source)

      # TODO(Tejal Desai): pantsbuild/pants/65 Remove java_sources attribute for ScalaLibrary
      if isinstance(target, ScalaLibrary):
        for java_source_target in target.java_sources:
          for abs_source, rel_source in abs_and_relative_sources(java_source_target):
            open_jar.write(abs_source, rel_source)

      if target.has_resources:
        for resource_target in target.resources:
          for abs_source, rel_source in abs_and_relative_sources(resource_target):
            open_jar.write(abs_source, rel_source)

    return jar_path

  def _java_doc(self, target):
    return self.context.products.get('javadoc').get(target)

  def _scala_doc(self, target):
    return self.context.products.get('scaladoc').get(target)

  def create_doc_jar(self, target, open_jar, version):
    """Returns a doc jar if either scala or java docs are available for the given target."""
    javadoc = self._java_doc(target)
    scaladoc = self._scala_doc(target)
    if javadoc or scaladoc:
      jar_path = self.artifact_path(open_jar, version, suffix='-javadoc')
      with self.open_jar(jar_path, overwrite=True, compressed=True) as open_jar:
        def add_docs(docs):
          if docs:
            for basedir, doc_files in docs.items():
              for doc_file in doc_files:
                open_jar.write(os.path.join(basedir, doc_file), doc_file)

        add_docs(javadoc)
        add_docs(scaladoc)
      return jar_path
    else:
      return None


text:
namespace JsonFormatterPlus.Internals.Strategies
{
    internal sealed class ColonCharacterStrategy : ICharacterStrategy
    {
        public char ForWhichCharacter => ':';

        public void Execute(JsonFormatterStrategyContext context)
        {
            if (context.IsProcessingString)
            {
                context.AppendCurrentChar();
                return;
            }

            context.IsProcessingVariableAssignment = true;
            context.AppendCurrentChar();
            context.AppendSpace();
        }
    }
}


text:
/* Layout helpers
----------------------------------*/
.ui-helper-hidden { display: none; }
.ui-helper-hidden-accessible { position: absolute; left: -99999999px; }
.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.ui-helper-clearfix { display: inline-block; }
/* required comment for clearfix to work in Opera \*/
* html .ui-helper-clearfix { height:1%; }
.ui-helper-clearfix { display:block; }
/* end clearfix */
.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }

/* Interaction Cues
----------------------------------*/
.ui-state-disabled { cursor: default !important; }

/* Icons
----------------------------------*/

/* states and images */
.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }

/* Misc visuals
----------------------------------*/

/* Overlays */
.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

/*
 * jQuery UI CSS Framework @VERSION
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Theming/API
 *
 */

/* Component containers
----------------------------------*/
.ui-widget { font-size: 12px; }
.ui-widget .ui-widget { font-size: 1em; }
.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif; font-size: 1em; }
.ui-widget-content {  }
.ui-widget-content a { color: #222222; }
.ui-widget-header { font-weight: bold; }
.ui-widget-header a { color: #222222; }

/* Interaction states
----------------------------------*/
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border-left: 1px solid #d5d5d5; font-weight: normal; border-bottom: 1px solid #D5D5D5; }
th.ui-state-default:first-child { border-left: none; }
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; }
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { background: #fafafa; font-weight: normal; color: #212121; }
.ui-state-hover a, .ui-state-hover a:hover { color: #797979; text-decoration: none; }
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { background: #fafafa; font-weight: normal; color: #797979; }
.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #797979; text-decoration: none; }
.ui-widget :active { outline: none; }

/* Interaction Cues
----------------------------------*/
.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; }
.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #fef1ec url(../images/jquery_ui/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; color: #cd0a0a; }
.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a; }
.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a; }
.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
.ui-priority-secondary, .ui-widget-content .ui-priority-secondary,  .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }

/* Icons
----------------------------------*/

/* states and images */
.ui-icon { width: 16px; height: 16px; background-image: url(../images/jquery_ui/ui-icons_222222_256x240.png); }
.ui-widget-content .ui-icon {background-image: url(../images/jquery_ui/ui-icons_222222_256x240.png); }
.ui-widget-header .ui-icon {background-image: url(../images/jquery_ui/ui-icons_222222_256x240.png); }
.ui-state-default .ui-icon { background-image: url(../images/jquery_ui/ui-icons_888888_256x240.png); }
.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(../images/jquery_ui/ui-icons_454545_256x240.png); }
.ui-state-active .ui-icon {background-image: url(../images/jquery_ui/ui-icons_454545_256x240.png); }
.ui-state-highlight .ui-icon {background-image: url(../images/jquery_ui/ui-icons_2e83ff_256x240.png); }
.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(../images/jquery_ui/ui-icons_cd0a0a_256x240.png); }

/* positioning */
.ui-icon-carat-1-n { background-position: 0 0; }
.ui-icon-carat-1-ne { background-position: -16px 0; }
.ui-icon-carat-1-e { background-position: -32px 0; }
.ui-icon-carat-1-se { background-position: -48px 0; }
.ui-icon-carat-1-s { background-position: -64px 0; }
.ui-icon-carat-1-sw { background-position: -80px 0; }
.ui-icon-carat-1-w { background-position: -96px 0; }
.ui-icon-carat-1-nw { background-position: -112px 0; }
.ui-icon-carat-2-n-s { background-position: -128px 0; }
.ui-icon-carat-2-e-w { background-position: -144px 0; }
.ui-icon-triangle-1-n { background-position: 0 -16px; }
.ui-icon-triangle-1-ne { background-position: -16px -16px; }
.ui-icon-triangle-1-e { background-position: -32px -16px; }
.ui-icon-triangle-1-se { background-position: -48px -16px; }
.ui-icon-triangle-1-s { background-position: -64px -16px; }
.ui-icon-triangle-1-sw { background-position: -80px -16px; }
.ui-icon-triangle-1-w { background-position: -96px -16px; }
.ui-icon-triangle-1-nw { background-position: -112px -16px; }
.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
.ui-icon-arrow-1-n { background-position: 0 -32px; }
.ui-icon-arrow-1-ne { background-position: -16px -32px; }
.ui-icon-arrow-1-e { background-position: -32px -32px; }
.ui-icon-arrow-1-se { background-position: -48px -32px; }
.ui-icon-arrow-1-s { background-position: -64px -32px; }
.ui-icon-arrow-1-sw { background-position: -80px -32px; }
.ui-icon-arrow-1-w { background-position: -96px -32px; }
.ui-icon-arrow-1-nw { background-position: -112px -32px; }
.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
.ui-icon-arrow-4 { background-position: 0 -80px; }
.ui-icon-arrow-4-diag { background-position: -16px -80px; }
.ui-icon-extlink { background-position: -32px -80px; }
.ui-icon-newwin { background-position: -48px -80px; }
.ui-icon-refresh { background-position: -64px -80px; }
.ui-icon-shuffle { background-position: -80px -80px; }
.ui-icon-transfer-e-w { background-position: -96px -80px; }
.ui-icon-transferthick-e-w { background-position: -112px -80px; }
.ui-icon-folder-collapsed { background-position: 0 -96px; }
.ui-icon-folder-open { background-position: -16px -96px; }
.ui-icon-document { background-position: -32px -96px; }
.ui-icon-document-b { background-position: -48px -96px; }
.ui-icon-note { background-position: -64px -96px; }
.ui-icon-mail-closed { background-position: -80px -96px; }
.ui-icon-mail-open { background-position: -96px -96px; }
.ui-icon-suitcase { background-position: -112px -96px; }
.ui-icon-comment { background-position: -128px -96px; }
.ui-icon-person { background-position: -144px -96px; }
.ui-icon-print { background-position: -160px -96px; }
.ui-icon-trash { background-position: -176px -96px; }
.ui-icon-locked { background-position: -192px -96px; }
.ui-icon-unlocked { background-position: -208px -96px; }
.ui-icon-bookmark { background-position: -224px -96px; }
.ui-icon-tag { background-position: -240px -96px; }
.ui-icon-home { background-position: 0 -112px; }
.ui-icon-flag { background-position: -16px -112px; }
.ui-icon-calendar { background-position: -32px -112px; }
.ui-icon-cart { background-position: -48px -112px; }
.ui-icon-pencil { background-position: -64px -112px; }
.ui-icon-clock { background-position: -80px -112px; }
.ui-icon-disk { background-position: -96px -112px; }
.ui-icon-calculator { background-position: -112px -112px; }
.ui-icon-zoomin { background-position: -128px -112px; }
.ui-icon-zoomout { background-position: -144px -112px; }
.ui-icon-search { background-position: -160px -112px; }
.ui-icon-wrench { background-position: -176px -112px; }
.ui-icon-gear { background-position: -192px -112px; }
.ui-icon-heart { background-position: -208px -112px; }
.ui-icon-star { background-position: -224px -112px; }
.ui-icon-link { background-position: -240px -112px; }
.ui-icon-cancel { background-position: 0 -128px; }
.ui-icon-plus { background-position: -16px -128px; }
.ui-icon-plusthick { background-position: -32px -128px; }
.ui-icon-minus { background-position: -48px -128px; }
.ui-icon-minusthick { background-position: -64px -128px; }
.ui-icon-close { background-position: -80px -128px; }
.ui-icon-closethick { background-position: -96px -128px; }
.ui-icon-key { background-position: -112px -128px; }
.ui-icon-lightbulb { background-position: -128px -128px; }
.ui-icon-scissors { background-position: -144px -128px; }
.ui-icon-clipboard { background-position: -160px -128px; }
.ui-icon-copy { background-position: -176px -128px; }
.ui-icon-contact { background-position: -192px -128px; }
.ui-icon-image { background-position: -208px -128px; }
.ui-icon-video { background-position: -224px -128px; }
.ui-icon-script { background-position: -240px -128px; }
.ui-icon-alert { background-position: 0 -144px; }
.ui-icon-info { background-position: -16px -144px; }
.ui-icon-notice { background-position: -32px -144px; }
.ui-icon-help { background-position: -48px -144px; }
.ui-icon-check { background-position: -64px -144px; }
.ui-icon-bullet { background-position: -80px -144px; }
.ui-icon-radio-off { background-position: -96px -144px; }
.ui-icon-radio-on { background-position: -112px -144px; }
.ui-icon-pin-w { background-position: -128px -144px; }
.ui-icon-pin-s { background-position: -144px -144px; }
.ui-icon-play { background-position: 0 -160px; }
.ui-icon-pause { background-position: -16px -160px; }
.ui-icon-seek-next { background-position: -32px -160px; }
.ui-icon-seek-prev { background-position: -48px -160px; }
.ui-icon-seek-end { background-position: -64px -160px; }
.ui-icon-seek-start { background-position: -80px -160px; }
.ui-icon-seek-first { background-position: -80px -160px; }
.ui-icon-stop { background-position: -96px -160px; }
.ui-icon-eject { background-position: -112px -160px; }
.ui-icon-volume-off { background-position: -128px -160px; }
.ui-icon-volume-on { background-position: -144px -160px; }
.ui-icon-power { background-position: 0 -176px; }
.ui-icon-signal-diag { background-position: -16px -176px; }
.ui-icon-signal { background-position: -32px -176px; }
.ui-icon-battery-0 { background-position: -48px -176px; }
.ui-icon-battery-1 { background-position: -64px -176px; }
.ui-icon-battery-2 { background-position: -80px -176px; }
.ui-icon-battery-3 { background-position: -96px -176px; }
.ui-icon-circle-plus { background-position: 0 -192px; }
.ui-icon-circle-minus { background-position: -16px -192px; }
.ui-icon-circle-close { background-position: -32px -192px; }
.ui-icon-circle-triangle-e { background-position: -48px -192px; }
.ui-icon-circle-triangle-s { background-position: -64px -192px; }
.ui-icon-circle-triangle-w { background-position: -80px -192px; }
.ui-icon-circle-triangle-n { background-position: -96px -192px; }
.ui-icon-circle-arrow-e { background-position: -112px -192px; }
.ui-icon-circle-arrow-s { background-position: -128px -192px; }
.ui-icon-circle-arrow-w { background-position: -144px -192px; }
.ui-icon-circle-arrow-n { background-position: -160px -192px; }
.ui-icon-circle-zoomin { background-position: -176px -192px; }
.ui-icon-circle-zoomout { background-position: -192px -192px; }
.ui-icon-circle-check { background-position: -208px -192px; }
.ui-icon-circlesmall-plus { background-position: 0 -208px; }
.ui-icon-circlesmall-minus { background-position: -16px -208px; }
.ui-icon-circlesmall-close { background-position: -32px -208px; }
.ui-icon-squaresmall-plus { background-position: -48px -208px; }
.ui-icon-squaresmall-minus { background-position: -64px -208px; }
.ui-icon-squaresmall-close { background-position: -80px -208px; }
.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
.ui-icon-grip-diagonal-se { background-position: -80px -224px; }

/* Misc visuals
----------------------------------*/

.ui-corner-tl { -moz-border-radius-topleft: 2px; -webkit-border-top-left-radius: 2px; border-top-left-radius: 2px; }
.ui-corner-tr { -moz-border-radius-topright: 2px; -webkit-border-top-right-radius: 2px; border-top-right-radius: 2px; }
.ui-corner-bl { -moz-border-radius-bottomleft: 2px; -webkit-border-bottom-left-radius: 2px; border-bottom-left-radius: 2px; }
.ui-corner-br { -moz-border-radius-bottomright: 2px; -webkit-border-bottom-right-radius: 2px; border-bottom-right-radius: 2px; }
.ui-corner-top { -moz-border-radius-topleft: 2px; -webkit-border-top-left-radius: 2px; border-top-left-radius: 2px; -moz-border-radius-topright: 2px; -webkit-border-top-right-radius: 2px; border-top-right-radius: 2px; }
.ui-corner-bottom { -moz-border-radius-bottomleft: 2px; -webkit-border-bottom-left-radius: 2px; border-bottom-left-radius: 2px; -moz-border-radius-bottomright: 2px; -webkit-border-bottom-right-radius: 2px; border-bottom-right-radius: 2px; }
.ui-corner-right {  -moz-border-radius-topright: 2px; -webkit-border-top-right-radius: 2px; border-top-right-radius: 2px; -moz-border-radius-bottomright: 2px; -webkit-border-bottom-right-radius: 2px; border-bottom-right-radius: 2px; }
.ui-corner-left { -moz-border-radius-topleft: 2px; -webkit-border-top-left-radius: 2px; border-top-left-radius: 2px; -moz-border-radius-bottomleft: 2px; -webkit-border-bottom-left-radius: 2px; border-bottom-left-radius: 2px; }
.ui-corner-all { -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px; }

/* Overlays */
.ui-widget-overlay { background: #aaaaaa url(../images/jquery_ui/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); }
.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(../images/jquery_ui/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; }

/* ===== UI resizable ===== */

.ui-resizable { position: relative;}
.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block;}
.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; }
.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; }
.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; }
.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; }
.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}

.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; }

.ui-accordion { width: 100%; }
.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; }
.ui-accordion .ui-accordion-li-fix { display: inline; }
.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; }
.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em .7em; }
.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; }
.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; }
.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; }
.ui-accordion .ui-accordion-content-active { display: block; }
.ui-autocomplete { position: absolute; cursor: default; }

/* workarounds */
* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */

.ui-menu { list-style:none; padding: 2px; margin: 0; display:block; float: left; }
.ui-menu .ui-menu { margin-top: -3px; }
.ui-menu .ui-menu-item { margin:0; padding: 0; zoom: 1; float: left; clear: left; width: 100%; }
.ui-menu .ui-menu-item a { text-decoration:none; display:block; padding:.2em .4em; line-height:1.5; zoom:1; }
.ui-menu .ui-menu-item a.ui-state-hover, .ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px;
}

.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */
.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */
button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */
.ui-button-icons-only { width: 3.4em; }
button.ui-button-icons-only { width: 3.7em; }

/*button text element */
.ui-button .ui-button-text { display: block; line-height: 1.4;  }
.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; }
.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; }
.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; }
.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; }
/* no icon support for input elements, provide padding by default */
input.ui-button { padding: .4em 1em; }

/*button icon element(s) */
.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; }
.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; }
.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; }
.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }

/*button sets*/
.ui-buttonset { margin-right: 5px; }
.ui-buttonset .ui-button { margin: 0 3px; background: #FAFAFA; border: 1px solid #D5D5D5; line-height: 14px; font-size: 11px; }

/* workarounds */
button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */

/* ===== UI Dialog ===== */

.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; }
.ui-dialog .ui-dialog-titlebar { position: relative;  }
.ui-dialog .ui-dialog-title { float: left; height: 38px; font-size: 16px; padding: 0 12px 0 12px; line-height: 38px; }
.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: 6px; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; }
.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 1px; background: #fafafa; }
.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; }
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; }
.ui-dialog .ui-dialog-buttonpane button { font-size: 10px; font-weight: bold; text-transform: uppercase; padding: 3px 12px 4px 12px; cursor: pointer; font-family: Arial, Helvetica, sans-serif; border: 1px solid #d5d5d5; color: #525252; margin: 5px; }
.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; }
.ui-draggable .ui-dialog-titlebar { cursor: move; }

/* ===== UI Slider ===== */

.ui-slider { position: relative; text-align: left; }
.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 16px; height: 16px; cursor: default; background: url(../images/ui/handle.png) no-repeat; border: none; cursor: pointer; }
.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background: url(../images/ui/sliderOverlay.png) repeat-x; -moz-border-radius: 4px; -webkit-border-radius: 4px; -khtml-border-radius: 4px; border-radius: 4px; }

.ui-slider-horizontal { height: 6px; background: url(../images/ui/sliderBg.png) repeat-x; clear: both; margin-top: 10px; }
.ui-slider-horizontal .ui-slider-handle { top: -5px; margin-left: -.6em; }
.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; }
.ui-slider-horizontal .ui-slider-range-min { left: 0; }
.ui-slider-horizontal .ui-slider-range-max { right: 0; }

.ui-slider-vertical { width: 6px; height: 100px; background: url(../images/ui/sliderBgVert.png) repeat-y; }
.ui-slider-vertical .ui-slider-handle { left: -5px; margin-left: 0; margin-bottom: -.6em; }
.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; background: url(../images/ui/sliderOverlayVert.png) repeat-y; }
.ui-slider-vertical .ui-slider-range-min { bottom: 0; }
.ui-slider-vertical .ui-slider-range-max { top: 0; }

/* ===== UI Tabs ===== */

.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; }
.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; }
.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; }
.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; }
.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; }
.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; }
.ui-tabs .ui-tabs-hide { display: none !important; }

/* ===== UI Datepicker ===== */

.datepicker { width: 70px!important; }
.ui-datepicker { width: 17em; padding: .2em .2em 0; border: 1px solid #d5d5d5; background: #fafafa; margin-top: 1px; z-index: 3; display: none; }
.ui-datepicker-append { margin-left: 10px; }
.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; border: 1px solid #E7E7E7; background: url(../images/leftNavBg.png) repeat-x; }
.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
.ui-datepicker .ui-datepicker-prev { left:2px; }
.ui-datepicker .ui-datepicker-next { right:2px; }
.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
.ui-datepicker .ui-datepicker-next-hover { right:1px; }
.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px;  }
.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
.ui-datepicker select.ui-datepicker-month,
.ui-datepicker select.ui-datepicker-year { width: 49%;}
.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
.ui-datepicker table .ui-state-default { border: 1px solid #d5d5d5; }
.ui-datepicker table tbody { font-size: 11px; }
.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0;  }
.ui-datepicker td { border: 0; padding: 1px; }
.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }

/* with multiple calendars */
.ui-datepicker.ui-datepicker-multi { width:auto; }
.ui-datepicker-multi .ui-datepicker-group { float:left; }
.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
.ui-datepicker-row-break { clear:both; width:100%; }

/* RTL support */
.ui-datepicker-rtl { direction: rtl; }
.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
.ui-datepicker-rtl .ui-datepicker-group { float:right; }
.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }

/* ===== UI Progress bar ===== */

.ui-progressbar { height: 16px; text-align: left; margin-top: 5px; background: url(../images/ui/progress.png) repeat-x; }
.ui-progressbar .ui-progressbar-value {margin: 0px; height:100%; overflow: hidden; display: block; background: url(../images/ui/progressOverlay.png) repeat-x; border-right: 1px solid #3c95d8; }
.pbar .ui-progressbar-value {display:block !important}
.pbar { overflow: hidden; background: url(../images/ui/progress.png) repeat-x;}
.percent { position: relative; text-align: right; margin-bottom: 5px; font-size: 11px; }
.elapsed { position: relative; text-align: right; margin-top: 5px; font-size: 11px;}

/*
 * jQuery UI Autocomplete 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Autocomplete#theming
 */
.ui-autocomplete { position: absolute; cursor: default; }

/* workarounds */
* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */

/*
 * jQuery UI Menu 1.8.16
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Menu#theming
 */
.ui-menu {
	list-style:none;
	padding: 2px;
	margin: 0;
	display:block;
	float: left;
    border: 1px solid #3C4049;
    border-top: 0;
    z-index: 11;
}
.ui-menu .ui-menu {
	margin-top: -3px;
}
.ui-menu .ui-menu-item {
	margin:0;
	padding: 0;
	zoom: 1;
	float: left;
	clear: left;
	width: 100%;
    background-color: #F5F5F5;
}
.ui-menu .ui-menu-item a {
	text-decoration:none;
	display:block;
	line-height:1.5;
}
.ui-menu .ui-menu-item a.ui-state-hover,
.ui-menu .ui-menu-item a.ui-state-active {
	font-weight: bold;

}