text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "core/paint/BoxBorderPainter.h"

#include "core/paint/BoxPainter.h"
#include "core/paint/PaintInfo.h"
#include "core/style/BorderEdge.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/GraphicsContextStateSaver.h"
#include "wtf/Vector.h"
#include <algorithm>

namespace blink {

namespace {

enum BorderEdgeFlag {
    TopBorderEdge = 1 << BSTop,
    RightBorderEdge = 1 << BSRight,
    BottomBorderEdge = 1 << BSBottom,
    LeftBorderEdge = 1 << BSLeft,
    AllBorderEdges = TopBorderEdge | BottomBorderEdge | LeftBorderEdge | RightBorderEdge
};

inline BorderEdgeFlag edgeFlagForSide(BoxSide side)
{
    return static_cast<BorderEdgeFlag>(1 << side);
}

inline bool includesEdge(BorderEdgeFlags flags, BoxSide side)
{
    return flags & edgeFlagForSide(side);
}

inline bool includesAdjacentEdges(BorderEdgeFlags flags)
{
    // The set includes adjacent edges iff it contains at least one horizontal and one vertical edge.
    return (flags & (TopBorderEdge | BottomBorderEdge))
        && (flags & (LeftBorderEdge | RightBorderEdge));
}

inline bool styleRequiresClipPolygon(EBorderStyle style)
{
    // These are drawn with a stroke, so we have to clip to get corner miters.
    return style == BorderStyleDotted || style == BorderStyleDashed;
}

inline bool borderStyleFillsBorderArea(EBorderStyle style)
{
    return !(style == BorderStyleDotted || style == BorderStyleDashed || style == BorderStyleDouble);
}

inline bool borderStyleHasInnerDetail(EBorderStyle style)
{
    return style == BorderStyleGroove || style == BorderStyleRidge || style == BorderStyleDouble;
}

inline bool borderStyleIsDottedOrDashed(EBorderStyle style)
{
    return style == BorderStyleDotted || style == BorderStyleDashed;
}

// BorderStyleOutset darkens the bottom and right (and maybe lightens the top and left)
// BorderStyleInset darkens the top and left (and maybe lightens the bottom and right)
inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide)
{
    // These styles match at the top/left and bottom/right.
    if (style == BorderStyleInset || style == BorderStyleGroove || style == BorderStyleRidge || style == BorderStyleOutset) {
        const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight);
        const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft);

        BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
        return flags == topRightFlags || flags == bottomLeftFlags;
    }
    return false;
}

inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
{
    if (!edges[adjacentSide].shouldRender())
        return false;

    if (!edges[side].sharesColorWith(edges[adjacentSide]))
        return false;

    return !borderStyleHasUnmatchedColorsAtCorner(edges[side].borderStyle(), side, adjacentSide);
}

inline bool borderWillArcInnerEdge(const FloatSize& firstRadius, const FloatSize& secondRadius)
{
    return !firstRadius.isZero() || !secondRadius.isZero();
}

inline bool willOverdraw(BoxSide side, EBorderStyle style, BorderEdgeFlags completedEdges)
{
    // If we're done with this side, it will obviously not overdraw any portion of the current edge.
    if (includesEdge(completedEdges, side))
        return false;

    // The side is still to be drawn. It overdraws the current edge iff it has a solid fill style.
    return borderStyleFillsBorderArea(style);
}

inline bool borderStylesRequireMiter(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
{
    if (style == BorderStyleDouble || adjacentStyle == BorderStyleDouble || adjacentStyle == BorderStyleGroove || adjacentStyle == BorderStyleRidge)
        return true;

    if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
        return true;

    if (style != adjacentStyle)
        return true;

    return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
}

FloatRect calculateSideRect(const FloatRoundedRect& outerBorder, const BorderEdge& edge, int side)
{
    FloatRect sideRect = outerBorder.rect();
    int width = edge.width;

    if (side == BSTop)
        sideRect.setHeight(width);
    else if (side == BSBottom)
        sideRect.shiftYEdgeTo(sideRect.maxY() - width);
    else if (side == BSLeft)
        sideRect.setWidth(width);
    else
        sideRect.shiftXEdgeTo(sideRect.maxX() - width);

    return sideRect;
}

FloatRect calculateSideRectIncludingInner(const FloatRoundedRect& outerBorder, const BorderEdge edges[], BoxSide side)
{
    FloatRect sideRect = outerBorder.rect();
    int width;

    switch (side) {
    case BSTop:
        width = sideRect.height() - edges[BSBottom].width;
        sideRect.setHeight(width);
        break;
    case BSBottom:
        width = sideRect.height() - edges[BSTop].width;
        sideRect.shiftYEdgeTo(sideRect.maxY() - width);
        break;
    case BSLeft:
        width = sideRect.width() - edges[BSRight].width;
        sideRect.setWidth(width);
        break;
    case BSRight:
        width = sideRect.width() - edges[BSLeft].width;
        sideRect.shiftXEdgeTo(sideRect.maxX() - width);
        break;
    }

    return sideRect;
}

FloatRoundedRect calculateAdjustedInnerBorder(const FloatRoundedRect& innerBorder, BoxSide side)
{
    // Expand the inner border as necessary to make it a rounded rect (i.e. radii contained within each edge).
    // This function relies on the fact we only get radii not contained within each edge if one of the radii
    // for an edge is zero, so we can shift the arc towards the zero radius corner.
    FloatRoundedRect::Radii newRadii = innerBorder.getRadii();
    FloatRect newRect = innerBorder.rect();

    float overshoot;
    float maxRadii;

    switch (side) {
    case BSTop:
        overshoot = newRadii.topLeft().width() + newRadii.topRight().width() - newRect.width();
        // FIXME: once we start pixel-snapping rounded rects after this point, the overshoot concept
        // should disappear.
        if (overshoot > 0.1) {
            newRect.setWidth(newRect.width() + overshoot);
            if (!newRadii.topLeft().width())
                newRect.move(-overshoot, 0);
        }
        newRadii.setBottomLeft(FloatSize(0, 0));
        newRadii.setBottomRight(FloatSize(0, 0));
        maxRadii = std::max(newRadii.topLeft().height(), newRadii.topRight().height());
        if (maxRadii > newRect.height())
            newRect.setHeight(maxRadii);
        break;

    case BSBottom:
        overshoot = newRadii.bottomLeft().width() + newRadii.bottomRight().width() - newRect.width();
        if (overshoot > 0.1) {
            newRect.setWidth(newRect.width() + overshoot);
            if (!newRadii.bottomLeft().width())
                newRect.move(-overshoot, 0);
        }
        newRadii.setTopLeft(FloatSize(0, 0));
        newRadii.setTopRight(FloatSize(0, 0));
        maxRadii = std::max(newRadii.bottomLeft().height(), newRadii.bottomRight().height());
        if (maxRadii > newRect.height()) {
            newRect.move(0, newRect.height() - maxRadii);
            newRect.setHeight(maxRadii);
        }
        break;

    case BSLeft:
        overshoot = newRadii.topLeft().height() + newRadii.bottomLeft().height() - newRect.height();
        if (overshoot > 0.1) {
            newRect.setHeight(newRect.height() + overshoot);
            if (!newRadii.topLeft().height())
                newRect.move(0, -overshoot);
        }
        newRadii.setTopRight(FloatSize(0, 0));
        newRadii.setBottomRight(FloatSize(0, 0));
        maxRadii = std::max(newRadii.topLeft().width(), newRadii.bottomLeft().width());
        if (maxRadii > newRect.width())
            newRect.setWidth(maxRadii);
        break;

    case BSRight:
        overshoot = newRadii.topRight().height() + newRadii.bottomRight().height() - newRect.height();
        if (overshoot > 0.1) {
            newRect.setHeight(newRect.height() + overshoot);
            if (!newRadii.topRight().height())
                newRect.move(0, -overshoot);
        }
        newRadii.setTopLeft(FloatSize(0, 0));
        newRadii.setBottomLeft(FloatSize(0, 0));
        maxRadii = std::max(newRadii.topRight().width(), newRadii.bottomRight().width());
        if (maxRadii > newRect.width()) {
            newRect.move(newRect.width() - maxRadii, 0);
            newRect.setWidth(maxRadii);
        }
        break;
    }

    return FloatRoundedRect(newRect, newRadii);
}

LayoutRectOutsets doubleStripeInsets(const BorderEdge edges[], BorderEdge::DoubleBorderStripe stripe)
{
    // Insets are representes as negative outsets.
    return LayoutRectOutsets(
        -edges[BSTop].getDoubleBorderStripeWidth(stripe),
        -edges[BSRight].getDoubleBorderStripeWidth(stripe),
        -edges[BSBottom].getDoubleBorderStripeWidth(stripe),
        -edges[BSLeft].getDoubleBorderStripeWidth(stripe));
}

void drawSolidBorderRect(GraphicsContext& context, const FloatRect& borderRect,
    float borderWidth, const Color& color)
{
    FloatRect strokeRect(borderRect);
    strokeRect.inflate(-borderWidth / 2);

    bool wasAntialias = context.shouldAntialias();
    if (!wasAntialias)
        context.setShouldAntialias(true);

    context.setStrokeStyle(SolidStroke);
    context.setStrokeColor(color);
    context.strokeRect(strokeRect, borderWidth);

    if (!wasAntialias)
        context.setShouldAntialias(false);
}

void drawBleedAdjustedDRRect(GraphicsContext& context, BackgroundBleedAvoidance bleedAvoidance,
    const FloatRoundedRect& outer, const FloatRoundedRect& inner, Color color)
{
    switch (bleedAvoidance) {
    case BackgroundBleedClipLayer: {
        // BackgroundBleedClipLayer clips the outer rrect for the whole layer. Based on this,
        // we can avoid background bleeding by filling the *outside* of inner rrect, all the
        // way to the layer bounds (enclosing int rect for the clip, in device space).
        ASSERT(outer.isRounded());

        SkPath path;
        path.addRRect(inner);
        path.setFillType(SkPath::kInverseWinding_FillType);

        SkPaint paint;
        paint.setColor(color.rgb());
        paint.setStyle(SkPaint::kFill_Style);
        paint.setAntiAlias(true);
        context.drawPath(path, paint);

        break;
    }
    case BackgroundBleedClipOnly:
        if (outer.isRounded()) {
            // BackgroundBleedClipOnly clips the outer rrect corners for us.
            FloatRoundedRect adjustedOuter = outer;
            adjustedOuter.setRadii(FloatRoundedRect::Radii());
            context.fillDRRect(adjustedOuter, inner, color);
            break;
        }
        // fall through
    default:
        context.fillDRRect(outer, inner, color);
        break;
    }
}

bool bleedAvoidanceIsClipping(BackgroundBleedAvoidance bleedAvoidance)
{
    return bleedAvoidance == BackgroundBleedClipOnly || bleedAvoidance == BackgroundBleedClipLayer;
}

// The LUTs below assume specific enum values.
static_assert(BorderStyleNone == 0, "unexpected EBorderStyle value");
static_assert(BorderStyleHidden == 1, "unexpected EBorderStyle value");
static_assert(BorderStyleInset == 2, "unexpected EBorderStyle value");
static_assert(BorderStyleGroove == 3, "unexpected EBorderStyle value");
static_assert(BorderStyleOutset == 4, "unexpected EBorderStyle value");
static_assert(BorderStyleRidge == 5, "unexpected EBorderStyle value");
static_assert(BorderStyleDotted == 6, "unexpected EBorderStyle value");
static_assert(BorderStyleDashed == 7, "unexpected EBorderStyle value");
static_assert(BorderStyleSolid == 8, "unexpected EBorderStyle value");
static_assert(BorderStyleDouble == 9, "unexpected EBorderStyle value");

static_assert(BSTop == 0, "unexpected BoxSide value");
static_assert(BSRight == 1, "unexpected BoxSide value");
static_assert(BSBottom == 2, "unexpected BoxSide value");
static_assert(BSLeft == 3, "unexpected BoxSide value");

// Style-based paint order: non-solid edges (dashed/dotted/double) are painted before
// solid edges (inset/outset/groove/ridge/solid) to maximize overdraw opportunities.
const unsigned kStylePriority[] = {
    0 /* BorderStyleNone */,
    0 /* BorderStyleHidden */,
    2 /* BorderStyleInset */,
    2 /* BorderStyleGroove */,
    2 /* BorderStyleOutset */,
    2 /* BorderStyleRidge */,
    1 /* BorderStyleDotted */,
    1 /* BorderStyleDashed */,
    3 /* BorderStyleSolid */,
    1 /* BorderStyleDouble */
};

// Given the same style, prefer drawing in non-adjacent order to minimize the number of sides
// which require miters.
const unsigned kSidePriority[] = {
    0, /* BSTop */
    2, /* BSRight */
    1, /* BSBottom */
    3, /* BSLeft */
};

// Edges sharing the same opacity. Stores both a side list and an edge bitfield to support
// constant time iteration + membership tests.
struct OpacityGroup {
    OpacityGroup(unsigned alpha) : edgeFlags(0), alpha(alpha) { }

    Vector<BoxSide, 4> sides;
    BorderEdgeFlags edgeFlags;
    unsigned alpha;
};

} // anonymous namespace

// Holds edges grouped by opacity and sorted in paint order.
struct BoxBorderPainter::ComplexBorderInfo {
    ComplexBorderInfo(const BoxBorderPainter& borderPainter, bool antiAlias)
        : antiAlias(antiAlias)
    {
        Vector<BoxSide, 4> sortedSides;

        // First, collect all visible sides.
        for (unsigned i = borderPainter.m_firstVisibleEdge; i < 4; ++i) {
            BoxSide side = static_cast<BoxSide>(i);

            if (includesEdge(borderPainter.m_visibleEdgeSet, side))
                sortedSides.append(side);
        }
        ASSERT(!sortedSides.isEmpty());

        // Then sort them in paint order, based on three (prioritized) criteria: alpha, style, side.
        std::sort(sortedSides.begin(), sortedSides.end(),
            [&borderPainter] (BoxSide a, BoxSide b) -> bool {
            const BorderEdge& edgeA = borderPainter.m_edges[a];
            const BorderEdge& edgeB = borderPainter.m_edges[b];

            const unsigned alphaA = edgeA.color.alpha();
            const unsigned alphaB = edgeB.color.alpha();
            if (alphaA != alphaB)
                return alphaA < alphaB;

            const unsigned stylePriorityA = kStylePriority[edgeA.borderStyle()];
            const unsigned stylePriorityB = kStylePriority[edgeB.borderStyle()];
            if (stylePriorityA != stylePriorityB)
                return stylePriorityA < stylePriorityB;

            return kSidePriority[a] < kSidePriority[b];
        });

        // Finally, build the opacity group structures.
        buildOpacityGroups(borderPainter, sortedSides);

        if (borderPainter.m_isRounded)
            roundedBorderPath.addRoundedRect(borderPainter.m_outer);
    }

    Vector<OpacityGroup, 4> opacityGroups;

    // Potentially used when drawing rounded borders.
    Path roundedBorderPath;

    bool antiAlias;

private:
    void buildOpacityGroups(const BoxBorderPainter& borderPainter,
        const Vector<BoxSide, 4>& sortedSides)
    {
        unsigned currentAlpha = 0;
        for (BoxSide side : sortedSides) {
            const BorderEdge& edge = borderPainter.m_edges[side];
            const unsigned edgeAlpha = edge.color.alpha();

            ASSERT(edgeAlpha > 0);
            ASSERT(edgeAlpha >= currentAlpha);
            if (edgeAlpha != currentAlpha) {
                opacityGroups.append(OpacityGroup(edgeAlpha));
                currentAlpha = edgeAlpha;
            }

            ASSERT(!opacityGroups.isEmpty());
            OpacityGroup& currentGroup = opacityGroups.last();
            currentGroup.sides.append(side);
            currentGroup.edgeFlags |= edgeFlagForSide(side);
        }

        ASSERT(!opacityGroups.isEmpty());
    }
};

void BoxBorderPainter::drawDoubleBorder(GraphicsContext& context, const LayoutRect& borderRect) const
{
    ASSERT(m_isUniformColor);
    ASSERT(m_isUniformStyle);
    ASSERT(firstEdge().borderStyle() == BorderStyleDouble);
    ASSERT(m_visibleEdgeSet == AllBorderEdges);

    const Color color = firstEdge().color;

    // outer stripe
    const LayoutRectOutsets outerThirdInsets =
        doubleStripeInsets(m_edges, BorderEdge::DoubleBorderStripeOuter);
    const FloatRoundedRect outerThirdRect = m_style.getRoundedInnerBorderFor(borderRect,
        outerThirdInsets, m_includeLogicalLeftEdge, m_includeLogicalRightEdge);
    drawBleedAdjustedDRRect(context, m_bleedAvoidance, m_outer, outerThirdRect, color);

    // inner stripe
    const LayoutRectOutsets innerThirdInsets =
        doubleStripeInsets(m_edges, BorderEdge::DoubleBorderStripeInner);
    const FloatRoundedRect innerThirdRect = m_style.getRoundedInnerBorderFor(borderRect,
        innerThirdInsets, m_includeLogicalLeftEdge, m_includeLogicalRightEdge);
    context.fillDRRect(innerThirdRect, m_inner, color);
}

bool BoxBorderPainter::paintBorderFastPath(GraphicsContext& context, const LayoutRect& borderRect) const
{
    if (!m_isUniformColor || !m_isUniformStyle || !m_inner.isRenderable())
        return false;

    if (firstEdge().borderStyle() != BorderStyleSolid && firstEdge().borderStyle() != BorderStyleDouble)
        return false;

    if (m_visibleEdgeSet == AllBorderEdges) {
        if (firstEdge().borderStyle() == BorderStyleSolid) {
            if (m_isUniformWidth && !m_outer.isRounded()) {
                // 4-side, solid, uniform-width, rectangular border => one drawRect()
                drawSolidBorderRect(context, m_outer.rect(), firstEdge().width, firstEdge().color);
            } else {
                // 4-side, solid border => one drawDRRect()
                drawBleedAdjustedDRRect(context, m_bleedAvoidance, m_outer, m_inner, firstEdge().color);
            }
        } else {
            // 4-side, double border => 2x drawDRRect()
            ASSERT(firstEdge().borderStyle() == BorderStyleDouble);
            drawDoubleBorder(context, borderRect);
        }

        return true;
    }

    // This is faster than the normal complex border path only if it avoids creating transparency
    // layers (when the border is translucent).
    if (firstEdge().borderStyle() == BorderStyleSolid && !m_outer.isRounded() && m_hasAlpha) {
        ASSERT(m_visibleEdgeSet != AllBorderEdges);
        // solid, rectangular border => one drawPath()
        Path path;
        path.setWindRule(RULE_NONZERO);

        for (int i = BSTop; i <= BSLeft; ++i) {
            const BorderEdge& currEdge = m_edges[i];
            if (currEdge.shouldRender())
                path.addRect(calculateSideRect(m_outer, currEdge, i));
        }

        context.setFillColor(firstEdge().color);
        context.fillPath(path);
        return true;
    }

    return false;
}

BoxBorderPainter::BoxBorderPainter(const LayoutRect& borderRect, const ComputedStyle& style,
    BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge,
    bool includeLogicalRightEdge)
    : m_style(style)
    , m_bleedAvoidance(bleedAvoidance)
    , m_includeLogicalLeftEdge(includeLogicalLeftEdge)
    , m_includeLogicalRightEdge(includeLogicalRightEdge)
    , m_visibleEdgeCount(0)
    , m_firstVisibleEdge(0)
    , m_visibleEdgeSet(0)
    , m_isUniformStyle(true)
    , m_isUniformWidth(true)
    , m_isUniformColor(true)
    , m_isRounded(false)
    , m_hasAlpha(false)
{
    style.getBorderEdgeInfo(m_edges, includeLogicalLeftEdge, includeLogicalRightEdge);
    computeBorderProperties();

    // No need to compute the rrects if we don't have any borders to draw.
    if (!m_visibleEdgeSet)
        return;

    m_outer = m_style.getRoundedBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
    m_inner = m_style.getRoundedInnerBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);

    m_isRounded = m_outer.isRounded();
}

BoxBorderPainter::BoxBorderPainter(const ComputedStyle& style, const LayoutRect& outer,
    const LayoutRect& inner, const BorderEdge& uniformEdgeInfo)
    : m_style(style)
    , m_bleedAvoidance(BackgroundBleedNone)
    , m_includeLogicalLeftEdge(true)
    , m_includeLogicalRightEdge(true)
    , m_outer(FloatRect(outer))
    , m_inner(FloatRect(inner))
    , m_visibleEdgeCount(0)
    , m_firstVisibleEdge(0)
    , m_visibleEdgeSet(0)
    , m_isUniformStyle(true)
    , m_isUniformWidth(true)
    , m_isUniformColor(true)
    , m_isRounded(false)
    , m_hasAlpha(false)
{
    for (auto& edge : m_edges)
        edge = uniformEdgeInfo;

    computeBorderProperties();
}

void BoxBorderPainter::computeBorderProperties()
{
    for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_edges); ++i) {
        const BorderEdge& edge = m_edges[i];

        if (!edge.shouldRender()) {
            if (edge.presentButInvisible()) {
                m_isUniformWidth = false;
                m_isUniformColor = false;
            }

            continue;
        }

        ASSERT(edge.color.alpha() > 0);

        m_visibleEdgeCount++;
        m_visibleEdgeSet |= edgeFlagForSide(static_cast<BoxSide>(i));

        m_hasAlpha |= edge.color.hasAlpha();

        if (m_visibleEdgeCount == 1) {
            m_firstVisibleEdge = i;
            continue;
        }

        m_isUniformStyle &= edge.borderStyle() == m_edges[m_firstVisibleEdge].borderStyle();
        m_isUniformWidth &= edge.width == m_edges[m_firstVisibleEdge].width;
        m_isUniformColor &= edge.color == m_edges[m_firstVisibleEdge].color;
    }
}

void BoxBorderPainter::paintBorder(const PaintInfo& info, const LayoutRect& rect) const
{
    if (!m_visibleEdgeCount || m_outer.rect().isEmpty())
        return;

    GraphicsContext& graphicsContext = info.context;

    if (paintBorderFastPath(graphicsContext, rect))
        return;

    bool clipToOuterBorder = m_outer.isRounded();
    GraphicsContextStateSaver stateSaver(graphicsContext, clipToOuterBorder);
    if (clipToOuterBorder) {
        // For BackgroundBleedClip{Only,Layer}, the outer rrect clip is already applied.
        if (!bleedAvoidanceIsClipping(m_bleedAvoidance))
            graphicsContext.clipRoundedRect(m_outer);

        if (m_inner.isRenderable() && !m_inner.isEmpty())
            graphicsContext.clipOutRoundedRect(m_inner);
    }

    const ComplexBorderInfo borderInfo(*this, true);
    paintOpacityGroup(graphicsContext, borderInfo, 0, 1);
}

// In order to maximize the use of overdraw as a corner seam avoidance technique, we draw
// translucent border sides using the following algorithm:
//
//   1) cluster sides sharing the same opacity into "opacity groups" [ComplexBorderInfo]
//   2) sort groups in increasing opacity order [ComplexBorderInfo]
//   3) reverse-iterate over groups (decreasing opacity order), pushing nested transparency
//      layers with adjusted/relative opacity [paintOpacityGroup]
//   4) iterate over groups (increasing opacity order), painting actual group contents and
//      then ending their corresponding transparency layer [paintOpacityGroup]
//
// Layers are created in decreasing opacity order (top -> bottom), while actual border sides are
// drawn in increasing opacity order (bottom -> top). At each level, opacity is adjusted to acount
// for accumulated/ancestor layer alpha. Because opacity is applied via layers, the actual draw
// paint is opaque.
//
// As an example, let's consider a border with the following sides/opacities:
//
//   top:    1.0
//   right:  0.25
//   bottom: 0.5
//   left:   0.25
//
// These are grouped and sorted in ComplexBorderInfo as follows:
//
//   group[0]: { alpha: 1.0,  sides: top }
//   group[1]: { alpha: 0.5,  sides: bottom }
//   group[2]: { alpha: 0.25, sides: right, left }
//
// Applying the algorithm yields the following paint sequence:
//
//                                 // no layer needed for group 0 (alpha == 1)
//   beginLayer(0.5)               // layer for group 1
//     beginLayer(0.5)             // layer for group 2 (effective opacity: 0.5 * 0.5 == 0.25)
//       paintSides(right, left)   // paint group 2
//     endLayer
//     paintSides(bottom)          // paint group 1
//   endLayer
//   paintSides(top)               // paint group 0
//
// Note that we're always drawing using opaque paints on top of less-opaque content - hence
// we can use overdraw to mask portions of the previous sides.
//
BorderEdgeFlags BoxBorderPainter::paintOpacityGroup(GraphicsContext& context,
    const ComplexBorderInfo& borderInfo, unsigned index, float effectiveOpacity) const
{
    ASSERT(effectiveOpacity > 0 && effectiveOpacity <= 1);

    const size_t opacityGroupCount = borderInfo.opacityGroups.size();

    // For overdraw logic purposes, treat missing/transparent edges as completed.
    if (index >= opacityGroupCount)
        return ~m_visibleEdgeSet;

    // Groups are sorted in increasing opacity order, but we need to create layers in
    // decreasing opacity order - hence the reverse iteration.
    const OpacityGroup& group = borderInfo.opacityGroups[opacityGroupCount - index - 1];

    // Adjust this group's paint opacity to account for ancestor transparency layers
    // (needed in case we avoid creating a layer below).
    unsigned paintAlpha = group.alpha / effectiveOpacity;
    ASSERT(paintAlpha <= 255);

    // For the last (bottom) group, we can skip the layer even in the presence of opacity iff
    // it contains no adjecent edges (no in-group overdraw possibility).
    bool needsLayer = group.alpha != 255
        && (includesAdjacentEdges(group.edgeFlags) || (index + 1 < borderInfo.opacityGroups.size()));

    if (needsLayer) {
        const float groupOpacity = static_cast<float>(group.alpha) / 255;
        ASSERT(groupOpacity < effectiveOpacity);

        context.beginLayer(groupOpacity / effectiveOpacity);
        effectiveOpacity = groupOpacity;

        // Group opacity is applied via a layer => we draw the members using opaque paint.
        paintAlpha = 255;
    }

    // Recursion may seem unpalatable here, but
    //   a) it has an upper bound of 4
    //   b) only triggers at all when mixing border sides with different opacities
    //   c) it allows us to express the layer nesting algorithm more naturally
    BorderEdgeFlags completedEdges = paintOpacityGroup(context, borderInfo, index + 1, effectiveOpacity);

    // Paint the actual group edges with an alpha adjusted to account for ancenstor layers opacity.
    for (BoxSide side : group.sides) {
        paintSide(context, borderInfo, side, paintAlpha, completedEdges);
        completedEdges |= edgeFlagForSide(side);
    }

    if (needsLayer)
        context.endLayer();

    return completedEdges;
}

void BoxBorderPainter::paintSide(GraphicsContext& context, const ComplexBorderInfo& borderInfo,
    BoxSide side, unsigned alpha, BorderEdgeFlags completedEdges) const
{
    const BorderEdge& edge = m_edges[side];
    ASSERT(edge.shouldRender());
    const Color color(edge.color.red(), edge.color.green(), edge.color.blue(), alpha);

    FloatRect sideRect = m_outer.rect();
    const Path* path = nullptr;

    // TODO(fmalita): find a way to consolidate these without sacrificing readability.
    switch (side) {
    case BSTop: {
        bool usePath = m_isRounded && (borderStyleHasInnerDetail(edge.borderStyle())
            || borderWillArcInnerEdge(m_inner.getRadii().topLeft(), m_inner.getRadii().topRight()));
        if (usePath)
            path = &borderInfo.roundedBorderPath;
        else
            sideRect.setHeight(edge.width);

        paintOneBorderSide(context, sideRect, BSTop, BSLeft, BSRight, path, borderInfo.antiAlias,
            color, completedEdges);
        break;
    }
    case BSBottom: {
        bool usePath = m_isRounded && (borderStyleHasInnerDetail(edge.borderStyle())
            || borderWillArcInnerEdge(m_inner.getRadii().bottomLeft(), m_inner.getRadii().bottomRight()));
        if (usePath)
            path = &borderInfo.roundedBorderPath;
        else
            sideRect.shiftYEdgeTo(sideRect.maxY() - edge.width);

        paintOneBorderSide(context, sideRect, BSBottom, BSLeft, BSRight, path, borderInfo.antiAlias,
            color, completedEdges);
        break;
    }
    case BSLeft: {
        bool usePath = m_isRounded && (borderStyleHasInnerDetail(edge.borderStyle())
            || borderWillArcInnerEdge(m_inner.getRadii().bottomLeft(), m_inner.getRadii().topLeft()));
        if (usePath)
            path = &borderInfo.roundedBorderPath;
        else
            sideRect.setWidth(edge.width);

        paintOneBorderSide(context, sideRect, BSLeft, BSTop, BSBottom, path, borderInfo.antiAlias,
            color, completedEdges);
        break;
    }
    case BSRight: {
        bool usePath = m_isRounded && (borderStyleHasInnerDetail(edge.borderStyle())
            || borderWillArcInnerEdge(m_inner.getRadii().bottomRight(), m_inner.getRadii().topRight()));
        if (usePath)
            path = &borderInfo.roundedBorderPath;
        else
            sideRect.shiftXEdgeTo(sideRect.maxX() - edge.width);

        paintOneBorderSide(context, sideRect, BSRight, BSTop, BSBottom, path, borderInfo.antiAlias,
            color, completedEdges);
        break;
    }
    default:
        ASSERT_NOT_REACHED();
    }
}

BoxBorderPainter::MiterType BoxBorderPainter::computeMiter(BoxSide side, BoxSide adjacentSide,
    BorderEdgeFlags completedEdges, bool antialias) const
{
    const BorderEdge& adjacentEdge = m_edges[adjacentSide];

    // No miters for missing edges.
    if (!adjacentEdge.isPresent)
        return NoMiter;

    // The adjacent edge will overdraw this corner, resulting in a correct miter.
    if (willOverdraw(adjacentSide, adjacentEdge.borderStyle(), completedEdges))
        return NoMiter;

    // Color transitions require miters. Use miters compatible with the AA drawing mode to avoid
    // introducing extra clips.
    if (!colorsMatchAtCorner(side, adjacentSide, m_edges))
        return antialias ? SoftMiter : HardMiter;

    // Non-anti-aliased miters ensure correct same-color seaming when required by style.
    if (borderStylesRequireMiter(side, adjacentSide, m_edges[side].borderStyle(), adjacentEdge.borderStyle()))
        return HardMiter;

    // Overdraw the adjacent edge when the colors match and we have no style restrictions.
    return NoMiter;
}

bool BoxBorderPainter::mitersRequireClipping(MiterType miter1, MiterType miter2, EBorderStyle style,
    bool antialias)
{
    // Clipping is required if any of the present miters doesn't match the current AA mode.
    bool shouldClip = antialias
        ? miter1 == HardMiter || miter2 == HardMiter
        : miter1 == SoftMiter || miter2 == SoftMiter;

    // Some styles require clipping for any type of miter.
    shouldClip = shouldClip
        || ((miter1 != NoMiter || miter2 != NoMiter) && styleRequiresClipPolygon(style));

    return shouldClip;
}

void BoxBorderPainter::paintOneBorderSide(GraphicsContext& graphicsContext,
    const FloatRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2,
    const Path* path, bool antialias, Color color, BorderEdgeFlags completedEdges) const
{
    const BorderEdge& edgeToRender = m_edges[side];
    ASSERT(edgeToRender.width);
    const BorderEdge& adjacentEdge1 = m_edges[adjacentSide1];
    const BorderEdge& adjacentEdge2 = m_edges[adjacentSide2];

    if (path) {
        MiterType miter1 = colorsMatchAtCorner(side, adjacentSide1, m_edges) ? HardMiter : SoftMiter;
        MiterType miter2 = colorsMatchAtCorner(side, adjacentSide2, m_edges) ? HardMiter : SoftMiter;

        GraphicsContextStateSaver stateSaver(graphicsContext);
        if (m_inner.isRenderable())
            clipBorderSidePolygon(graphicsContext, side, miter1, miter2);
        else
            clipBorderSideForComplexInnerPath(graphicsContext, side);
        float thickness = std::max(std::max(edgeToRender.width, adjacentEdge1.width), adjacentEdge2.width);
        drawBoxSideFromPath(graphicsContext, LayoutRect(m_outer.rect()), *path, edgeToRender.width,
            thickness, side, color, edgeToRender.borderStyle());
    } else {
        MiterType miter1 = computeMiter(side, adjacentSide1, completedEdges, antialias);
        MiterType miter2 = computeMiter(side, adjacentSide2, completedEdges, antialias);
        bool shouldClip = mitersRequireClipping(miter1, miter2, edgeToRender.borderStyle(), antialias);

        GraphicsContextStateSaver clipStateSaver(graphicsContext, shouldClip);
        if (shouldClip) {
            clipBorderSidePolygon(graphicsContext, side, miter1, miter2);

            // Miters are applied via clipping, no need to draw them.
            miter1 = miter2 = NoMiter;
        }

        ObjectPainter::drawLineForBoxSide(graphicsContext, sideRect.x(), sideRect.y(),
            sideRect.maxX(), sideRect.maxY(), side, color, edgeToRender.borderStyle(),
            miter1 != NoMiter ? adjacentEdge1.width : 0, miter2 != NoMiter ? adjacentEdge2.width : 0,
            antialias);
    }
}

void BoxBorderPainter::drawBoxSideFromPath(GraphicsContext& graphicsContext,
    const LayoutRect& borderRect, const Path& borderPath, float thickness, float drawThickness,
    BoxSide side, Color color, EBorderStyle borderStyle) const
{
    if (thickness <= 0)
        return;

    if (borderStyle == BorderStyleDouble && thickness < 3)
        borderStyle = BorderStyleSolid;

    switch (borderStyle) {
    case BorderStyleNone:
    case BorderStyleHidden:
        return;
    case BorderStyleDotted:
    case BorderStyleDashed: {
        graphicsContext.setStrokeColor(color);

        // The stroke is doubled here because the provided path is the
        // outside edge of the border so half the stroke is clipped off.
        // The extra multiplier is so that the clipping mask can antialias
        // the edges to prevent jaggies.
        graphicsContext.setStrokeThickness(drawThickness * 2 * 1.1f);
        graphicsContext.setStrokeStyle(borderStyle == BorderStyleDashed ? DashedStroke : DottedStroke);

        // If the number of dashes that fit in the path is odd and non-integral then we
        // will have an awkwardly-sized dash at the end of the path. To try to avoid that
        // here, we simply make the whitespace dashes ever so slightly bigger.
        // FIXME: This could be even better if we tried to manipulate the dash offset
        // and possibly the gapLength to get the corners dash-symmetrical.
        float dashLength = thickness * ((borderStyle == BorderStyleDashed) ? 3.0f : 1.0f);
        float gapLength = dashLength;
        float numberOfDashes = borderPath.length() / dashLength;
        // Don't try to show dashes if we have less than 2 dashes + 2 gaps.
        // FIXME: should do this test per side.
        if (numberOfDashes >= 4) {
            bool evenNumberOfFullDashes = !((int)numberOfDashes % 2);
            bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes);
            if (!evenNumberOfFullDashes && !integralNumberOfDashes) {
                float numberOfGaps = numberOfDashes / 2;
                gapLength += (dashLength  / numberOfGaps);
            }

            DashArray lineDash;
            lineDash.append(dashLength);
            lineDash.append(gapLength);
            graphicsContext.setLineDash(lineDash, dashLength);
        }

        // FIXME: stroking the border path causes issues with tight corners:
        // https://bugs.webkit.org/show_bug.cgi?id=58711
        // Also, to get the best appearance we should stroke a path between the two borders.
        graphicsContext.strokePath(borderPath);
        return;
    }
    case BorderStyleDouble: {
        // Draw inner border line
        {
            GraphicsContextStateSaver stateSaver(graphicsContext);
            const LayoutRectOutsets innerInsets = doubleStripeInsets(m_edges, BorderEdge::DoubleBorderStripeInner);
            FloatRoundedRect innerClip = m_style.getRoundedInnerBorderFor(borderRect, innerInsets,
                m_includeLogicalLeftEdge, m_includeLogicalRightEdge);

            graphicsContext.clipRoundedRect(innerClip);
            drawBoxSideFromPath(graphicsContext, borderRect, borderPath, thickness, drawThickness,
                side, color, BorderStyleSolid);
        }

        // Draw outer border line
        {
            GraphicsContextStateSaver stateSaver(graphicsContext);
            LayoutRect outerRect = borderRect;
            LayoutRectOutsets outerInsets = doubleStripeInsets(m_edges, BorderEdge::DoubleBorderStripeOuter);

            if (bleedAvoidanceIsClipping(m_bleedAvoidance)) {
                outerRect.inflate(1);
                outerInsets.setTop(outerInsets.top() - 1);
                outerInsets.setRight(outerInsets.right() - 1);
                outerInsets.setBottom(outerInsets.bottom() - 1);
                outerInsets.setLeft(outerInsets.left() - 1);
            }

            FloatRoundedRect outerClip = m_style.getRoundedInnerBorderFor(outerRect, outerInsets,
                m_includeLogicalLeftEdge, m_includeLogicalRightEdge);
            graphicsContext.clipOutRoundedRect(outerClip);
            drawBoxSideFromPath(graphicsContext, borderRect, borderPath, thickness, drawThickness,
                side, color, BorderStyleSolid);
        }
        return;
    }
    case BorderStyleRidge:
    case BorderStyleGroove:
    {
        EBorderStyle s1;
        EBorderStyle s2;
        if (borderStyle == BorderStyleGroove) {
            s1 = BorderStyleInset;
            s2 = BorderStyleOutset;
        } else {
            s1 = BorderStyleOutset;
            s2 = BorderStyleInset;
        }

        // Paint full border
        drawBoxSideFromPath(graphicsContext, borderRect, borderPath, thickness, drawThickness,
            side, color, s1);

        // Paint inner only
        GraphicsContextStateSaver stateSaver(graphicsContext);
        LayoutUnit topWidth(m_edges[BSTop].usedWidth() / 2);
        LayoutUnit bottomWidth(m_edges[BSBottom].usedWidth() / 2);
        LayoutUnit leftWidth(m_edges[BSLeft].usedWidth() / 2);
        LayoutUnit rightWidth(m_edges[BSRight].usedWidth() / 2);

        FloatRoundedRect clipRect = m_style.getRoundedInnerBorderFor(borderRect,
            LayoutRectOutsets(-topWidth, -rightWidth, -bottomWidth, -leftWidth),
            m_includeLogicalLeftEdge, m_includeLogicalRightEdge);

        graphicsContext.clipRoundedRect(clipRect);
        drawBoxSideFromPath(graphicsContext, borderRect, borderPath, thickness, drawThickness,
            side, color, s2);
        return;
    }
    case BorderStyleInset:
        if (side == BSTop || side == BSLeft)
            color = color.dark();
        break;
    case BorderStyleOutset:
        if (side == BSBottom || side == BSRight)
            color = color.dark();
        break;
    default:
        break;
    }

    graphicsContext.setStrokeStyle(NoStroke);
    graphicsContext.setFillColor(color);
    graphicsContext.drawRect(pixelSnappedIntRect(borderRect));
}

void BoxBorderPainter::clipBorderSideForComplexInnerPath(GraphicsContext& graphicsContext,
    BoxSide side) const
{
    graphicsContext.clip(calculateSideRectIncludingInner(m_outer, m_edges, side));
    FloatRoundedRect adjustedInnerRect = calculateAdjustedInnerBorder(m_inner, side);
    if (!adjustedInnerRect.isEmpty())
        graphicsContext.clipOutRoundedRect(adjustedInnerRect);
}

void BoxBorderPainter::clipBorderSidePolygon(GraphicsContext& graphicsContext, BoxSide side,
    MiterType firstMiter, MiterType secondMiter) const
{
    ASSERT(firstMiter != NoMiter || secondMiter != NoMiter);

    FloatPoint quad[4];

    const LayoutRect outerRect(m_outer.rect());
    const LayoutRect innerRect(m_inner.rect());

    // For each side, create a quad that encompasses all parts of that side that may draw,
    // including areas inside the innerBorder.
    //
    //         0----------------3
    //       0  \              /  0
    //       |\  1----------- 2  /|
    //       | 1                1 |
    //       | |                | |
    //       | |                | |
    //       | 2                2 |
    //       |/  1------------2  \|
    //       3  /              \  3
    //         0----------------3
    //
    switch (side) {
    case BSTop:
        quad[0] = FloatPoint(outerRect.minXMinYCorner());
        quad[1] = FloatPoint(innerRect.minXMinYCorner());
        quad[2] = FloatPoint(innerRect.maxXMinYCorner());
        quad[3] = FloatPoint(outerRect.maxXMinYCorner());

        if (!m_inner.getRadii().topLeft().isZero()) {
            findIntersection(quad[0], quad[1],
                FloatPoint(
                    quad[1].x() + m_inner.getRadii().topLeft().width(),
                    quad[1].y()),
                FloatPoint(
                    quad[1].x(),
                    quad[1].y() + m_inner.getRadii().topLeft().height()),
                quad[1]);
        }

        if (!m_inner.getRadii().topRight().isZero()) {
            findIntersection(quad[3], quad[2],
                FloatPoint(
                    quad[2].x() - m_inner.getRadii().topRight().width(),
                    quad[2].y()),
                FloatPoint(
                    quad[2].x(),
                    quad[2].y() + m_inner.getRadii().topRight().height()),
                quad[2]);
        }
        break;

    case BSLeft:
        quad[0] = FloatPoint(outerRect.minXMinYCorner());
        quad[1] = FloatPoint(innerRect.minXMinYCorner());
        quad[2] = FloatPoint(innerRect.minXMaxYCorner());
        quad[3] = FloatPoint(outerRect.minXMaxYCorner());

        if (!m_inner.getRadii().topLeft().isZero()) {
            findIntersection(quad[0], quad[1],
                FloatPoint(
                    quad[1].x() + m_inner.getRadii().topLeft().width(),
                    quad[1].y()),
                FloatPoint(
                    quad[1].x(),
                    quad[1].y() + m_inner.getRadii().topLeft().height()),
                quad[1]);
        }

        if (!m_inner.getRadii().bottomLeft().isZero()) {
            findIntersection(quad[3], quad[2],
                FloatPoint(
                    quad[2].x() + m_inner.getRadii().bottomLeft().width(),
                    quad[2].y()),
                FloatPoint(
                    quad[2].x(),
                    quad[2].y() - m_inner.getRadii().bottomLeft().height()),
                quad[2]);
        }
        break;

    case BSBottom:
        quad[0] = FloatPoint(outerRect.minXMaxYCorner());
        quad[1] = FloatPoint(innerRect.minXMaxYCorner());
        quad[2] = FloatPoint(innerRect.maxXMaxYCorner());
        quad[3] = FloatPoint(outerRect.maxXMaxYCorner());

        if (!m_inner.getRadii().bottomLeft().isZero()) {
            findIntersection(quad[0], quad[1],
                FloatPoint(
                    quad[1].x() + m_inner.getRadii().bottomLeft().width(),
                    quad[1].y()),
                FloatPoint(
                    quad[1].x(),
                    quad[1].y() - m_inner.getRadii().bottomLeft().height()),
                quad[1]);
        }

        if (!m_inner.getRadii().bottomRight().isZero()) {
            findIntersection(quad[3], quad[2],
                FloatPoint(
                    quad[2].x() - m_inner.getRadii().bottomRight().width(),
                    quad[2].y()),
                FloatPoint(
                    quad[2].x(),
                    quad[2].y() - m_inner.getRadii().bottomRight().height()),
                quad[2]);
        }
        break;

    case BSRight:
        quad[0] = FloatPoint(outerRect.maxXMinYCorner());
        quad[1] = FloatPoint(innerRect.maxXMinYCorner());
        quad[2] = FloatPoint(innerRect.maxXMaxYCorner());
        quad[3] = FloatPoint(outerRect.maxXMaxYCorner());

        if (!m_inner.getRadii().topRight().isZero()) {
            findIntersection(quad[0], quad[1],
                FloatPoint(
                    quad[1].x() - m_inner.getRadii().topRight().width(),
                    quad[1].y()),
                FloatPoint(
                    quad[1].x(),
                    quad[1].y() + m_inner.getRadii().topRight().height()),
                quad[1]);
        }

        if (!m_inner.getRadii().bottomRight().isZero()) {
            findIntersection(quad[3], quad[2],
                FloatPoint(
                    quad[2].x() - m_inner.getRadii().bottomRight().width(),
                    quad[2].y()),
                FloatPoint(
                    quad[2].x(),
                    quad[2].y() - m_inner.getRadii().bottomRight().height()),
                quad[2]);
        }
        break;
    }

    if (firstMiter == secondMiter) {
        graphicsContext.clipPolygon(4, quad, firstMiter == SoftMiter);
        return;
    }

    // If antialiasing settings for the first edge and second edge is different,
    // they have to be addressed separately. We do this by breaking the quad into
    // two parallelograms, made by moving quad[1] and quad[2].
    float ax = quad[1].x() - quad[0].x();
    float ay = quad[1].y() - quad[0].y();
    float bx = quad[2].x() - quad[1].x();
    float by = quad[2].y() - quad[1].y();
    float cx = quad[3].x() - quad[2].x();
    float cy = quad[3].y() - quad[2].y();

    const static float kEpsilon = 1e-2f;
    float r1, r2;
    if (fabsf(bx) < kEpsilon && fabsf(by) < kEpsilon) {
        // The quad was actually a triangle.
        r1 = r2 = 1.0f;
    } else {
        // Extend parallelogram a bit to hide calculation error
        const static float kExtendFill = 1e-2f;

        r1 = (-ax * by + ay * bx) / (cx * by - cy * bx) + kExtendFill;
        r2 = (-cx * by + cy * bx) / (ax * by - ay * bx) + kExtendFill;
    }

    if (firstMiter != NoMiter) {
        FloatPoint firstQuad[4];
        firstQuad[0] = quad[0];
        firstQuad[1] = quad[1];
        firstQuad[2] = FloatPoint(quad[3].x() + r2 * ax, quad[3].y() + r2 * ay);
        firstQuad[3] = quad[3];
        graphicsContext.clipPolygon(4, firstQuad, firstMiter == SoftMiter);
    }

    if (secondMiter != NoMiter) {
        FloatPoint secondQuad[4];
        secondQuad[0] = quad[0];
        secondQuad[1] = FloatPoint(quad[0].x() - r1 * cx, quad[0].y() - r1 * cy);
        secondQuad[2] = quad[2];
        secondQuad[3] = quad[3];
        graphicsContext.clipPolygon(4, secondQuad, secondMiter == SoftMiter);
    }
}

} // namespace blink


text:
package com.frameworkset.common.tag.html;

import java.io.IOException;
import java.util.Map;

import javax.servlet.jsp.JspException;

import com.frameworkset.common.tag.BaseCellTag;
import com.frameworkset.platform.cms.documentmanager.bean.DocExtValue;

/**
 *
ExtendLableTag.java

 *
 Description:

 *
 bboss workgroup

 *
 Copyright (c) 2005-2013

 *
 * @Date 2014年2月10日
 * @author biaoping.yin
 * @version 1.0
 */
public class ExtendLableTag extends BaseCellTag{
	protected String field = null;

	protected DocExtValue docExtValue;

	protected Map<String,DocExtValue> extenddatas;
	public int doStartTag() throws JspException {
		super.doStartTag();
		DocExtends docExtends = (DocExtends) this.findAncestorWithClass(this, DocExtends.class);
		if(docExtends == null)
		{
			this.doaloneTag();
		}
		else
		{
			doInnerTag(docExtends);
		}

		String outStr =getOut(this.docExtValue);

		try {

			out.print(outStr);

		}
		catch(Exception e)
		{
			try {
				out.print(outStr);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return this.SKIP_BODY;

	}

	private void doaloneTag()
	{
		if(super.dataSet != null)
		{
			if(this.getColName() != null)
			{
				extenddatas = dataSet.getMap(this.getColName());
			}
			else
			{
				extenddatas = dataSet.getMap("docExtField");
			}

		}
		if(extenddatas != null)
		{
			DocExtValue value = extenddatas.get(field);
			docExtValue = value;
		}

	}

	private void doInnerTag(DocExtends docExtends)
	{
		this.docExtValue = docExtends.currentdocExtValue.getValue();
		this.extenddatas = docExtends.extenddatas;

	}

	protected String getOut(DocExtValue value)
	{

		if(value != null)
		{
			return value.getLabel();
		}

		return "";
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public int doEndTag() throws JspException
	{
		int ret = super.doEndTag();

		return ret;
	}

	@Override
	public void doFinally() {
		field = null;

		this.extenddatas = null;
		docExtValue = null;
		super.doFinally();
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link href="../../JavaScript-ConsoleStyle/JavaScript-ConsoleStyle.css" rel="stylesheet"/>
    <title>English Digit</title>

    Enter number:
    <input type="text" id="number"/>

    <button id="check">Check</button>


text:
from .state import State

from ..messages.request_vote import RequestVoteResponseMessage

class Voter(State):

    def __init__(self):
        self._last_vote = None

    def on_vote_request(self, message):
        if(self._last_vote is None and
           message.data["lastLogIndex"] >= self._server._lastLogIndex):
            self._last_vote = message.sender
            self._send_vote_response_message(message)
        else:
            self._send_vote_response_message(message, yes=False)

        return self, None

    def _send_vote_response_message(self, msg, yes=True):
        voteResponse = RequestVoteResponseMessage(
            self._server._name,
            msg.sender,
            msg.term,
            {"response": yes})
        self._server.send_message_response(voteResponse)


text:
FactoryGirl.define do
  # Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them.
  #
  # Example adding this to your spec_helper will load these Factories for use:
  # require 'solidus_elastic_product/factories'

  # Creating the state directly causes problems as it's attempt to initialize
  # the product will cause it to reset itself. So instead extending product to
  # be created with a pre-defined SB state
  #
  # This really only make sense when calling the create factory.
  factory :product_with_elastic_state, parent: :product do
    transient do
      json nil
      locked_for_serialization_at nil
      uploaded false
      locked_for_upload_at nil
    end

    after(:create) do |product, config|
      state = product.elastic_state
      state.update_attributes! json: config.json,
        locked_for_serialization_at: config.locked_for_serialization_at,
        uploaded: config.uploaded, locked_for_upload_at: config.locked_for_upload_at
    end
  end

  factory :elastic_state, class: "Solidus::ElasticProduct::State" do
    product_id 0 # use dummy value to avoid the above problem
    json nil
    locked_for_serialization_at nil
    uploaded false
    locked_for_upload_at nil
  end

end


text:
package eu.kingconquest.conquest.event;

import eu.kingconquest.conquest.core.Objective;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

public class CaptureNeutralEvent extends Event{
    private static final HandlerList handlers = new HandlerList();
	private final Objective objective;
    private Player player;

    public CaptureNeutralEvent(Player player, Objective objective) {
    	this.objective = objective;
    	this.player = player;
    }

    public Player getPlayer(){
    	return player;
    }

    public Objective getObjective(){
		return objective;
    }

    @Override
    public HandlerList getHandlers() {
        return handlers;
    }
    public static HandlerList getHandlerList() {
        return handlers;
    }
}


text:
/*
	This is part of pyahocorasick Python module.

	AutomatonItemsIter const, struct & methods declarations.
	This class implements iterator walk over trie, that returns
	words and associated values. Object of this class is
	returned by 'keys'/'values'/'items' methods of Automaton class.

	Author    : Wojciech Mu³a, wojciech_mula@poczta.onet.pl
	WWW       : http://0x80.pl/proj/pyahocorasick/
	License   : 3-clauses BSD (see LICENSE)
	Date      : $Date$

	$Id$
*/
#ifndef ahocorasick_AutomatonItemsIter_h_included
#define ahocorasick_AutomatonItemsIter_h_included

#include "common.h"
#include "Automaton.h"

typedef enum {
	ITER_KEYS,
	ITER_VALUES,
	ITER_ITEMS
} ItemsType;

typedef enum {
	MATCH_EXACT_LENGTH,
	MATCH_AT_MOST_PREFIX,
	MATCH_AT_LEAST_PREFIX
} PatternMatchType;

typedef struct AutomatonItemsIter {
	PyObject_HEAD

	Automaton*	automaton;
	int			version;		///< automaton version
	TrieNode* 	state;			///< current automaton node
	List		stack;			///< stack
	ItemsType	type;			///< type of iterator (KEYS/VALUES/ITEMS)
	TRIE_LETTER_TYPE* buffer;	///< buffer to construct key representation

	size_t pattern_length;
	TRIE_LETTER_TYPE* pattern;	///< pattern
	bool use_wildcard;
	TRIE_LETTER_TYPE wildcard;	///< wildcard char
	PatternMatchType matchtype;	///< how pattern have to be handled
} AutomatonItemsIter;

/* new() */
static PyObject*
automaton_items_iter_new(
	Automaton* automaton,
	const TRIE_LETTER_TYPE* word,
	const ssize_t wordlen,

	const bool use_wildcard,
	const TRIE_LETTER_TYPE wildcard,

	const PatternMatchType	matchtype
);

#endif


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
        <item name="android:textColor">@color/primary_text</item>
        <item name="android:textColorSecondary">@color/secondary_text</item>
        <item name="android:divider">@color/divider</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>


text:
package com.tonilopezmr.login;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.login.widget.LoginButton;
import com.google.android.gms.common.SignInButton;
import com.squareup.picasso.Picasso;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import io.fabric.sdk.android.Fabric;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends SignInActivity {

    // Note: Your consumer key and secret should be obfuscated in your source code before shipping.
    private static final String TWITTER_KEY = "VS8IpmwlBd7VOWqsmmrAtX6eS";
    private static final String TWITTER_SECRET = "bIojcMjUiH30qruY9fUW5sPQkYuZeKAb79gsTSXebHujN82m8j";

    private Button signOutButton;
    private ImageView imageView;
    private TextView userName;
    private TextView userEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig));
        setContentView(R.layout.activity_login);

        imageView = (ImageView)findViewById(R.id.user_image);
        userName = (TextView)findViewById(R.id.user_name);
        userEmail = (TextView)findViewById(R.id.user_email);

        signOutButton = (Button)findViewById(R.id.sign_out_button);
        signOutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signOut();
            }
        });

        init();
    }

    @Override
    public void userIsLogged() {
        signInGoogleButton.setEnabled(false);
        facebookLoginButton.setEnabled(false);
        twitterLoginButton.setEnabled(false);
        signOutButton.setEnabled(true);
        connect();
    }

    @Override
    public void errorOnConnect() {

    }

    @Override
    public void userIsntLogged() {
        facebookLoginButton.setEnabled(true);
        twitterLoginButton.setEnabled(true);
        signInGoogleButton.setEnabled(true);
        signOutButton.setEnabled(false);
    }

    @Override
    public void onConnectionComplete(UserProfile person) {
        if (person != null){
            Toast.makeText(getApplicationContext(), "User: "+ person.getId(), Toast.LENGTH_LONG).show();
            Picasso.with(getApplicationContext()).load(person.getImageUri()).into(imageView);
            userName.setText(person.getName());
            userEmail.setText(person.getEmail());
            facebookLoginButton.setEnabled(false);
            twitterLoginButton.setEnabled(false);
            signInGoogleButton.setEnabled(false);
            signOutButton.setEnabled(true);
        }
    }

    private void signOut(){
        disconnect();
        twitterLoginButton.setEnabled(true);
        facebookLoginButton.setEnabled(true);
        signInGoogleButton.setEnabled(true);
        signOutButton.setEnabled(false);
    }

    @Override
    public LoginButton getLoginFacebookButton() {
        return (LoginButton) findViewById(R.id.login_button);
    }

    @Override
    public TwitterLoginButton getLoginTwitterButton() {
        return (TwitterLoginButton) findViewById(R.id.twitter_login_button);
    }

    @Override
    public SignInButton getLoginGoogleButton() {
        return (SignInButton)findViewById(R.id.sign_in_button);
    }

    /**
     * Call this method inside onCreate once to get your hash key
     */
    public void printKeyHash() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo("com.tonilopezmr.login", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.e("SHA: ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}


text:
module tetra.common{
    export enum MessageType {
        Error = 0,
        Warning = 1,
        Success = 2,
        Info = 3
    }

    export class LogMessage {
        type: MessageType;
        message: string;

        constructor(type: MessageType, message: string) {
            this.type = type;
            this.message = message;
        }
    }

    export class MessageLog {
        messages: LogMessage[];

        constructor() {
            this.messages = [];
        }

        get errors(): LogMessage[] {
            return this.getMessagesByType(MessageType.Error);
        }

        get successes(): LogMessage[] {
            return this.getMessagesByType(MessageType.Success);
        }

        get hasErrors(): boolean {
            return this.errors.length > 0;
        }

        get hasSuccesses(): boolean {
            return this.successes.length > 0;
        }

        addSuccess(message: string): void {
            var logMessage = this.addMessage(MessageType.Success, message);
        }

        addErrorResponse(response: any): void {
            if (!response) {
                return;
            }
            if (response.errors) {
                response.errors.forEach((msg: string) => this.addError(msg));
            } else {
                this.addError(response.message);
            }
        }

        addError(message: string): void {
            this.addMessage(MessageType.Error, message);
        }

        addMessage(type: MessageType, message: string): LogMessage {
            var logMessage = new LogMessage(type, message);
            this.messages.push(logMessage);
            return logMessage;
        }

        clearAll(): void {
            this.messages = [];
        }

        private getMessagesByType(type: MessageType): LogMessage[] {
            return Enumerable.from(this.messages)
                .where((msg: LogMessage) => msg.type === type)
                .toArray();
        }
    }
}


text:
<?php

namespace console;

class Version{

	public $description = 'Exibe a versão do OnService';
	public $order = 0;

	function __construct(){}

	public function index(){
		return OnServiceVersion;
	}

}


text:
package org.apache.maven.cli.logging.impl;

import org.apache.maven.cli.logging.BaseSlf4jConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Configuration for slf4j-logback.
 *
 * @author Hervé Boutemy
 * @since 3.1.0
 */
public class LogbackConfiguration extends BaseSlf4jConfiguration {
    @Override
    public void setRootLoggerLevel(Level level) {
        ch.qos.logback.classic.Level value;
        switch (level) {
            case DEBUG:
                value = ch.qos.logback.classic.Level.DEBUG;
                break;

            case INFO:
                value = ch.qos.logback.classic.Level.INFO;
                break;

            default:
                value = ch.qos.logback.classic.Level.ERROR;
                break;
        }
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(value);
    }

    @Override
    public void activate() {
        // no op
    }
}


text:
<title>
Computer Science Final Project-Evan
</title>

    1v1 Battle Arena

<body id="myBody" style=" background-size: cover; background-image: url('giphy.gif'); background-repeat : repeat-x; "

onload="{document.myEfired= 0}" onkeydown="{
//alert(String.fromCharCode(event.keyCode))

//document.myEfired= 0

myChar = String.fromCharCode(event.keyCode)

if((String.fromCharCode(event.keyCode)) == 'D'){
    document.getElementById('myA').style.left = parseInt(document.getElementById('myA').style.left) + 20 + 'px'
    if(document.myEfired==0){
	document.getElementById('myC').style.left = parseInt(document.getElementById('myA').style.left) + 40 + 'px'
    }

if (parseInt(document.getElementById('myA').style.left) >= 1200 ){
            document.getElementById('myA').style.left = '1200px'
			document.getElementById('myC').style.left = '1240px'

	}

}

 if((String.fromCharCode(event.keyCode)) == 'S'){
    document.getElementById('myA').style.top=parseInt(document.getElementById('myA').style.top) + 20 + 'px'
    if(document.myEfired==0){
	document.getElementById('myC').style.top = document.getElementById('myA').style.top
    }

	if (parseInt(document.getElementById('myA').style.top) >= 725 ){
            document.getElementById('myA').style.top = '715px'
			document.getElementById('myC').style.top = '715px'
	}

}

if((String.fromCharCode(event.keyCode)) == 'A'){
    document.getElementById('myA').style.left=parseInt(document.getElementById('myA').style.left) + -20 + 'px'
    if(document.myEfired==0){
	document.getElementById('myC').style.left = parseInt(document.getElementById('myA').style.left) + 40 + 'px'
    }

	if (parseInt(document.getElementById('myA').style.left) <= 30 ){
            document.getElementById('myA').style.left = '30px'
			document.getElementById('myC').style.left = '70px'
	}

}

if((String.fromCharCode(event.keyCode)) == 'W'){
    document.getElementById('myA').style.top=parseInt(document.getElementById('myA').style.top) + -20 + 'px'
    if(document.myEfired==0){
	document.getElementById('myC').style.top = document.getElementById('myA').style.top
    }

	if (parseInt(document.getElementById('myA').style.top) <= 100 ){
            document.getElementById('myA').style.top = '100px'
			document.getElementById('myC').style.top = '100px'
	}

}

	if((String.fromCharCode(event.keyCode)) == 'E'){

	document.getElementById('myOut01').innerHTML =  'You fired!'

    document.getElementById('myC').style.left=parseInt(document.getElementById('myC').style.left) + 80 + 'px'
    //clearInterval(myInt)

	if (document.myEfired == 0){

    document.myInt = setInterval(function(){
	   document.getElementById('myD').style.left = document.getElementById('myB').style.left
	   document.getElementById('myD').style.top = document.getElementById('myB').style.top
       document.getElementById('myC').style.left=parseInt(document.getElementById('myC').style.left) + 10 + 'px'
	   myCheck()
	   if ( parseInt(document.getElementById('myC').style.left ) >= 1240  ) {
          document.getElementById('myC').style.left = parseInt(document.getElementById('myA').style.left) + 40 + 'px'

		  clearInterval(document.myInt)

		  document.myEfired= 0

      }

   },20)
   }

   document.myEfired= 1
}

myChar = String.fromCharCode(event.keyCode)

if((String.fromCharCode(event.keyCode)) == 'f'){
    document.getElementById('myB').style.left=parseInt(document.getElementById('myB').style.left) + 20 + 'px'
    if(document.myEfired==0){
    document.getElementById('myD').style.left = document.getElementById('myB').style.left
    }

if (parseInt(document.getElementById('myB').style.left) >= 1200 ){
            document.getElementById('myB').style.left = '1200px'
			document.getElementById('myD').style.left = '1200px'
	}

}
 if((String.fromCharCode(event.keyCode)) == 'e'){
    document.getElementById('myB').style.top=parseInt(document.getElementById('myB').style.top) + 20 + 'px'
    if(document.myEfired==0){
	document.getElementById('myD').style.top = document.getElementById('myB').style.top
    }

if (parseInt(document.getElementById('myB').style.top) >= 725 ){
            document.getElementById('myB').style.top = '715px'
			document.getElementById('myD').style.top = '715px'
	}

}
if((String.fromCharCode(event.keyCode)) == 'd'){
    document.getElementById('myB').style.left=parseInt(document.getElementById('myB').style.left) + -20 + 'px'
    if(document.myEfired==0){
    document.getElementById('myD').style.left = document.getElementById('myB').style.left
    }

if (parseInt(document.getElementById('myB').style.left) <= 25 ){
             document.getElementById('myB').style.left = '25px'
			document.getElementById('myD').style.left = '25px'
	}

}

if((String.fromCharCode(event.keyCode)) == 'h'){
    document.getElementById('myB').style.top=parseInt(document.getElementById('myB').style.top) + -20 + 'px'
if(document.myEfired==0){
    document.getElementById('myD').style.top = document.getElementById('myB').style.top
    }

if (parseInt(document.getElementById('myB').style.top) <= 105 ){
            document.getElementById('myB').style.top = '105px'
			document.getElementById('myD').style.top = '105px'
	}

}

if((String.fromCharCode(event.keyCode)) == 'g'){
     if (document.myEfired == 0){

    document.getElementById('myD').style.left=parseInt(document.getElementById('myD').style.left) + -80 + 'px'
   //clearInterval(myInt)
    document.myInt = setInterval(function(){

	   document.getElementById('myC').style.left = parseInt(document.getElementById('myA').style.left) + 40 + 'px'
	   document.getElementById('myC').style.top = parseInt(document.getElementById('myA').style.top)
       document.getElementById('myD').style.left=parseInt(document.getElementById('myD').style.left) + -10 + 'px'
	   myCheck()
      if ( parseInt(document.getElementById('myD').style.left ) <= -10  ) {
          document.getElementById('myD').style.left = document.getElementById('myB').style.left
		  clearInterval(document.myInt)
		  document.myEfired= 0
      }

   },20)
   }
   document.myEfired= 1
}

// ***********************  Done keypress now collisions     ****************************************  */

myCheck()

}">

...

<input type="number" id="player1HP" value="3" size="5px" readonly=""> <input type="number" id="player2HP" value="3" size="5px" readonly="">

    Player 1 health bar              Player 2 health bar


text:
/*
 * Do not modify this file. This file is generated from the glacier-2012-06-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.Glacier.Model
{
    /// <summary>
    /// The Amazon Glacier response to your request.
    /// </summary>
    public partial class InitiateMultipartUploadResponse : AmazonWebServiceResponse
    {
        private string _location;
        private string _uploadId;

        /// <summary>
        /// Gets and sets the property Location.
        /// <para>
        /// The relative URI path of the multipart upload ID Amazon Glacier created.
        /// </para>
        /// </summary>
        public string Location
        {
            get { return this._location; }
            set { this._location = value; }
        }

        // Check to see if Location property is set
        internal bool IsSetLocation()
        {
            return this._location != null;
        }

        /// <summary>
        /// Gets and sets the property UploadId.
        /// <para>
        /// The ID of the multipart upload. This value is also included as part of the location.
        ///
        /// </para>
        /// </summary>
        public string UploadId
        {
            get { return this._uploadId; }
            set { this._uploadId = value; }
        }

        // Check to see if UploadId property is set
        internal bool IsSetUploadId()
        {
            return this._uploadId != null;
        }

    }
}


text:
angular.module('moduleA').controller(function ($scope) {

});


text:
from tests.base_case import ChatBotTestCase
from mock import Mock, MagicMock
from chatterbot.trainers import TwitterTrainer
import os
import json

def get_search_side_effect(*args, **kwargs):
    from twitter import Status

    current_directory = os.path.dirname(os.path.realpath(__file__))
    data_file = os.path.join(
        current_directory,
        'test_data',
        'get_search.json'
    )
    tweet_data = open(data_file)
    data = json.loads(tweet_data.read())
    tweet_data.close()

    return [Status.NewFromJsonDict(x) for x in data.get('statuses')]

def get_status_side_effect(*args, **kwargs):
    from twitter import Status

    current_directory = os.path.dirname(os.path.realpath(__file__))
    data_file = os.path.join(
        current_directory,
        'test_data',
        'get_search.json'
    )
    tweet_data = open(data_file)
    data = json.loads(tweet_data.read())
    tweet_data.close()

    return Status.NewFromJsonDict(data.get('statuses')[1])

class TwitterTrainerTestCase(ChatBotTestCase):

    def setUp(self):
        """
        Instantiate the trainer class for testing.
        """
        super(TwitterTrainerTestCase, self).setUp()

        self.trainer = TwitterTrainer(
            self.chatbot.storage,
            twitter_consumer_key='twitter_consumer_key',
            twitter_consumer_secret='twitter_consumer_secret',
            twitter_access_token_key='twitter_access_token_key',
            twitter_access_token_secret='twitter_access_token_secret'
        )
        self.trainer.api = Mock()

        self.trainer.api.GetSearch = MagicMock(side_effect=get_search_side_effect)
        self.trainer.api.GetStatus = MagicMock(side_effect=get_status_side_effect)

    def test_random_word(self):
        word = self.trainer.random_word('random')

        self.assertTrue(len(word) > 3)

    def test_get_words_from_tweets(self):
        tweets = get_search_side_effect()
        words = self.trainer.get_words_from_tweets(tweets)

        self.assertIn('about', words)
        self.assertIn('favorite', words)
        self.assertIn('things', words)

    def test_get_statements(self):
        statements = self.trainer.get_statements()

        self.assertEqual(len(statements), 1)

    def test_train(self):
        self.trainer.train()

        statement_created = self.trainer.storage.filter()
        self.assertTrue(len(statement_created))


text:
SELECT *
FROM pg_depend as d1
WHERE refclassid = 0 OR refobjid = 0 OR
      deptype NOT IN ('a', 'e', 'i', 'n', 'p') OR
      (deptype != 'p' AND (classid = 0 OR objid = 0)) OR
      (deptype = 'p' AND (classid != 0 OR objid != 0 OR objsubid != 0));

-- **************** pg_shdepend ****************

-- Look for illegal values in pg_shdepend fields.
-- classid/objid can be zero, but only in 'p' entries

SELECT *
FROM pg_shdepend as d1
WHERE refclassid = 0 OR refobjid = 0 OR
      deptype NOT IN ('a', 'o', 'p', 'r') OR
      (deptype != 'p' AND (classid = 0 OR objid = 0)) OR
      (deptype = 'p' AND (dbid != 0 OR classid != 0 OR objid != 0 OR objsubid != 0));

-- Check each OID-containing system catalog to see if its lowest-numbered OID
-- is pinned.  If not, and if that OID was generated during initdb, then
-- perhaps initdb forgot to scan that catalog for pinnable entries.
-- Generally, it's okay for a catalog to be listed in the output of this
-- test if that catalog is scanned by initdb.c's setup_depend() function;
-- whatever OID the test is complaining about must have been added later
-- in initdb, where it intentionally isn't pinned.  Legitimate exceptions
-- to that rule are listed in the comments in setup_depend().

do $$
declare relnm text;
  reloid oid;
  shared bool;
  lowoid oid;
  pinned bool;
begin
for relnm, reloid, shared in
  select relname, oid, relisshared from pg_class
  where EXISTS(
      SELECT * FROM pg_attribute
      WHERE attrelid = pg_class.oid AND attname = 'oid')
    and relkind = 'r' and oid < 16384 order by 1
loop
  execute 'select min(oid) from ' || relnm into lowoid;
  continue when lowoid is null or lowoid >= 16384;
  if shared then
    pinned := exists(select 1 from pg_shdepend
                     where refclassid = reloid and refobjid = lowoid
                     and deptype = 'p');
  else
    pinned := exists(select 1 from pg_depend
                     where refclassid = reloid and refobjid = lowoid
                     and deptype = 'p');
  end if;
  if not pinned then
    raise notice '% contains unpinned initdb-created object(s)', relnm;
  end if;
end loop;
end$$;

-- **************** pg_class ****************

-- Look for system tables with varlena columns but no toast table. All
-- system tables with toastable columns should have toast tables, with
-- the following exceptions:
-- 1. pg_class, pg_attribute, and pg_index, due to fear of recursive
-- dependencies as toast tables depend on them.
-- 2. pg_largeobject and pg_largeobject_metadata.  Large object catalogs
-- and toast tables are mutually exclusive and large object data is handled
-- as user data by pg_upgrade, which would cause failures.

-- GPDB: A few GPDB catalog tables are also missing toast tables. Not
-- for any particular reason, but the fields are only used to store short
-- system-generated values, so they don't need toasting.

SELECT relname, attname, atttypid::regtype
FROM pg_class c JOIN pg_attribute a ON c.oid = attrelid
WHERE c.oid < 16384 AND
      reltoastrelid = 0 AND
      relkind = 'r' AND
      attstorage != 'p'
ORDER BY 1, 2;


text:
package com.deftwun.zombiecopter.components;

import com.badlogic.ashley.core.Component;
import com.badlogic.gdx.utils.Pool.Poolable;

public class WalkComponent extends Component implements Poolable{
	public float topSpeed;
	//public boolean left,right;

	/*
	public void stop(){left = false; right = false;}
	public void walkLeft(){right = false; left = true;}
	public void walkRight(){right = true; left = false;}
	*/

	@Override
	public void reset() {
		topSpeed = 0;
		//left = false;
		//right = false;
	}
}


text:
package com.facebook.buck.shell;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.hash.HashCode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;

public abstract class WorkerProcessPool {

  private final int capacity;
  private final BlockingQueue<WorkerProcess> availableWorkers;
  @GuardedBy("createdWorkers")
  private final List<WorkerProcess> createdWorkers;
  private final HashCode poolHash;

  public WorkerProcessPool(int maxWorkers, HashCode poolHash) {
    this.capacity = maxWorkers;
    this.availableWorkers = new LinkedBlockingQueue<>();
    this.createdWorkers = new ArrayList<>();
    this.poolHash = poolHash;
  }

  /**
   * If there are available workers, returns one. Otherwise blocks until one becomes available and
   * returns it. You must free worker process by calling {@link #returnWorkerProcess(WorkerProcess)}
   * method after you finish using it.
   */
  public WorkerProcess borrowWorkerProcess()
      throws IOException, InterruptedException {
    WorkerProcess workerProcess = availableWorkers.poll(0, TimeUnit.SECONDS);
    if (workerProcess == null) {
      workerProcess = createNewWorkerIfPossible();
    }
    if (workerProcess != null) {
      return workerProcess;
    }
    return availableWorkers.take();
  }

  private @Nullable WorkerProcess createNewWorkerIfPossible() throws IOException {
    synchronized (createdWorkers) {
      if (createdWorkers.size() == capacity) {
        return null;
      }
      WorkerProcess process = Preconditions.checkNotNull(startWorkerProcess());
      createdWorkers.add(process);
      return process;
    }
  }

  public void returnWorkerProcess(WorkerProcess workerProcess)
      throws InterruptedException {
    synchronized (createdWorkers) {
      Preconditions.checkArgument(
          createdWorkers.contains(workerProcess),
          "Trying to return a foreign WorkerProcess to the pool");
    }
    availableWorkers.put(workerProcess);
  }

  public void close() {
    ImmutableSet<WorkerProcess> processesToClose;
    synchronized (createdWorkers) {
      processesToClose = ImmutableSet.copyOf(createdWorkers);
      Preconditions.checkState(
          availableWorkers.size() == createdWorkers.size(),
          "WorkerProcessPool was still running when shutdown was called.");
    }

    for (WorkerProcess process : processesToClose) {
      process.close();
    }
  }

  public int getCapacity() {
    return capacity;
  }

  protected abstract WorkerProcess startWorkerProcess() throws IOException;

  public HashCode getPoolHash() {
    return poolHash;
  }
}


text:
{% extends "base.html" %}

{% block title %}Edit Post{% endblock %}

{% block body %}

Edit the Post

  <form method="POST" action="{{ url_for('blog.edit_post', id=post.id) }}">
    {{ form.hidden_tag() }}

      {{ form.title.label }}
      {% if form.title.errors %}
      {% for e in form.title.errors %}

{{ e }}

      {% endfor %}
      {% endif %}
      {{ form.title(class_='form-control', value=post.title) }}

      {{ form.text.label }}
      {% if form.text.errors %}
      {% for e in form.text.errors %}

{{ e }}

      {% endfor %}
      {% endif %}
      {{ form.text(id="editor", class_='form-contril') }}

    <input class="btn-primary" type="submit" value="Submit">
  </form>

{% endblock %}

{% block js %}

{% endblock %}


text:
export default function MissingBlueprintError(key) {
  const error = new Error(
    `There was no blueprint provided for '${key}'. You must provide one if
    your getState call does not map to conventions.`
  );
  error.name = 'MissingBlueprintError';
  return error;
}


text:
@interface CCCommonDefine ()

@end

@implementation CCCommonDefine

void CC_Safe_Operation(id blockNil , dispatch_block_t block) {
    if (!blockNil || !block) return;
    block();
}
void CC_Safe_UI_Operation(id blockNil , dispatch_block_t block) {
    if (!blockNil || !block) return;
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_sync(dispatch_get_main_queue(), ^{
            block();
        });
    }
}
void CC_Main_Queue_Operation(dispatch_block_t block) {
    if (!block) return;
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_sync(dispatch_get_main_queue(), ^{
            block();
        });
    }
}

void CC_Debug_Operation(dispatch_block_t block) {
    if (_CC_DEBUG_MODE_) {
        if (block) block();
    }
}

UIColor * ccHexColor(int intValue ,float floatAlpha){
    return [UIColor colorWithRed:( (CGFloat) ( (intValue & 0xFF0000) >> 16) ) / 255.0
                           green:( (CGFloat) ( (intValue & 0xFF00) >> 8) ) / 255.0
                            blue:( (CGFloat) (intValue & 0xFF) ) / 255.0
                           alpha:floatAlpha];
}

UIColor *ccRGBColor(float floatR , float floatG , float floatB){
    return ccRGBAColor(floatR, floatG, floatB, 1.0f);
}
UIColor *ccRGBAColor(float floatR , float floatG , float floatB , float floatA) {
    return [UIColor colorWithRed:floatR / 255.0f
                           green:floatG / 255.0f
                            blue:floatB / 255.0f
                           alpha:floatA];
}

NSURL * ccURL (NSString * stringURL , BOOL isLocalFile) {
    return isLocalFile ? [NSURL fileURLWithPath:stringURL] : [NSURL URLWithString:stringURL];
}

UIImage *ccImageCache(NSString *stringName){
    return ccImage(stringName, YES);
}

UIImage *ccImage(NSString *stringName , BOOL isCacheInMemory){
    return isCacheInMemory ? [UIImage imageNamed:stringName] : [UIImage imageWithContentsOfFile:stringName];
}

NSString * ccLocalize(NSString * stringLocalKey , ...){
    return ccBundleLocalize(stringLocalKey, NSBundle.mainBundle , "");
}

NSString * ccBundleLocalize(NSString * stringLocalKey , NSBundle * bundle , ... ){
    return NSLocalizedStringFromTableInBundle(stringLocalKey, @"LocalizableMain", bundle, nil);
}

NSString * ccObjMerge(id obj , ... ) {
    NSMutableArray *arrayStrings = [NSMutableArray array];
    NSString *stringTemp;
    va_list argumentList;
    if (obj) {
        if ([obj isKindOfClass:[NSString class]]) {
            [arrayStrings addObject:obj];
        } else [arrayStrings addObject:ccStringFormat(@"%@",obj)];
        va_start(argumentList, obj);
        while ((stringTemp = va_arg(argumentList, id))) {
            if ([stringTemp isKindOfClass:[NSString class]]) {
                [arrayStrings addObject:stringTemp];
            } else [arrayStrings addObject:ccStringFormat(@"%@",stringTemp)] ;
        }
        va_end(argumentList);
    }
    return [NSString ccMergeWithStringArray:arrayStrings
                          withNeedLineBreak:false
                            withNeedSpacing:false];
}

@end


text:
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        def dfs(curr, maxVal):
            if curr is None:
                return 0
            count = 1 if curr.val >= maxVal else 0
            maxVal = max(maxVal, curr.val)
            return count + dfs(curr.left, maxVal) + dfs(curr.right, maxVal)
        return dfs(root, root.val)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@android:color/background_dark"
    tools:context="me.seanmaltby.canary.MainActivity">

    <ImageView
        android:id="@+id/album_art"
        android:layout_width="320dp"
        android:layout_height="320dp"
        android:adjustViewBounds="false"
        android:cropToPadding="false"
        app:srcCompat="@android:color/background_dark"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:onClick="listen" />

    <TextView
        android:id="@+id/shuffle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/album_art"
        android:layout_marginTop="42dp"
        android:ems="5"
        android:textColor="@android:color/white"
        android:text="Shuffle: False" />

    <TextView
        android:id="@+id/repeat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/album_art"
        android:layout_marginTop="42dp"
        android:ems="5"
        android:textColor="@android:color/white"
        android:text="Repeat: False"
        android:layout_alignParentEnd="true"/>

    <TextView
        android:id="@+id/song"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/album_art"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/white"
        android:text=""/>

    <TextView
        android:id="@+id/artist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/song"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/white"
        android:text=""/>

</RelativeLayout>


text:
class CommentCounts < CequelCQL2::Model::Counter

  key :blog_id, :int
  columns :uuid

  self.default_batch_size = 2

end


text:
package com.lordjoe.distributed.util;

import com.lordjoe.distributed.*;

import javax.annotation.*;
import java.io.*;

/**
 * com.lordjoe.distributed.util.WordNumberSerializer
 * Sample serializer for a simple object
 * -- NOTE any object which can be expressed as one line of test can
 * work i this way
 * User: Steve
 * Date: 8/25/2014
 */
public class WordNumberSerializer implements IStringSerializer<WordNumber> {

    /**
     * convert a String to a T
     *
     * @param src source string
     * @return possibly null T
     */
    @Override public WordNumber fromString(@Nonnull final String src) {
        return new WordNumber(src);
    }

    @Override public String serialize(@Nonnull final WordNumber src) {
        return src.toString();
    }

    /**
     * if this was Java this would be a default out.append(serialize(src); out.append("\n");
     *
     * @param src source object
     * @param out sink - all exceptions convert to runtimes
     */
    @Override public void append(@Nonnull final WordNumber src, @Nonnull final Appendable out) {
        try {
            out.append(serialize(src));
            out.append("\n");
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param rdr reader
     * @return possibly null T - also set the value of line to the current position
     */
    @Override public WordNumber fromReader(@Nonnull final LineNumberReader rdr) {
        try {
            String line = rdr.readLine();
            if (line == null || line.length() == 0)
                return null;
            return fromString(line);
        }
        catch (IOException e) {
            throw new RuntimeException(e);

        }
    }
}


text:
<?php

namespace Symfony\Component\Cache\Tests\Adapter;

use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\Psr16Adapter;
use Symfony\Component\Cache\Psr16Cache;

/**
 * @group time-sensitive
 */
class Psr16AdapterTest extends AdapterTestCase
{
    protected $skippedTests = [
        'testPrune' => 'Psr16adapter just proxies',
        'testClearPrefix' => 'SimpleCache cannot clear by prefix',
    ];

    public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface
    {
        return new Psr16Adapter(new Psr16Cache(new FilesystemAdapter()), '', $defaultLifetime);
    }

    public function testValidCacheKeyWithNamespace()
    {
        $cache = new Psr16Adapter(new Psr16Cache(new ArrayAdapter()), 'some_namespace', 0);
        $item = $cache->getItem('my_key');
        $item->set('someValue');
        $cache->save($item);

        $this->assertTrue($cache->getItem('my_key')->isHit(), 'Stored item is successfully retrieved.');
    }
}


text:
using DotNetNuke.Entities.Modules;

namespace Dnn.Modules.DnnSpaModule
{
    public class DnnSpaModuleModuleSettingsBase : ModuleSettingsBase
    {
    }
}