text:
package com.trywildcard.pair.model.media;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.trywildcard.pair.exception.CardBuilderException;
import com.trywildcard.pair.extraction.MetaTagModel;
import com.trywildcard.pair.model.Builder;
import com.trywildcard.pair.validation.ValidationTool;
import org.apache.commons.lang3.StringUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * Created by karthiksenthil on 10/5/14.
 */
@JsonPOJOBuilder(buildMethodName = "build", withPrefix = "")
public class VideoBuilder implements Builder<Video> {

    @JsonIgnore
    protected ValidationTool v = new ValidationTool();

    protected String title;
    protected URL embeddedUrl;
    protected Integer embeddedUrlWidth;
    protected Integer embeddedUrlHeight;

    //optional fields
    protected URL streamUrl;
    protected String streamContentType;
    protected Date publicationDate;
    protected String description;
    protected URL posterImageUrl;
    protected String creator;
    protected String source;

    /** Private Constructor **/
    private VideoBuilder() { }

    /**
     * Construct an VideoBuilder provided a title and embeddedUrl.
     */
    public VideoBuilder(String title, String embeddedUrl, Integer embeddedUrlWidth, Integer embeddedUrlHeight) throws CardBuilderException {
        title(title);
        embeddedUrl(embeddedUrl);
        embeddedUrlHeight(embeddedUrlHeight);
        embeddedUrlWidth(embeddedUrlWidth);
    }

    /**
     * Construct an VideoBuilder provided a meta tag model
     */
    public VideoBuilder(MetaTagModel metaTagModel) throws CardBuilderException {

        try {
            if (metaTagModel == null) {
                throw new CardBuilderException("MetaTagModel is required");
            }

            if (StringUtils.isEmpty(metaTagModel.getTitle()) || StringUtils.isEmpty(metaTagModel.getVideoUrl())
                    || StringUtils.isEmpty(metaTagModel.getVideoHeight()) || StringUtils.isEmpty(metaTagModel.getVideoWidth())) {
                throw new CardBuilderException("Either video title, url, width, or height is not contained in meta tags" +
                        " - all of which are required to create a VideoBuilder");
            }

            title(metaTagModel.getTitle());
            embeddedUrl(metaTagModel.getVideoUrl());
            embeddedUrlHeight(Integer.parseInt(metaTagModel.getVideoHeight()));
            embeddedUrlWidth(Integer.parseInt(metaTagModel.getVideoWidth()));

            /* optional fields to attempt to fill in */
            description(metaTagModel.getDescription());
            posterImageUrl(metaTagModel.getImageUrl());
        } catch (NumberFormatException nfe) {
            throw new CardBuilderException("Unable to convert video width or height meta tag value to a valid integer, " +
                    "which is required to construct a VideoBuilder", nfe);
        }
    }

    private VideoBuilder title(String title) throws CardBuilderException {
        boolean isValid = v.required(v.notNullOrEmpty(title), "Video Title cannot be blank.");
        if (isValid) {
            this.title = title;
        }
        return this;
    }

    private VideoBuilder embeddedUrl(String embeddedURL) throws CardBuilderException {
        boolean isValid = v.required(v.notNullOrEmpty(embeddedURL), "Must specify a video embedded URL.");
        if (isValid) {
            try {
                this.embeddedUrl = new URL(embeddedURL);
            } catch (MalformedURLException e) {
                v.required(v.fail(), "Could not parse URL from embedded URL.");
            }
        }

        return this;
    }

    private void embeddedUrlHeight(Integer embeddedURLHeight) throws CardBuilderException {
        boolean isNotNull = v.required(v.notNull(embeddedURLHeight), "Video embeddedUrlHeight must not be null");
        boolean isNotNegative = v.required(v.notNegative(embeddedURLHeight), "Video embeddedUrlHeight must be a non-negative Integer.");

        if (isNotNull && isNotNegative) {
            this.embeddedUrlHeight = embeddedURLHeight;
        }
    }

    private void embeddedUrlWidth(Integer embeddedURLWidth) throws CardBuilderException {
        boolean isNotNull = v.required(v.notNull(embeddedURLWidth), "Video embeddedUrlWidth must not be null");
        boolean isNotNegative = v.required(v.notNegative(embeddedURLWidth), "Video embeddedUrlWidth must be a non-negative Integer.");

        if (isNotNull && isNotNegative) {
            this.embeddedUrlWidth = embeddedURLWidth;
        }
    }

    public VideoBuilder streamUrl(String streamUrl) {
        boolean isValid = v.optional(v.notNullOrEmpty(streamUrl), "Must specify a video streamUrl.");
        if (isValid) {
            try {
                this.streamUrl = new URL(streamUrl);
            } catch (MalformedURLException e) {
                v.optional(v.fail(), "Could not parse URL from video stream URL.");
            }
        }

        return this;
    }

    public VideoBuilder streamContentType(String streamContentType) {
        boolean isValid = v.optional(v.notNullOrEmpty(streamContentType), "Must specify a video streamUrl.");
        if (isValid) {
            this.streamContentType = streamContentType;
        }

        return this;
    }

    public VideoBuilder posterImageUrl(String posterImageUrl) {
        boolean isValid = v.optional(v.notNullOrEmpty(posterImageUrl), "Must specify a posterImageUrl.");
        if (isValid) {
            try {
                this.posterImageUrl = new URL(posterImageUrl);
            } catch (MalformedURLException e) {
                v.optional(v.fail(), "Could not parse URL from video posterImageUrl.");
            }
        }

        return this;
    }

    public VideoBuilder publicationDate(Date publicationDate) {
        boolean isValid = v.optional(v.notNull(publicationDate), "Article Publication Date cannot be null.");
        if (isValid) {
            this.publicationDate = publicationDate;
        }
        return this;
    }

    public VideoBuilder description(String description) {
        boolean isValid = v.optional(v.notNullOrEmpty(description), "Video description cannot be blank.");
        if (isValid) {
            this.description = description;
        }
        return this;
    }

    public VideoBuilder creator(String creator) {
        boolean isValid = v.optional(v.notNullOrEmpty(creator), "Video creator cannot be blank.");
        if (isValid) {
            this.creator = creator;
        }
        return this;
    }

    public VideoBuilder source(String source) {
        boolean isValid = v.optional(v.notNullOrEmpty(source), "Vdieo Source cannot be blank.");
        if (isValid) {
            this.source = source;
        }
        return this;
    }

    /**
     * Instantiate a Video with the data in this builder.
     * @return the constructed video
     */
    public Video build() {
        Video video = new Video(this);
        return video;
    }

    /**
     * Get a list of validation errors.
     * @return the list of errors.
     */
    public List<String> getErrors(){
        return v.getErrors();
    }

}


text:
First be sure to enable the haproxy UDS stats socket in the config then reload:
```
global
  stats socket /tmp/haproxy.sock mode 600 level admin
  stats socket ipv4@127.0.0.1:9000 level admin
  stats timeout 2m
```

## CLI Usage
Once haproxy is configured and reloaded, collect haproxy stats and/or info as follows:

```
export HAPROXY_SOCK=/tmp/haproxy.sock
haproxy-cli stats
haproxy-cli info
```

For using haproxy-cli with BOSH releases see `docs/bosh.md`

## Library Usage

Be sure that the `HAPROXY_SOCK` environment variable is set and pointing to the
location of the HAProxy socket file as described above.

Import the library, if you set the import name to `hap` then you can name your
object that you interact with `haproxy`.
```
import (
	hap "github.com/wayneeseguin/haproxy-cli/haproxy"
)
```
Create a new haproxy object:
```
haproxy = &hap.Haproxy{Socket: os.Getenv("HAPROXY_SOCK")}
```

Then you can gather statistics as a JSON array of statistics K/V objects,
```
output, err := haproxy.Stats("all")
```

Or information about the haproxy process as a JSON KV Object,
```
output, err := haproxy.Info()
```

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syst. nat. 2(2):1035. 1792

#### Original name
null

### Remarks
null


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'nonce-noncynonce' 'nonce-noncy+/nonce='; connect-src 'self';">
    <title>scriptnonce-allowed</title>

        This tests the effect of a valid script-nonce value. It passes if no CSP violation is generated and the alerts are executed.


text:
import { AlloySpec, Behaviour, GuiFactory, Keying, Replacing, SimpleSpec } from '@ephox/alloy';
import { Dialog } from '@ephox/bridge';
import { Arr, Optional } from '@ephox/katamari';

import { UiFactoryBackstageShared } from '../../backstage/Backstage';
import { ComposingConfigs } from '../alien/ComposingConfigs';
import { RepresentingConfigs } from '../alien/RepresentingConfigs';

type LabelSpec = Omit<Dialog.Label, 'type'>;

export const renderLabel = (spec: LabelSpec, backstageShared: UiFactoryBackstageShared): SimpleSpec => {
  const label: AlloySpec = {
    dom: {
      tag: 'label',
      classes: [ 'tox-label' ]
    },
    components: [
      GuiFactory.text(backstageShared.providers.translate(spec.label))
    ]
  };
  const comps = Arr.map(spec.items, backstageShared.interpreter);
  return {
    dom: {
      tag: 'div',
      classes: [ 'tox-form__group' ]
    },
    components: [
      label,
      ...comps
    ],
    behaviours: Behaviour.derive([
      ComposingConfigs.self(),
      Replacing.config({}),
      RepresentingConfigs.domHtml(Optional.none()),
      Keying.config({
        mode: 'acyclic'
      })
    ])
  };
};


text:
package org.tolweb.treedrawing;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.GeneralPath;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

import javax.swing.ImageIcon;

import org.tolweb.btol.AdditionalFields;
import org.tolweb.dao.PageDAO;
import org.tolweb.hibernate.MappedNode;
import org.tolweb.hibernate.MappedOtherName;
import org.tolweb.hibernate.MappedPage;
import org.tolweb.misc.URLBuilder;
import org.tolweb.treegrow.main.StringUtils;
import org.tolweb.treegrow.tree.AbstractTreePanel;
import org.tolweb.treegrow.tree.Node;
import org.tolweb.treegrow.tree.NodeView;
import org.tolweb.treegrow.tree.Tree;
import org.tolweb.treegrow.tree.TreeFrame;

/**
 * Low-functionality tree panel found on the Page tab of the node/page
 * data editor
 */
public class TreeImagePanel extends AbstractTreePanel implements MouseListener {
	private static final int EXTINCT_IMAGE_PADDING = 4;
	/**
	 *
	 */
	private static final long serialVersionUID = 9082043354199013015L;
	private Node rootNode;
    private Font microsoftArialFont;
    private Font microsoftArialItalicFont;
    @SuppressWarnings("unchecked")
    private Hashtable nodeViewsToLabelPoints = new Hashtable();
    @SuppressWarnings("unchecked")
    private Hashtable pagedNodeViewsToPoints = new Hashtable();
    @SuppressWarnings("unchecked")
    private List monophylyUncertainRects = new ArrayList();
    @SuppressWarnings("unchecked")
    private List notMonophylecticRects = new ArrayList();
    @SuppressWarnings("unchecked")
    private List ispuNodeViews = new ArrayList();
    private PageDAO pageDAO;
    private URLBuilder urlBuilder;
    private Rectangle rootRectangle;
    private boolean isBlackLines = true;
    private boolean drawDescriptions;
    private boolean drawAuthorities;
    private boolean includeSpecimenInfo;
    private Color leadsToComplete = Color.magenta.darker();
    private Color lightGray = new Color(181, 178, 183);
    private Color descriptionLightGray = Color.lightGray.darker();

    private int currentMaxTerminalTextOverrun = 0;
    private int maxTerminalX;
    private static final int X_PADDING = 4;
    private static final int TERMINAL_ADJUSTMENT = 2;
    private static final int DESCRIPTION_AUTHORITY_PADDING = 5;
    protected Font questionMarkFont;// = new Font("SansSerif", Font.PLAIN, DEFAULT_QUESTIONMARK_FONT_SIZE + 2);
    @SuppressWarnings("unchecked")
	private List confidenceNotMonophyleticRects = new ArrayList();
    @SuppressWarnings("unchecked")
	private List confidenceMonophlyUncertainRects = new ArrayList();

    private Color trunkColor = Color.orange;
    @SuppressWarnings("unchecked")
	private List trunkVertLineList = new ArrayList();
    // This is the "trunk coloring" switch - needs to be refactored out into
    // an implementation of a tree-colorer or tree-color-strategy, whatever it's
    // going to be called going forward
	private boolean trunkColoringEnabled = false;

    public TreeImagePanel() {
        this(null, null, null, null, null);
    }
    public TreeImagePanel(String arialFontPath, String arialItalicFontPath, String extinctIconPath) {
    	this(null, null, arialFontPath, arialItalicFontPath, extinctIconPath);
    }

    /** Creates a new instance of PreviewTreePanel */
    public TreeImagePanel(Tree tr, TreeFrame frame, String arialFontPath, String arialItalicFontPath,
    		String extinctImagePath) {
        super(tr, frame);
        setBackground(Color.white);
        try {
            microsoftArialFont = Font.createFont(Font.TRUETYPE_FONT, new File(arialFontPath));
            microsoftArialItalicFont = Font.createFont(Font.TRUETYPE_FONT, new File(arialItalicFontPath));
            microsoftArialFont = microsoftArialFont.deriveFont(11F);
            microsoftArialItalicFont = microsoftArialItalicFont.deriveFont(11F);
            setFont(microsoftArialFont);
            zoomFactor++;
            zoomUpdate(microsoftArialFont);
            questionMarkFont = microsoftArialFont;
            initQMarkDims();
            extinctImage = new ImageIcon(extinctImagePath).getImage();
	        extinctImageWidth = extinctImage.getWidth(null);
	        extinctImageHeight = extinctImage.getHeight(null);
        } catch (FontFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * workaround for jdk1.6 bug!  Also, since there is no repainting
     * for this, no need to be double buffered
     */
	protected boolean getUseDoubleBuffering() {
		return false;
	}

    /**
     * Overrides method in abstract class  - gives root of subtree being drawn
     */
    protected Node getRootNode() {
        return rootNode;
    }

    public void setRootNode(Node node) {
        this.rootNode = node;
    }

    /**
     * Overrides method in abstract class  - causes tree to be drawn 1-deep
     */
    public boolean dontDrawChildren(NodeView view) {
        return view.getNode() != rootNode && view.getNode().hasPage();
    }

    @SuppressWarnings("unchecked")
    protected void addExtinctIndicator(NodeView currentView) {
    	// only draw extinct icons for terminal taxa
    	if (currentView.getIsTerminal()) {
	        Point stringLoc = getStringLoc(currentView);
	        int startX = stringLoc.x;
	        // add in the metrics for the name
	        startX += getStringWidthForNodeView(currentView); // <-- DEVN: BUG: when taxa name italic, the last character covers the extinct icon (this is likely the method needing the fix)
	        if (! currentView.isTerminal() ) {
	            startX += getCircleDiameter() + getHalfCircleDiameter();
	        }
	        startX += X_PADDING;
	        int startY = currentView.getY() ;
	        extinctIndicators.add(new Point(startX, startY));
    	}
    }

    protected void handleConfidenceDoubleQmark(Point p, Rectangle repaintRect, Graphics g) {
    	NodeView rootView = (NodeView) nodeToNodeView.get(getRootNode());
    	int rootX = rootView.getX();
        g.drawString("?", p.x + 7, p.y+getCircleDiameter());
        Color currentColor = g.getColor();
        g.setColor(Color.white);
        // draw white rects back to root in order to clean up any other lines that might have
        // arisen
        g.fillRect(rootX, p.y, p.x - rootX, getYStep());
        g.setColor(currentColor);
	}

    /**
     * For TreeGrow purposes a 1-pixel line is fine but on the pages we would
     * like a thicker stroke, so allow this to be overridden
     * @return
     */
    public boolean getAdjustStroke() {
    	return true;
    }

    /**
     * Can be overridden by subclasses who want a thicker stroke
     * @return
     */
    public BasicStroke getThickerStroke() {
    	return new BasicStroke(2.55f);
    }

    /**
     * Overridden to clear the contents of the panel
     */
    @SuppressWarnings("unchecked")
    public void paintComponent(Graphics g) {
    	Graphics2D g2d = (Graphics2D) g;
        Rectangle clipRect = g.getClipBounds();
        //clipRect.setBounds((int)clipRect.getX(), (int)clipRect.getY() + TOP_PADDING, (int)clipRect.getWidth(), (int)clipRect.getHeight() - TOP_PADDING);
        g.clearRect(0, 0, (int) clipRect.getWidth(), (int) clipRect.getHeight());
        super.paintComponent(g);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        // for antialiasing geometric shapes
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

        //g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        // to go for quality over speed
        //g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );

        //g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        //
        //g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        //g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_I)

        iterateLabelPoints(g, nodeViewsToLabelPoints, Color.black);
        iterateLabelPoints(g, pagedNodeViewsToPoints, Color.blue);
        NodeView rootView = (NodeView) nodeToNodeView.get(rootNode);
        // draw root triangle
        Color color = g.getColor();
        g.setColor(getIsBlackLines() ? Color.black : getLightGrayColor());
        boolean isTrunkNode = getRootNode().getTrunkNode() == Node.TRUNK_NODE;
        g.setColor(getTrunkColoringEnabled() && isTrunkNode ? trunkColor : g.getColor());
        GeneralPath triangle = new GeneralPath();
        int startX = rootView.getX() - getDefaultLineLength() - 5 + getRootLineLessPixels();
        int startY = rootView.getY() + getCircleDiameter() / 2 + 1;
        triangle.moveTo(startX, startY);
        int triRight = startX + 9;
        int triTop = startY - 5;
        int triBottom = startY + 4;
        Stroke stroke = g2d.getStroke();
    	BasicStroke thinnerStroke = new BasicStroke(0.5f);
        g2d.setStroke(thinnerStroke);
        triangle.lineTo(triRight, triTop);
        triangle.lineTo(triRight, triBottom);
        triangle.closePath();
        //triangle.lineTo(startX, startY);
        g2d.setStroke(stroke);
        rootRectangle = triangle.getBounds();
        (g2d).fill(triangle);

        // draw over top of the vertical lines if trunk color is enabled
        if (getTrunkColoringEnabled() && isTrunkNode) {
        	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
            Stroke preserveStroke = g2d.getStroke();
            BasicStroke thickerStroke = getThickerStroke();
            g2d.setStroke(thickerStroke);
        	g2d.setColor(getTrunkColor());
            Iterator it = trunkVertLineList.iterator();

            while (it.hasNext()) {
                int[] coords = (int[]) it.next();
                int repaintMaxX = (int)(clipRect.getX() + clipRect.getWidth());
                int repaintMaxY = (int)(clipRect.getY() + clipRect.getHeight());

                boolean vertOrHorizInRect = (coords[2] >= clipRect.getX()  && coords[0] <= repaintMaxX   &&
                                            coords[3] >= clipRect.getY() &&  coords[1] <= repaintMaxY );

                boolean diagInRect = false;

                if (coords[0]!=coords[2] && coords[1]!=coords[3]) { //is a diagonal
                    Point pt1 = new Point(coords[0],coords[1]);
                    Point pt2 = new Point(coords[2],coords[3]);
                    diagInRect = (clipRect.contains (pt1) ||  clipRect.contains (pt2));
                }
                if (vertOrHorizInRect || diagInRect) {
                    //only paint this line if it in some way overlaps the requests rectangle of repainting
                    g2d.drawLine(coords[0], coords[1], coords[2], coords[3]);
                }
            }
            g2d.setStroke(preserveStroke);
        }
        // draw a 2-pixel rect just to the right of the triangle in order to
        // create some separation for the back to root arrow
        g.setColor(Color.white);
        g.fillRect(triRight, triTop, 1, triBottom - triTop);
        if (getIncludeSpecimenInfo()) {
        	drawSpecimenInfo(g);
        }
        g.setColor(color);
    }

    @SuppressWarnings("unchecked")
    private void drawSpecimenInfo(Graphics g) {
    	List terminalViews = new ArrayList();
    	for (Iterator iter = nodeViews.iterator(); iter.hasNext();) {
			NodeView nextView = (NodeView) iter.next();
			if (nextView.getIsTerminal()) {
				terminalViews.add(nextView);
			}
		}
    	int squareSize = 12;
    	int relatedSquaresSpacing = 5;
    	int unrelatedSquaresSpacing = 15;
    	int labelYPos = 10;
    	int i = 0;
    	Font currentFont = g.getFont();
    	for (Iterator iter = terminalViews.iterator(); iter.hasNext();) {
			NodeView nextView = (NodeView) iter.next();
			MappedNode node  = (MappedNode) nextView.getNode();
			// DNA rects
			int currentX = maxTerminalX + 10;
			// draw header
			if (i == 0) {
				Font newFont = microsoftArialFont.deriveFont(Font.BOLD);
				g.setFont(newFont);
				g.setColor(Color.black);
				g.drawString("DNA", currentX + 3, labelYPos);
			}
			g.setColor(getColorForDNAPrioritySquare(node));
			g.fillRect(currentX, nextView.getY() - 2, squareSize, squareSize);
			g.setColor(Color.black);
			currentX += squareSize + relatedSquaresSpacing;
			g.setColor(getColorForDNASpecimensSquare(node));
			g.fillRect(currentX, nextView.getY() - 2, squareSize, squareSize);
			currentX += squareSize + unrelatedSquaresSpacing;
			// Adults rects
			if (i == 0) {
				g.setColor(Color.black);
				g.drawString("Adults", currentX - 2, labelYPos);
			}
			g.setColor(getColorForAdultPrioritySquare(node));
			g.fillRect(currentX, nextView.getY() - 2, squareSize, squareSize);
			g.setColor(Color.black);
			currentX += squareSize + relatedSquaresSpacing;
			g.setColor(getColorForAdultSpecimensSquare(node));
			g.fillRect(currentX, nextView.getY() - 2, squareSize, squareSize);
			currentX += squareSize + unrelatedSquaresSpacing;
			// Larvae rects
			if (i == 0) {
				g.setColor(Color.black);
				g.drawString("Larvae", currentX - 2, labelYPos);
			}
			g.setColor(getColorForLarvaePrioritySquare(node));
			g.fillRect(currentX, nextView.getY() - 2, squareSize, squareSize);
			currentX += squareSize + relatedSquaresSpacing;
			g.setColor(getColorForLarvaeSpecimensSquare(node));
			g.fillRect(currentX, nextView.getY() - 2, squareSize, squareSize);
			i++;
			g.setColor(Color.black);
		}
    	g.setFont(currentFont);
    }

    private Color getColorForDNASpecimensSquare(MappedNode node) {
    	return getColorForSpecimens(true, node.getAdditionalFields().getDnaPriority());
    }

    private Color getColorForLarvaeSpecimensSquare(MappedNode node) {
    	return getColorForSpecimens(node.getAdditionalFields().getHasLarvalSpecimens(), node.getAdditionalFields().getLarvaePriority());
    }

    private Color getColorForAdultSpecimensSquare(MappedNode node) {
    	return getColorForSpecimens(node.getAdditionalFields().getHasPage(), node.getAdditionalFields().getAdultPriority());
    }

    private Color getColorForSpecimens(boolean hasSpecimens, int priority) {
    	if (hasSpecimens) {
    		return Color.blue.darker();
    	} else {
    		if (priority == AdditionalFields.HIGH_PRIORITY) {
    			return Color.red;
    		} else if (priority == AdditionalFields.MEDIUM_PRIORITY) {
    			return new Color(204, 10, 153);
    		} else {
    			return Color.pink;
    		}
    	}
    }

    private Color getColorForDNAPrioritySquare(MappedNode node) {
    	return getColorForPriority(node.getAdditionalFields().getDnaPriority());
    }

    private Color getColorForLarvaePrioritySquare(MappedNode node) {
    	return getColorForPriority(node.getAdditionalFields().getLarvaePriority());
    }

    private Color getColorForAdultPrioritySquare(MappedNode node) {
    	return getColorForPriority(node.getAdditionalFields().getAdultPriority());
    }

    private Color getColorForPriority(int priority) {
    	switch(priority) {
    		case AdditionalFields.HIGH_PRIORITY: return Color.black;
    		case AdditionalFields.MEDIUM_PRIORITY: return Color.darkGray.brighter().brighter();
    		default: return Color.lightGray;
    	}
    }

    private int getSpecimenBlockWidth() {
    	return 150;
    }

    protected int getHeaderPixels() {
    	return 15;
    }

    protected int getPanelWidth() {
    	int additionalWidth = getIncludeSpecimenInfo() ? getSpecimenBlockWidth() : 0;
    	return -1*minX + getTerminalTextOverrun() + getDefaultLineLength() + additionalWidth;
    }

    @SuppressWarnings("unchecked")
    private void iterateLabelPoints(Graphics g, Hashtable stringsToPoints, Color desiredFontColor) {
        Color currentColor = g.getColor();
        g.setFont(getFont());
        g.setColor(desiredFontColor);
        for (Iterator iter = stringsToPoints.keySet().iterator(); iter.hasNext();) {
            NodeView nextNodeView = (NodeView) iter.next();
            MappedNode nextNode = (MappedNode) nextNodeView.getNode();
            int terminalAdjustment = 0;
            boolean isTerminal = nextNodeView.getIsTerminal();
            if (isTerminal) {
            	// if they are terminals, get them a little more snug
            	terminalAdjustment = 2;
            }
            Point stringLoc = (Point) stringsToPoints.get(nextNodeView);
            if (getDrawNameInItalics(nextNode)) {
            	g.setFont(microsoftArialItalicFont);
            	// italic font indents things further to the right,
            	// so shift left one pixel to line up with non-italics
            	terminalAdjustment += 1;
            } else {
            	g.setFont(microsoftArialFont);
            }
            int confidenceHeightAdjustment = 0;
            int confidenceWidthAdjustment = 0;
            // if this is an internal incertae sedis node, adjust to line up with qmark
            if (!nextNodeView.getIsTerminal() && nextNode.getConfidence() == Node.INCERT_PUTATIVE) {
            	confidenceHeightAdjustment = singleQuestionMarkStringDimension.height / 2 - 1;
            	confidenceWidthAdjustment = singleQuestionMarkStringDimension.width + 5;
            }
            // string drawn here should actually be according to whether authority, italics, etc.
            g.drawString(nextNodeView.getNameString(), stringLoc.x - terminalAdjustment - confidenceWidthAdjustment, stringLoc.y + confidenceHeightAdjustment);

            int currentX = stringLoc.x - terminalAdjustment + getFontMetrics(g.getFont()).stringWidth(nextNodeView.getNameString());

            // reset font in case of authority or description
            g.setFont(microsoftArialFont);
            int stringPadding = DESCRIPTION_AUTHORITY_PADDING;
            // check to see if it has authority
            if (getDrawAuthorities() && StringUtils.notEmpty(nextNodeView.getAuthorityString())) {
            	// draw the authority
            	g.setColor(descriptionLightGray);
            	currentX += stringPadding;
            	g.drawString(nextNodeView.getAuthorityString(), currentX, stringLoc.y);
            	currentX += getFontMetrics(g.getFont()).stringWidth(nextNodeView.getAuthorityString());
            	g.setColor(desiredFontColor);
            }
            // check to see if it has a description
            if (getDrawDescriptions() && isTerminal && StringUtils.notEmpty(nextNode.getDescription())
            		&& !"0".equals(nextNode.getDescription())) {
            	// draw the description
            	g.setColor(descriptionLightGray);
            	if (nextNode.getExtinct() == Node.EXTINCT) {
					currentX += extinctImageWidth + EXTINCT_IMAGE_PADDING;
            	}
            	currentX += stringPadding;
            	g.drawString(nextNode.getDescription(), currentX, stringLoc.y);
            	g.setColor(desiredFontColor);
            }
        }
        g.setColor(currentColor);
    }

    protected boolean getDrawNameInItalics(MappedNode node) {
    	if (node.getHasSupertitle()) {
    		return ((MappedOtherName) node.getFirstPreferredOtherName()).getItalicize();
    	} else {
    		return node.getItalicizeName();
    	}
    }

    /**
     * Added on to the list of ISPU nodes since we don't want them appearing in the
     * regular tree
     * @param childNodeView The view for the ISPU node
     * @param parentNodeView Ignored for these purposes
     */
    @SuppressWarnings("unchecked")
    protected void addISPUNodeView(NodeView childNodeView, NodeView parentNodeView, Stack nodeViewStack) {
    	//parentNodeView.addAsFirstChild(childNodeView);
    	ispuNodeViews.add(childNodeView);
    	NodeView rootNodeView = (NodeView) nodeToNodeView.get(getRootNode());
    	childNodeView.setParent(rootNodeView);
    }

    @SuppressWarnings("unchecked")
    protected void addToMonophylyUncertainRects(Rectangle rect, Node node) {
   		monophylyUncertainRects.add(rect);
   		if (node.getConfidence() != Node.INCERT_OFF) {
   			confidenceMonophlyUncertainRects.add(rect);
   		}
    }

    @SuppressWarnings("unchecked")
    protected void addToNotMonophylecticRects(Rectangle rect, Node node) {
   		notMonophylecticRects.add(rect);
   		if (node.getConfidence() != Node.INCERT_OFF) {
   			confidenceNotMonophyleticRects.add(rect);
   		}
    }

    /**
     * Used to place various drawing coordinates related to confidence drawing
     * including making the line dotted, and adding question marks
     * @param currentNode
     * @param yLoc
     * @param horizLineEndX
     * @param currentX
     */
    @SuppressWarnings("unchecked")
    protected void handleConfidenceLocations(Node currentNode, int yLoc, int horizLineEndX, int currentX) {
    	int additionalIspuPixels = 13;
		int leftPadding = currentNode.getConfidence() == Node.INCERT_PUTATIVE ? 5 : additionalIspuPixels;
    	int width = horizLineEndX - currentX - X_PADDING + leftPadding;
    	int qmarkPadding = 5;
		// add the question mark close to the edge of the rectangle
		// 4 pixels is all the rectangle that is needed to draw on the right side
		// 10 pixels is all the rectangle that is needed to draw on the left, so
		// add the clear rect accordingly
		Rectangle newRect = new Rectangle(currentX - leftPadding, yLoc-2 , width, 5);
		int nodePhylesis = currentNode.getPhylesis();
		confidenceEmptyRects.add(newRect);
		if (nodePhylesis == Node.NOT_MONOPHYLETIC) {
			confidenceNotMonophyleticRects.add(newRect);
		} else if (nodePhylesis == Node.MONOPHYLY_UNCERTAIN) {
			confidenceMonophlyUncertainRects.add(newRect);
		}
		confidenceSingleQmarkPoints.add(new Point(newRect.x + width - qmarkPadding - 1, newRect.y + 1));
    }

    public void rebuildTree() {
        nodeToNodeView.clear();
        nodeViewsToLabelPoints.clear();
        pagedNodeViewsToPoints.clear();
        monophylyUncertainRects.clear();
        notMonophylecticRects.clear();
    	confidenceNotMonophyleticRects.clear();
    	confidenceMonophlyUncertainRects.clear();
        currentMaxTerminalTextOverrun = 0;
        maxTerminalX = 0;
        ispuNodeViews.clear();
        super.rebuildTree();
    }

    /**
     * overridden to return the width of the longest
     * description or authority for a terminal taxon
     * in this particular tree image (used for
     * calculating the panel's dimensions)
     */
    protected int getTerminalTextOverrun() {
    	return currentMaxTerminalTextOverrun;
    }

    private Point getStringLoc(NodeView nodeView) {
        int labelX, labelY ;
        if (!nodeView.isTerminal()) {
            int labelWidth = getStringWidthForNodeView(nodeView);
            labelX = nodeView.getX() - labelWidth + 1;
            labelY = nodeView.getY();
            nodeView.getPanel().getHalfCircleDiameter();
        } else {
            labelX = nodeView.getX() + 2*X_PADDING + getHalfCircleDiameter();
            labelY = nodeView.getY() + 8;
            if (nodeView.getNode().getTermWithSubTree()) {
                labelX += AbstractTreePanel.getSubtreeImageWidth() + X_PADDING;
            }
        }
        return new Point(labelX, labelY);
    }

    private int getStringWidthForNodeView(NodeView view) {
    	FontMetrics metrics = getDrawNameInItalics((MappedNode)view.getNode()) ? getFontMetrics(microsoftArialItalicFont) : getFontMetrics(microsoftArialFont);
        return metrics.stringWidth(getTreeStringForNodeView(view));
    }

    /**
     *  In the context of the tree drawing, we either want:
     *	1) the node name or
     *	2) the name of the supertitle
     * @param view
     * @return
     */
    private String getTreeStringForNodeView(NodeView view) {
    	MappedNode node = (MappedNode) view.getNode();
    	if (node.getHasSupertitle()) {
    		return node.getFirstPreferredOtherName().getName();
    	} else {
    		return node.getName();
    	}
    }

    protected int getStepX() {
    	return getDefaultLineLength();
    }

    protected int getHorizlineEndX(NodeView view) {
    	return view.getX() + getCircleDiameter() / 2;
    }

    /**
     * Overridden to place ispu nodes at the bottom of the tree
     */
    @SuppressWarnings("unchecked")
    protected void placeIspuNodes() {
    	int index = 0;
    	// reverse these guys because they are iterated in reverse order in the superclass
    	List reverseIspuViews = new ArrayList(ispuNodeViews);
    	Collections.reverse(reverseIspuViews);
    	for (Iterator iter = reverseIspuViews.iterator(); iter.hasNext();) {
			NodeView nextIspuView = (NodeView) iter.next();
			ypos += getYStep();
			nextIspuView.setY(ypos);
			index++;
		}
    }

    /**
     * Function that places all visible textFields on the screen then launches a thread to create and place
     * all the non-visible ones.  Also places all image icons.
     */
    @SuppressWarnings("unchecked")
    protected void placeTextFields() {
        for (Iterator iter = nodeViews.iterator(); iter.hasNext();) {
            NodeView nextView = (NodeView) iter.next();
            if (!nextView.getIsRootView() && StringUtils.notEmpty(nextView.getNode().getName())) {
                Point stringLoc = getStringLoc(nextView);
                MappedNode nextNode = (MappedNode) nextView.getNode();
                Point nextStringPoint = getStringLoc(nextView);
                if (nextNode.getHasPage()) {
                    pagedNodeViewsToPoints.put(nextView, nextStringPoint);
                } else {
                    nodeViewsToLabelPoints.put(nextView, nextStringPoint);
                }
            	boolean italicizeName = getDrawNameInItalics(nextNode);
            	Font fontToCheck = italicizeName ? microsoftArialItalicFont : microsoftArialFont;
                String nameString = getTreeStringForNodeView(nextView);
                nextView.setNameString(nameString);
                // calculate some width and location info about descriptions
                // and possibly authorities
                if (nextView.getIsTerminal()) {
	                int nextTextOverrun = 0;
	                int currentX = stringLoc.x - TERMINAL_ADJUSTMENT + getFontMetrics(fontToCheck).stringWidth(nameString);
	                int standardEndX = currentX;
	                if (currentX > maxTerminalX) {
	                	// store this for specimen boxes
	                	maxTerminalX = currentX;
	                }
	                if (nextNode.getExtinct() == Node.EXTINCT) {
	                	currentX += extinctImageWidth + EXTINCT_IMAGE_PADDING;
	                }
	                int stringPadding = DESCRIPTION_AUTHORITY_PADDING;
	                // check to see if it has authority
	                if (getDrawAuthorities() && nextNode.getShowAuthorityInContainingGroup()) {
	                	// draw the authority
	                	String authString;
	                	if (nextNode.getHasSupertitle()) {
	                		authString = nextNode.getSupertitle().getAuthority();
	                		Integer authYear = nextNode.getSupertitle().getAuthorityYear();
	                		authString += " " + ((authYear != null) ? authYear.toString() : "");
	                	} else {
	                		authString = nextNode.getNameAuthority();
	                		Integer authYear = nextNode.getAuthorityDate();
	                		authString += " " + ((authYear != null) ? authYear.toString() : "");
	                	}
	                	currentX += stringPadding;
	                	currentX += getFontMetrics(microsoftArialFont).stringWidth(authString);
	                	nextView.setAuthorityString(authString);
	                }
	                // check to see if it has a description
	                if (getDrawDescriptions() && StringUtils.notEmpty(nextNode.getDescription())) {
	                	currentX += stringPadding;
	                	currentX += getFontMetrics(microsoftArialFont).stringWidth(nextNode.getDescription());
	                }
	                nextTextOverrun = currentX - standardEndX;
	                // if our particular case is wider than any yet seen,
	                // store our value as the widest
	                if (nextTextOverrun > currentMaxTerminalTextOverrun) {
	                	currentMaxTerminalTextOverrun = nextTextOverrun;
	                }
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    public String getLinkCoords(MappedPage page) {
        FontMetrics fm = getFontMetrics();
        String returnString = "";
        for (Iterator iter = pagedNodeViewsToPoints.keySet().iterator(); iter.hasNext();) {
            NodeView nextNodeView = (NodeView) iter.next();
            int width = getStringWidthForNodeView(nextNodeView);
            int height = fm.getHeight();
            Point startPoint = (Point) pagedNodeViewsToPoints.get(nextNodeView);
            returnString += getLinkAreaString(nextNodeView, startPoint, width, height) + "\n";
        }
        // loop through the extinct icons
        for (Iterator iter = extinctIndicators.iterator(); iter.hasNext();) {
            Point nextExtinctPoint = (Point) iter.next();
            returnString += getExtinctAreaString(nextExtinctPoint) + "\n";
        }
        for (Iterator iter = notMonophylecticRects.iterator(); iter.hasNext();) {
            Rectangle nextRect = (Rectangle) iter.next();
			if (!confidenceMonophlyUncertainRects.contains(nextRect) &&
					!confidenceNotMonophyleticRects.contains(nextRect)) {
				returnString += getNotMonophyleticAreaString(nextRect);
			}
        }
        for (Iterator iter = monophylyUncertainRects.iterator(); iter.hasNext();) {
            Rectangle nextRect = (Rectangle) iter.next();
			if (!confidenceMonophlyUncertainRects.contains(nextRect) &&
					!confidenceNotMonophyleticRects.contains(nextRect)) {
				returnString += getMonophylyUncertainAreaString(nextRect);
			}
        }
        for (Iterator iter = confidenceEmptyRects.iterator(); iter.hasNext();) {
			Rectangle nextRect = (Rectangle) iter.next();
			if (!confidenceMonophlyUncertainRects.contains(nextRect) &&
					!confidenceNotMonophyleticRects.contains(nextRect)) {
				returnString += getConfidenceUncertainAreaString(nextRect);
			}
		}
        for (Iterator iter = confidenceMonophlyUncertainRects.iterator(); iter.hasNext();) {
			Rectangle nextRect = (Rectangle) iter.next();
			returnString += getConfidenceMonoUncertainAreaString(nextRect);
		}
        for (Iterator iter = confidenceNotMonophyleticRects.iterator(); iter.hasNext();) {
			Rectangle nextRect = (Rectangle) iter.next();
			returnString += getConfidenceNotMonoAreaString(nextRect);
		}

        Object[] nameAndId = getPageDAO().getGroupNameAndNodeIdForPage(page.getParentPageId());
        // don't want to do it for life on earth!
        if (nameAndId != null) {
	        String url = getUrlBuilder().getURLForBranchPage(URLBuilder.NO_HOST_PREFIX, (String) nameAndId[0], (Long) nameAndId[1]);
	        String parentGroupName = (String) nameAndId[0];
	        // add the root rect
	        String parentArrowAreaString = getAreaBeginningString(rootRectangle.x, rootRectangle.y, rootRectangle.x + rootRectangle.width, rootRectangle.y + rootRectangle.height);
	        parentArrowAreaString += " href=\"" + url + "\" alt=\"[down<--]" + parentGroupName + "\" title=\"" + parentGroupName + "\">" + "\n";
	        returnString += parentArrowAreaString;
        }
        return returnString;
    }

    protected Color getColorForNode(Node node) {
    	MappedNode coloredNode = (MappedNode) node;
    	//boolean hasPage = coloredNode.getHasPage();
    	boolean leadsToCompletePage = false;
    	// if it has a page, check to see if the page leads to a complete page
    	/*if (hasPage) {
    		Long pageId = getPageDAO().getPageIdForNode(coloredNode);
    		leadsToCompletePage = getPageDAO().getPageLeadsToCompletePage(pageId);
    	}*/
    	boolean isTrunkNode = coloredNode.getTrunkNode() == Node.TRUNK_NODE;
		if (getTrunkColoringEnabled() && isTrunkNode){
			return trunkColor;
    	} else if (leadsToCompletePage && !(coloredNode.getNodeId().equals(((MappedNode) getRootNode()).getNodeId()))) {
			return leadsToComplete;
		} else {
			return getIsBlackLines() ? Color.black : getLightGrayColor();
		}
    }

    /**
     * Overridden to get color based on the status of the page
     * @param view
     * @return
     */
    protected boolean getIsBlackLine(NodeView view) {
        return getIsBlackLines();
    }
    protected Color getLightGrayColor() {
    	return lightGray;
    }

    /**
     * Overridden to do nothing since we don't want node circles on these trees
     * @param circleValues
     * @param repaintRect
     * @param g
     */
    @SuppressWarnings("unchecked")
    protected void conditionallyRepaintCircles(ArrayList circleValues, Rectangle repaintRect, Graphics g) {
    }

    private String getExtinctAreaString(Point point) {
        String returnString = getAreaBeginningString(point.x, point.y, point.x + extinctImageWidth, point.y + extinctImageHeight);
        return returnString +
            "href=\"/tree/home.pages/treeinterpret.html#extinct\" alt=\"extinct icon\" onmouseover=\"doTooltip(event,extinct_tooltip)\" onmouseout=\"if(hideTip!=null) hideTip()\">";
    }

    private String getMonophylyUncertainAreaString(Rectangle rect) {
        String returnString = getAreaBeginningString(rect);
        return returnString + "href=\"/tree/home.pages/treeinterpret.html#monounc\" alt=\"Monophyly Uncertain\" onmouseover=\"doTooltip(event,monophyly_uncertain_tooltip)\" onmouseout=\"if(hideTip!=null) hideTip()\">";
    }

    private String getNotMonophyleticAreaString(Rectangle rect) {
        String returnString = getAreaBeginningString(rect);
        return returnString + "href=\"/tree/home.pages/treeinterpret.html#nonmono\" alt=\"Not Monophyletic\" onmouseover=\"doTooltip(event, not_monophyletic_tooltip)\" onmouseout=\"if(hideTip!=null) hideTip()\">";
    }
	private String getConfidenceUncertainAreaString(Rectangle rect) {
    	String returnString = getAreaBeginningString(rect);
    	//href="/tree/home.pages/treeinterpret.html#nonmono" alt="Phylogenetic position of group is uncertain" onmouseover="doTooltip(event, incert_tooltip)" onmouseout="if(hideTip!=null) hideTip()"
    	return returnString + "href=\"/tree/home.pages/treeinterpret.html#incertae\" alt=\"Phylogenetic position of group is uncertain\" onmouseover=\"doTooltip(event, incert_tooltip)\" onmouseout=\"if(hideTip!=null) hideTip()\">";
    }
	private String getConfidenceNotMonoAreaString(Rectangle rect) {
		String returnString = getAreaBeginningString(rect);
		return returnString + "href=\"/tree/home.pages/treeinterpret.html#nonmono\" alt=\"Phylogenetic position of group is uncertain and group is not monophyletic\" onmouseover=\"doTooltip(event, incert_not_monophyletic_tooltip)\" onmouseout=\"if(hideTip!=null) hideTip()\">";
	}
	private String getConfidenceMonoUncertainAreaString(Rectangle rect) {
		String returnString = getAreaBeginningString(rect);
		return returnString + "href=\"/tree/home.pages/treeinterpret.html#monounc\" alt=\"Phylogenetic position of group is uncertain and monophyly of group is uncertain\" onmouseover=\"doTooltip(event, incert_monophyly_uncertain_tooltip)\" onmouseout=\"if(hideTip!=null) hideTip()\">";

	}
	private String getAreaBeginningString(Rectangle rect) {
		return getAreaBeginningString(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
	}
    private String getAreaBeginningString(int startX, int startY, int endX, int endY) {
        return "<area coords=\"" + startX + "," + startY + "," +
            endX + "," + endY + "\"";
    }

    private String getLinkAreaString(NodeView view, Point startPoint, int width, int height) {
        String treeString = getTreeStringForNodeView(view);
        Long nodeId = ((MappedNode) view.getNode()).getNodeId();
        String returnString = getAreaBeginningString(startPoint.x, startPoint.y, startPoint.x + width, startPoint.y - height);
        String urlString = getUrlBuilder().getURLForBranchPage(URLBuilder.NO_HOST_PREFIX, treeString, nodeId);
        returnString += "href=\"" + urlString + "\" alt=\"[up-->]" + treeString +
            "\" title=\"" + treeString + "\">";
        return returnString;
    }

    protected int getYStep() {
        return (int)(myFontMetrics.getHeight()*1.3);
    }

    public int getDefaultLineLength() {
        return getDefaultStringWidth();
    }

    public int getDefaultStringWidth() {
        return myFontMetrics.stringWidth("     ");
    }

    protected int calculateRootOverrun(NodeView rootView) {
        return 0;
    }

    protected void calculateRootLineLength(int rootOverrun) {
        rootLineLength = getDefaultLineLength() - getRootLineLessPixels();
    }

    protected int getRootLineLessPixels() {
    	return 6;
    }
	protected Color getQMarkFontColor() {
		return Color.black;
	}
	protected Font getQuestionMarkFont() {
		return microsoftArialFont;
	}

    /** Invoked when the mouse button has been clicked (pressed
     * and released) on a component.
     *
     */
    public void mouseClicked(MouseEvent e) {
    }

    /** Invoked when the mouse enters a component.
     *
     */
    public void mouseEntered(MouseEvent e) {
    }

    /** Invoked when the mouse exits a component.
     *
     */
    public void mouseExited(MouseEvent e) {
    }

    /** Invoked when a mouse button has been pressed on a component.
     *
     */
    public void mousePressed(MouseEvent e) {
    }

    /** Invoked when a mouse button has been released on a component.
     *
     */
    public void mouseReleased(MouseEvent e) {
    }

    /**
     * @return Returns the isBlack.
     */
    public boolean getIsBlackLines() {
        return isBlackLines;
    }

    /**
     * @param isBlack The isBlack to set.
     */
    public void setIsBlackLines(boolean isBlack) {
        this.isBlackLines = isBlack;
    }

	/**
	 * @return Returns the pageDAO.
	 */
	public PageDAO getPageDAO() {
		return pageDAO;
	}

	/**
	 * @param pageDAO The pageDAO to set.
	 */
	public void setPageDAO(PageDAO pageDAO) {
		this.pageDAO = pageDAO;
	}

	public boolean getDrawDescriptions() {
		return drawDescriptions;
	}

	public void setDrawDescriptions(boolean drawDescriptions) {
		this.drawDescriptions = drawDescriptions;
	}
	public boolean getDrawAuthorities() {
		return drawAuthorities;
	}

	public void setDrawAuthorities(boolean drawAuthorities) {
		this.drawAuthorities = drawAuthorities;
	}
	public boolean getIncludeSpecimenInfo() {
		return includeSpecimenInfo;
	}

	public void setIncludeSpecimenInfo(boolean includeSpecimenInfo) {
		this.includeSpecimenInfo = includeSpecimenInfo;
	}

	public URLBuilder getUrlBuilder() {
		return urlBuilder;
	}

	public void setUrlBuilder(URLBuilder urlBuilder) {
		this.urlBuilder = urlBuilder;
	}

	@SuppressWarnings("unchecked")
	public void constructLocations() {
		super.constructLocations();

        // Add all the circles and lines to our arrays
        Iterator it = nodeViews.iterator();
        while (it.hasNext()) {
            NodeView currentView = (NodeView)it.next();
            Node currentNode = currentView.getNode();

            int yLoc = currentView.getY() + getHalfCircleDiameter();
            int horizLineStartX;
            if (currentView.getIsRootView()) {//root
                horizLineStartX = currentView.getX() - rootLineLength;
            } else {  //not the root
                horizLineStartX = currentView.getParent().getX()+ getHalfCircleDiameter();
            }

            boolean notPhylesis = currentNode.getPhylesis() != Node.MONOPHYLETIC;
            boolean isTrunkNode = currentNode.getTrunkNode() == Node.TRUNK_NODE;

            // determine lines to draw
            if (notPhylesis && isTrunkNode) {
	            // Connect the vertical line a little further by drawing a small horizontal one
	            trunkVertLineList.add(new int[] {horizLineStartX, yLoc+1, horizLineStartX+1, yLoc+1});
            }

            if (!currentView.isTerminal() && isTrunkNode) {
                //vertical lines
                ArrayList children = currentView.getChildren();
                Iterator childIter = children.iterator();

                while(childIter.hasNext()) {
                	NodeView childCurrView = (NodeView)childIter.next();

                	boolean childIsTrunk = childCurrView.getNode().getTrunkNode() == Node.TRUNK_NODE;
                	if (childIsTrunk) {
                		int x = currentView.getX() + getHalfCircleDiameter();
                		int y1 = childCurrView.getY() + getHalfCircleDiameter();
                		int y2 = currentView.getY() + getHalfCircleDiameter();
                        List vertLineList = trunkVertLineList;
                        vertLineList.add(new int[] {x, y1 , x, y2});
                        vertLineList.add(new int[] {x+1, y1 , x+1, y2});
                	}
                }
            }

        }
	}

	public boolean getTrunkColoringEnabled() {
		return trunkColoringEnabled;
	}

	public void setTrunkColoringEnabled(boolean trunkColoringEnabled) {
		this.trunkColoringEnabled = trunkColoringEnabled;
	}
	public Color getTrunkColor() {
		return trunkColor;
	}
	public void setTrunkColor(Color trunkColor) {
		this.trunkColor = trunkColor;
	}
}


text:
package com.jnape.palatable.lambda.semigroup.builtin;

import com.jnape.palatable.lambda.adt.Either;
import com.jnape.palatable.lambda.semigroup.Semigroup;
import org.junit.Test;

import static com.jnape.palatable.lambda.adt.Either.left;
import static com.jnape.palatable.lambda.adt.Either.right;
import static com.jnape.palatable.lambda.monoid.builtin.Join.join;
import static com.jnape.palatable.lambda.semigroup.builtin.Merge.merge;
import static org.junit.Assert.assertEquals;

public class MergeTest {

    @Test
    public void semigroup() {
        Semigroup<String>  join = join();
        Semigroup<Integer> add  = Integer::sum;

        Semigroup<Either<String, Integer>> merge = merge(join, add);
        assertEquals(left("onetwo"), merge.apply(left("one"), left("two")));
        assertEquals(right(3), merge.apply(right(1), right(2)));
        assertEquals(left("foo"), merge.apply(left("foo"), right(2)));
        assertEquals(left("foo"), merge.apply(right(2), left("foo")));
    }
}


text:
package com.quollwriter.ui.components;

import java.awt.*;

import javax.swing.*;
import javax.swing.border.*;

public class Header extends Box
{

    // orig: public static Color defaultPaintLeftColor = new Color (112, 149, 226);
    public static Color defaultPaintLeftColor = UIUtils.getColor ("#516CA3");

    // public static Color defaultPaintLeftColor = new Color (77, 122, 244);
    public static Color  defaultPaintRightColor = null;
    public static Insets defaultPadding = new Insets (3,
                                                      3,
                                                      3,
                                                      3);

    /*
    public static Font defaultFont = new Font ("Tahoma",
                                               Font.BOLD,
                                               12);
     */
    public static Color defaultTitleColor = Color.WHITE;

    private JLabel        label = null;
    private PaintProvider paintProvider = null;
    private Component     controls = null;

    public Header(String    title,
                  Icon      icon,
                  Component controls)
    {

        this ();

        this.setTitle (title);
        this.setIcon (icon);

        this.setControls (controls);

    }

    public Header()
    {

        super (BoxLayout.LINE_AXIS);

        this.label = new JLabel ();

        this.label.setAlignmentY (Component.TOP_ALIGNMENT);
        this.label.setOpaque (false);
        //this.label.setVerticalAlignment (SwingConstants.TOP);

        //this.label.setVerticalTextPosition (SwingConstants.TOP);

        this.add (this.label);
        this.add (Box.createHorizontalGlue ());

        this.paintProvider = new GradientPainter (Header.defaultPaintLeftColor,
                                                  Header.defaultPaintRightColor);

        this.setPadding (Header.defaultPadding);

        Font f = this.getFont ().deriveFont (Font.BOLD,
                                             14);

        this.setFont (f);
        this.setTitleColor (Header.defaultTitleColor);

    }

    @Override
    public void setTransferHandler (TransferHandler h)
    {

        this.label.setTransferHandler (h);

    }

    public void setLabel (JLabel l)
    {

        this.label = l;
        this.label.setOpaque (false);

        this.remove (0);

        this.add (this.label,
                  0);

        this.validate ();
        this.repaint ();

    }

    public Component getControls ()
    {

        return this.controls;

    }

    public void setControls (Component c)
    {

        if (c == null)
        {

            return;

        }

        if (c instanceof JComponent)
        {

            ((JComponent) c).setAlignmentY (Component.TOP_ALIGNMENT);

        }

        int ind = -1;

        if (this.controls != null)
        {

            for (int i = 0; i < this.getComponentCount (); i++)
            {

                if (this.getComponent (i) == this.controls)
                {

                    ind = i;

                    break;

                }

            }

        }

        if (ind > -1)
        {

            this.remove (ind);

            this.add (c,
                      ind);

        } else
        {

            this.add (c);

        }

        this.controls = c;

        this.validate ();
        this.repaint ();

    }

    public JLabel getLabel ()
    {

        return this.label;

    }

    public void setPadding (Insets i)
    {

        if (i == null)
        {

            this.setBorder (null);

            return;

        }

        this.setBorder (new EmptyBorder (i));

    }

    public Header getClone (String    title,
                            Icon      icon,
                            Component controls)
    {

        Header n = new Header (title,
                               icon,
                               controls);

        n.setTitleColor (this.label.getForeground ());
        n.setPaintProvider (this.getPaintProvider ().getClone ());
        n.setFont (this.label.getFont ());

        return n;

    }

    public Dimension getMaximumSize ()
    {

        return new Dimension (Short.MAX_VALUE,
                              this.getPreferredSize ().height);

    }

    public Dimension getMinimumSize ()
    {

        return new Dimension (this.label.getPreferredSize ().width + 5 + ((this.controls != null) ? this.controls.getMinimumSize ().width : 0),
                              this.getPreferredSize ().height);

    }

    public PaintProvider getPaintProvider ()
    {

        return this.paintProvider;

    }

    public void setPaintProvider (PaintProvider p)
    {

        this.paintProvider = p;

    }

    public String getTitle ()
    {

        return this.label.getText ();

    }

    public Icon getIcon ()
    {

        return this.label.getIcon ();

    }

    public void setIcon (Icon i)
    {

        this.label.setIcon (i);

    }

    public void setTitleColor (Color c)
    {

        this.label.setForeground (c);

    }

    public void setTitle (String t)
    {

        this.label.setText (String.format ("<html>%s</html>",
                                           com.quollwriter.Environment.replaceObjectNames (t)));

    }

    public Font getFont ()
    {

        return this.label.getFont ();

    }

    public void setFont (Font f)
    {

        this.label.setFont (f);

    }

    public void setFontSize (float i)
    {

        this.label.setFont (this.label.getFont ().deriveFont (i));

    }

    public void setBold (boolean b)
    {

        this.label.setFont (this.label.getFont ().deriveFont ((b ? Font.BOLD : Font.PLAIN)));

    }

    protected void paintComponent (Graphics g)
    {

        if (this.paintProvider != null)
        {

            Paint p = this.paintProvider.getPaint (this);

            Graphics2D g2d = (Graphics2D) g;

            int w = this.getWidth ();
            int h = this.getHeight ();

            g2d.setPaint (p);
            g2d.fillRect (0,
                          0,
                          w,
                          h);

            this.setOpaque (false);

        }

        super.paintComponent (g);

        //this.setOpaque (true);

    }

    public static Header createBoldSubHeader (String    title,
                                              ImageIcon icon)
    {

        Header h = new Header (title,
                               ((icon == null) ? null : icon),
                               null);

        h.setFont (h.getFont ().deriveFont (Font.BOLD,
                                            12f));
        // h.setTitleColor (Color.BLACK);
        // h.setOpaque (false);
        // h.setBackground (new Color (0, 0, 0, 0));
        // h.setPaintProvider (null);

        h.setAlignmentX (Component.LEFT_ALIGNMENT);

        h.setBorder (new EmptyBorder (3,
                                      3,
                                      3,
                                      3));

        return h;

    }

}


text:
import logging
from savu.plugins.base_recon import BaseRecon
from savu.data.plugin_info import CitationInfomration
from savu.plugins.driver.cpu_plugin import CpuPlugin

import skimage.transform as transform
import numpy as np
from scipy import ndimage

from savu.plugins.utils import register_plugin

@register_plugin
class ScikitimageFilterBackProjection(BaseRecon, CpuPlugin):
    """
    A Plugin to reconstruct an image by filter back projection
    using the inverse radon transform from scikit-image.

    :param output_size: Number of rows and columns in the
    reconstruction. Default: None.
    :param filter: Filter used in frequency domain filtering
    Ramp filter used by default. Filters available: ramp, shepp-logan,
    cosine, hamming, hann. Assign None to use no filter. Default: 'ramp'.
    :param interpolation: interpolation method used in reconstruction.
    Methods available: 'linear', 'nearest', and 'cubic' ('cubic' is slow).
    Default: 'linear'.
    :param circle: Assume the reconstructed image is zero outside the inscribed
    circle. Also changes the default output_size to match the behaviour of
    radon called with circle=True. Default: False.
    """

    def __init__(self):
        logging.debug("initialising Scikitimage Filter Back Projection")
        logging.debug("Calling super to make sure that all superclasses are " +
                      " initialised")
        super(ScikitimageFilterBackProjection,
              self).__init__("ScikitimageFilterBackProjection")

    def _shift(self, sinogram, centre_of_rotation):
        centre_of_rotation_shift = (sinogram.shape[0]/2) - centre_of_rotation
        return ndimage.interpolation.shift(sinogram,
                                           centre_of_rotation_shift)

    def reconstruct(self, sinogram, centre_of_rotation,
                    angles, shape, center):
        print sinogram.shape
        sinogram = np.swapaxes(sinogram, 0, 1)
        sinogram = self._shift(sinogram, centre_of_rotation)
        sino = np.nan_to_num(sinogram)
        theta = np.linspace(0, 180, sinogram.shape[1])
        result = \
            transform.iradon(sino, theta=theta,
                             output_size=(sinogram.shape[0]),
                             # self.parameters['output_size'],
                             filter='ramp',  # self.parameters['filter'],
                             interpolation='linear',
                             # self.parameters['linear'],
                             circle=False)  # self.parameters[False])
        return result

    def get_citation_information(self):
        cite_info = CitationInformation()
        cite_info.description = \
            ("The Tomographic reconstruction performed in this processing " +
             "chain is derived from this work.")
        cite_info.bibtex = \
            ("@book{avinash2001principles,\n" +
             " title={Principles of computerized tomographic imaging},\n" +
             " author={Kak, Avinash C. and Slaney, Malcolm},\n" +
             " year={2001},\n" +
             " publisher={Society for Industrial and Applied Mathematics}\n" +
             "}")
        cite_info.endnote = \
            ("%0 Book\n" +
             "%T Principles of computerized tomographic imaging\n" +
             "%A Kak, Avinash C.\n" +
             "%A Slaney, Malcolm\n" +
             "%@ 089871494X\n" +
             "%D 2001\n" +
             "%I Society for Industrial and Applied Mathematics")
        cite_info.doi = "http://dx.doi.org/10.1137/1.9780898719277"
        return cite_info


text:
// Dstl (c) Crown Copyright 2017
package uk.gov.dstl.baleen.annotators.regex;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.uima.UimaContext;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.resource.ResourceInitializationException;

import com.google.common.collect.ImmutableSet;

import uk.gov.dstl.baleen.core.pipelines.orderers.AnalysisEngineAction;
import uk.gov.dstl.baleen.core.utils.ConfigUtils;
import uk.gov.dstl.baleen.types.geo.Coordinate;
import uk.gov.dstl.baleen.uima.BaleenTextAwareAnnotator;
import uk.gov.dstl.baleen.uima.data.TextBlock;

/**
 * Annotate Latitude-Longitude coordinates in decimal (DD) and degrees-minutes-seconds (DMS) format
 * using regular expressions.
 *
 *
Decimal degree (DD)
 *
 *
The document content is run through a regular expression matcher looking for
 * latitude-longitude pairs in DD (e.g. 51.068787 -1.794472 or 51.068787° -1.794472° or 51.068787°N
 * 1.794472°W). If the minimum number of decimal places required is 0, the following regular
 * expressions are used:
 *
 *
(-?\\d{1,3}(\\.\\d+)?)(,\\h*|\\h+)(-?\\d{1,3}(\\.\\d+)?)

 *
 *
(-?\\d{1,3}(\\.\\d+)?)°(,\\h*|\\h+)(-?\\d{1,3}(\\.\\d+)?)°

 *
 *
\\b(\\d{1,3}(\\.\\d+)?)°( )?([NSEW])(,\\h*|\\h+)(\\d{1,3}(\\.\\d+)?)°( )?([NSEW])

 *
 *
If the minimum number of decimal places required is greater than 0, the following regular
 * expressions are used where x is the minimum number of decimal places:
 *
 *
(-?\\d{1,3}(\\.\\d{x,}))(,\\h*|\\h+)(-?\\d{1,3}(\\.\\d{x,}))

 *
 *
(-?\\d{1,3}(\\.\\d{x,}))°(,\\h*|\\h+)(-?\\d{1,3}(\\.\\d{x,}))°

 *
 *
\\b(\\d{1,3}(\\.\\d{x,}))°( )?([NSEW])(,\\h*|\\h+)(\\d{1,3}(\\.\\d{x,}))°( )?([NSEW])

 *
 *
The latitude and longitude are extracted (optionally the user can specify it should be
 * longitude and latitude instead) and a GeoJSON object is built representing this location.
 *
 *
Coordinates that are preceded by a £, $ or € symbol are skipped as they are assumed to be
 * monetary values rather than coordinates (e.g. £3,000).
 *
 *
The regular expressions used when searching for Digital Degree formats that use the minus sign
 * for southern and western hemispheres do not include word boundaries when looking for matches
 * because this can cause the expression to fail to extract a first negative sign. This means the
 * annotator will extract, for example, currency strings (e.g. $40,000).
 *
 *
Degrees-minutes-seconds (DMS)
 *
 *
The document content is run through a regular expression matcher looking for
 * latitude-longitude pairs in DMS format (e.g. 51°4'7.6332"N 1°47'40.0992"W) that match the
 * following regular expression:
 *
 *

 * \\b(\\d{1,3})°(\\d{1,2})'(\\d{1,2}(\\.\\d*)?)\"([NSEW])[,/\\h]*(\\d{1,3})°(\\d{1,2})'(\\d{1,2}(\\.\\d*)?)\"([NSEW])\\b
 *

 *
 *
A similar regex is used to find pairs that have spaces instead of symbols in them (e.g. 10 12
 * 14 N, 11 13 15 E), and another regex to find pairs with no spaces.
 *
 *
The following regexes are also used to pick up other formats:
 *
 *

 *

 *

 *       \\b(lat|latitude)\\h*(\\d{1,2})°\\h*(\\d{1,2}(\\.\\d+)?)'(\\h*(\\d{1,2}(\\.\\d+)?)\")?\\h*([NS])\\.?,?\\h*(lon|long|longitude)\\h*(\\d{1,3})°\\h*(\\d{1,2}(\\.\\d+)?)'(\\h*(\\d{1,2}(\\.\\d+)?)\")?\\h*([EW])\\b
 *

 *

 *

 *       \\b(lat|latitude)\\h*(\\d{1,2})°\\h*(\\d{1,2})'\\.(\\d+)\\h*([NS])\\.?,?\\h*(lon|long|longitude)\\h*(\\d{1,3})°\\h*(\\d{1,2})'\\.(\\d+)\\h*([EW])\\b
 *

 *

 *
 *
Some validation is done on the extracted text, then the latitude and longitude are extracted
 * and a GeoJSON object is built representing this location.
 *
 * @baleen.javadoc
 */
public class LatLon extends BaleenTextAwareAnnotator {

  private final Pattern llDMSPattern =
      Pattern.compile(
          "\\b(\\d{1,3})°(\\d{1,2})'(\\d{1,2}(\\.\\d+)?)\"([NSEW])[,/\\h]*(\\d{1,3})°(\\d{1,2})'(\\d{1,2}(\\.\\d+)?)\"([NSEW])\\b");
  private final Pattern llDMSSpacePattern =
      Pattern.compile(
          "\\b(\\d{1,3}) (\\d{1,2}) (\\d{1,2}(\\.\\d+)?) ([NSEW])[,/\\h]*(\\d{1,3}) (\\d{1,2}) (\\d{1,2}(\\.\\d+)?) ([NSEW])\\b");
  private final Pattern llDMSNumericPattern =
      Pattern.compile(
          "\\b(\\d{2,3})(\\d{2})(\\d{2})?( )?([NSEW])[,/\\h]*(\\d{2,3})(\\d{2})(\\d{2})?( )?([NSEW])\\b");
  private final Pattern llDMSPunctuationPattern =
      Pattern.compile(
          "\\b(\\d{2,3})-(\\d{2}),(\\d{2})?( )?([NSEW])[,/\\h]*(\\d{2,3})-(\\d{2}),(\\d{2})?( )?([NSEW])\\b");

  private final Pattern llDMSTextPattern =
      Pattern.compile(
          "\\b((lat|latitude)\\h*)?(\\d{1,2})°\\h*(\\d{1,2}(\\.\\d+)?)'(\\h*(\\d{1,2}(\\.\\d+)?)\")?\\h*([NS])\\.?,?\\h*(lon|long|longitude)?\\h*(\\d{1,3})°\\h*(\\d{1,2}(\\.\\d+)?)'(\\h*(\\d{1,2}(\\.\\d+)?)\")?\\h*([EW])\\b",
          Pattern.CASE_INSENSITIVE);
  private final Pattern llDMTextPattern =
      Pattern.compile(
          "\\b((lat|latitude)\\h*)?(\\d{1,2})°\\h*(\\d{1,2})'\\.(\\d+)\\h*([NS])\\.?,?\\h*(lon|long|longitude)?\\h*(\\d{1,3})°\\h*(\\d{1,2})'\\.(\\d+)\\h*([EW])\\b",
          Pattern.CASE_INSENSITIVE);

  private static final String COULD_NOT_PARSE =
      "Couldn't parse extracted coordinates - coordinate will be skipped";

  /**
   * Tell the annotator that coordinates are specified with the longitude first rather than the
   * latitude.
   *
   * @baleen.config false
   */
  public static final String PARAM_LONLAT = "lonlat";

  @ConfigurationParameter(name = PARAM_LONLAT, defaultValue = "false")
  private boolean lonlat;

  /**
   * Use the coordinate translated into decimal as the string to store in the Value field of the
   * Entity, allowing a normalised format for all located coordinates. This option will also format
   * the values to a maximum of 7.d.p. The use of cardinal point strings and the ordering are
   * defined by other resources.
   *
   * @baleen.config false
   */
  public static final String PARAM_STORE_DECIMAL = "storeDecimalValue";

  @ConfigurationParameter(name = PARAM_STORE_DECIMAL, defaultValue = "false")
  private boolean storeDecimalValue;

  /**
   * Store the appropriate cardinal points (N, S, E, W) with digital degree values when normalising
   * the text stored in the value field.
   *
   * @baleen.config false
   */
  public static final String PARAM_STORE_CARDINAL = "storeCardinalPoint";

  @ConfigurationParameter(name = PARAM_STORE_CARDINAL, defaultValue = "false")
  private boolean storeCardinalPoint;

  /**
   * Store the digital degree values with the longitude first instead of the default latitude first
   * when normalising the text stored in the value field.
   *
   * @baleen.config false
   */
  public static final String PARAM_STORE_LON_FIRST = "storeLongitudeFirst";

  @ConfigurationParameter(name = PARAM_STORE_LON_FIRST, defaultValue = "false")
  private boolean storeLongitudeFirst;

  /**
   * The minimum number of decimal places required when parsing Decimal Degrees. If 0, then any
   * number of decimal places is accepted.
   *
   * @baleen.config 2
   */
  public static final String PARAM_MIN_DP = "minDP";

  @ConfigurationParameter(name = PARAM_MIN_DP, defaultValue = "2")
  private String minDPString;

  /** Variable to hold the regular expression pattern for Digital Degrees */
  private Pattern llDDPattern;

  /** Variable to hold the regular expression pattern for Digital Degrees with degree symbol */
  private Pattern llDDSymPattern;

  /** Variable to hold the regular expression pattern for Digital Degrees with NSEW symbols */
  private Pattern llDDCardPattern;

  /** List of currency symbols to check for when excluding monetary values */
  private final List<String> currencySymbols = Arrays.asList("£", "$", "€");

  /**
   * Set of already found coordinates (per document) to avoid different patterns picking out the
   * same coordinate
   */
  private Set<String> found;

  /**
   * Initialise the annotator - primarily, this sets the regular expression to the correct pattern
   * for the user specified minDP (minimum decimal places)
   */
  @Override
  public void doInitialize(UimaContext aContext) throws ResourceInitializationException {

    // Parse the minDP config parameter into this variable to avoid issues with parameter types
    int minDP = ConfigUtils.stringToInteger(minDPString, 2);

    if (minDP == 0) {
      // No word boundary characters as that excludes negative signs
      llDDPattern = Pattern.compile("(-?\\d{1,3}(\\.\\d+)?)(,\\h*|\\h+)(-?\\d{1,3}(\\.\\d+)?)");
      llDDSymPattern =
          Pattern.compile("(-?\\d{1,3}(\\.\\d+)?)°(,\\h*|\\h+)(-?\\d{1,3}(\\.\\d+)?)°");
      llDDCardPattern =
          Pattern.compile(
              "\\b(\\d{1,3}(\\.\\d+)?)°( )?([NSEW])(,\\h*|\\h+)(\\d{1,3}(\\.\\d+)?)°( )?([NSEW])");
    } else {
      llDDPattern =
          Pattern.compile(
              "(-?\\d{1,3}(\\.\\d{"
                  + minDP
                  + ",}))(,\\h*|\\h+)(-?\\d{1,3}(\\.\\d{"
                  + minDP
                  + ",}))");
      llDDSymPattern =
          Pattern.compile(
              "(-?\\d{1,3}(\\.\\d{"
                  + minDP
                  + ",}))°(,\\h*|\\h+)(-?\\d{1,3}(\\.\\d{"
                  + minDP
                  + ",}))°");
      llDDCardPattern =
          Pattern.compile(
              "\\b(\\d{1,3}(\\.\\d{"
                  + minDP
                  + ",}))°( )?([NSEW])(,\\h*|\\h+)(\\d{1,3}(\\.\\d{"
                  + minDP
                  + ",}))°( )?([NSEW])");
    }
  }

  /**
   * Extract decimal coordinate pairs from the document, and add validated coordinates to the CAS
   */
  @Override
  public void doProcessTextBlock(TextBlock block) throws AnalysisEngineProcessException {
    found = new HashSet<>();
    String text = normalizeQuotesAndDots(block.getCoveredText());

    processDD(block, text);
    processDDCard(block, text);
    processDMS(block, text);
    processDMSText(block, text);
  }

  @Override
  public AnalysisEngineAction getAction() {
    return new AnalysisEngineAction(Collections.emptySet(), ImmutableSet.of(Coordinate.class));
  }

  /**
   * Searches the text for digital degree strings This method handles digital degree strings
   * consisting of a pair of decimal numbers separated by whitespace or a comma and optionally with
   * the degree symbol. The pair is assumed to be in the order Latitude, Longitude unless the
   * resource lonlat has been set to true.
   *
   * @param block the TextBlock being processed
   * @param text the text string to search for coordinates.
   */
  private void processDD(TextBlock block, String text) {

    Pattern[] patterns = new Pattern[] {llDDPattern, llDDSymPattern};
    for (Pattern p : patterns) {
      Matcher matcher = p.matcher(text);

      while (matcher.find()) {
        if (currencySymbols.contains(text.substring(matcher.start(1) - 1, matcher.start(1)))) {
          getMonitor().info("Skipping coordinate as it is preceded by a currency symbol");
          continue;
        }

        try {
          Double lat;
          Double lon;

          if (!lonlat) {
            lat = Double.parseDouble(matcher.group(1));
            lon = Double.parseDouble(matcher.group(4));
          } else {
            lon = Double.parseDouble(matcher.group(1));
            lat = Double.parseDouble(matcher.group(4));
          }

          addCoordinate(block, matcher, lon, lat, "dd");

        } catch (NumberFormatException e) {
          getMonitor().warn(COULD_NOT_PARSE, e);
        }
      }
    }
  }

  /**
   * Searches the text for digital degree strings with cardinal points. This method handles
   * processing of digital degree strings consisting of a pair of decimal numbers separated by
   * whitespace or a comma and each number is followed by a degree symbol and a letter representing
   * its cardinal compass point, i.e. N, S, E, W. The cardinal point is used to determine which
   * value is latitude and which is longitude.
   *
   * @param block the TextBlock being processed.
   * @param text the text string to search for coordinates.
   */
  private void processDDCard(TextBlock block, String text) {

    Matcher matcher = llDDCardPattern.matcher(text);
    while (matcher.find()) {
      // If no valid cardinal point letter then skip it
      if (!isValidPair(matcher.group(4), matcher.group(9))) {
        continue;
      }

      try {
        Double lat;
        Double lon;

        // Assume latitude first
        lat = Double.parseDouble(matcher.group(1));
        lon = Double.parseDouble(matcher.group(6));
        if ("E".equals(matcher.group(4)) || "W".equals(matcher.group(4))) {
          // Actually longitude first so swap values
          Double tmp = lat;
          lat = lon;
          lon = tmp;
        }

        if (flipLon(matcher.group(4), matcher.group(9))) {
          lon = -lon;
        }

        if (flipLat(matcher.group(4), matcher.group(9))) {
          lat = -lat;
        }

        addCoordinate(block, matcher, lon, lat, "dd");

      } catch (NumberFormatException e) {
        getMonitor().warn(COULD_NOT_PARSE, e);
      }
    }
  }

  private void processDMS(TextBlock block, String text) throws AnalysisEngineProcessException {

    Pattern[] patterns =
        new Pattern[] {
          llDMSPattern, llDMSSpacePattern, llDMSNumericPattern, llDMSPunctuationPattern
        };

    for (Pattern p : patterns) {
      Matcher matcher = p.matcher(text);

      while (matcher.find()) {
        if (!isValidPair(matcher.group(5), matcher.group(10))) {
          continue;
        }

        try {
          double[] lonLat = determineLonLatDMS(matcher);
          addCoordinate(block, matcher, lonLat[0], lonLat[1], "dms");
        } catch (NumberFormatException e) {
          getMonitor().warn(COULD_NOT_PARSE, e);
        }
      }
    }
  }

  private void processDMSText(TextBlock block, String text) throws AnalysisEngineProcessException {

    Matcher m = llDMSTextPattern.matcher(text);
    while (m.find()) {
      Double lat = Double.parseDouble(m.group(3));
      lat += Double.parseDouble(m.group(4)) / 60;
      if (m.group(7) != null) lat += Double.parseDouble(m.group(7)) / 3600;
      if ("S".equalsIgnoreCase(m.group(9))) lat = -lat;

      Double lon = Double.parseDouble(m.group(11));
      lon += Double.parseDouble(m.group(12)) / 60;
      if (m.group(15) != null) lon += Double.parseDouble(m.group(15)) / 3600;
      if ("W".equalsIgnoreCase(m.group(17))) lon = -lon;

      addCoordinate(block, m, lon, lat, "dms");
    }

    m = llDMTextPattern.matcher(text);
    while (m.find()) {
      Double lat = Double.parseDouble(m.group(3));
      lat += Double.parseDouble(m.group(4)) / 60;
      lat += Double.parseDouble(m.group(5)) / 3600;
      if ("S".equalsIgnoreCase(m.group(6))) lat = -lat;

      Double lon = Double.parseDouble(m.group(8));
      lon += Double.parseDouble(m.group(9)) / 60;
      lon += Double.parseDouble(m.group(10)) / 3600;
      if ("S".equalsIgnoreCase(m.group(11))) lon = -lon;

      addCoordinate(block, m, lon, lat, "dms");
    }
  }

  private double[] determineLonLatDMS(Matcher matcher) {
    Double lat = 0.0;
    Double lon = 0.0;

    lat =
        dmsToDeg(
            Integer.parseInt(matcher.group(1)),
            Integer.parseInt(matcher.group(2)),
            parseOrNull(matcher.group(3)));

    lon =
        dmsToDeg(
            Integer.parseInt(matcher.group(6)),
            Integer.parseInt(matcher.group(7)),
            parseOrNull(matcher.group(8)));

    if ("E".equals(matcher.group(5)) || "W".equals(matcher.group(5))) {
      Double tmp = lat;
      lat = lon;
      lon = tmp;
    }

    if (flipLon(matcher.group(5), matcher.group(10))) {
      lon = -lon;
    }

    if (flipLat(matcher.group(5), matcher.group(10))) {
      lat = -lat;
    }

    return new double[] {lon, lat};
  }

  /**
   * Determines whether we have both a North/South and an East/West directional indicator present
   */
  private boolean isValidPair(String... parameters) {
    boolean nFound = false;
    boolean eFound = false;

    for (String s : parameters) {
      if ("N".equalsIgnoreCase(s) || "S".equalsIgnoreCase(s)) {
        nFound = true;
      } else if ("E".equalsIgnoreCase(s) || "W".equalsIgnoreCase(s)) {
        eFound = true;
      }
    }

    return nFound && eFound;
  }

  private boolean flipLat(String... parameters) {
    for (String s : parameters) {
      if ("S".equalsIgnoreCase(s)) {
        return true;
      }
    }

    return false;
  }

  private boolean flipLon(String... parameters) {
    for (String s : parameters) {
      if ("W".equalsIgnoreCase(s)) {
        return true;
      }
    }

    return false;
  }

  /**
   * Converts a Degrees Minutes Seconds coordinate into a decimal degree value The conversion is
   * ignorant of the cardinality (N, S, E, W) so degrees value should be positive and the conversion
   * of an S latitude or W longitude coordinate to a negative value should be carried out by the
   * calling function.
   *
   * @param d number of degrees. It is assumed this is a positive value
   * @param m number of minutes
   * @param s number of seconds, or null if no seconds supplied
   * @return the decimal degree value for the degrees minutes seconds
   */
  private double dmsToDeg(Integer d, Integer m, Double s) {
    double seconds = m * 60.0;
    if (s != null) {
      seconds += s;
    }
    return d + (seconds / 3600);
  }

  private Double parseOrNull(String s) {
    if (s != null) {
      return Double.parseDouble(s);
    } else {
      return null;
    }
  }

  private void addCoordinate(
      TextBlock block, Matcher matcher, Double lon, Double lat, String coordinateType) {
    if (lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180) {
      String textLoc = matcher.start() + "," + matcher.end();

      if (found.add(textLoc)) {
        Coordinate loc = new Coordinate(block.getJCas());

        loc.setConfidence(1.0f);

        block.setBeginAndEnd(loc, matcher.start(), matcher.end());
        if (storeDecimalValue) {
          addNormalisedValue(lat, lon, loc);
        } else {
          loc.setValue(matcher.group(0));
        }

        String coords = "[" + lon + "," + lat + "]";

        loc.setGeoJson("{\"type\":\"Point\",\"coordinates\":" + coords + "}");

        loc.setCoordinateValue(lon + "," + lat);
        loc.setSubType(coordinateType);

        addToJCasIndex(loc);
      }
    }
  }
  /*
   * Formats the decimal degree values into a normalised form
   * This method sets the Value field of the JCas Coordinate
   * object to a normalised string rather than a copy of the
   * original text in the document string.
   * The format consist of decimal degree values. The use of
   * cardinal point strings and the order is controlled by
   * resource.
   *
   * @param lat the latitude as a decimal degree (negative is S)
   * @param lon the longitude as a decimal degree (negative is W)
   * @param loc  the coordinate location to hold the normalised string
   */
  private void addNormalisedValue(double lat, double lon, Coordinate loc) {
    String pattern = "###.#######";
    double normLat = lat;
    double normLon = lon;
    String latString = "";
    String lonString = "";

    DecimalFormat df = new DecimalFormat(pattern);
    if (storeCardinalPoint) {
      String cardLat = "N";
      String cardLon = "E";
      if (normLat < 0) {
        normLat = -normLat;
        cardLat = "S";
      }
      if (normLon < 0) {
        normLon = -normLon;
        cardLon = "W";
      }
      latString = df.format(normLat) + cardLat;
      lonString = df.format(normLon) + cardLon;
    } else {
      latString = df.format(normLat);
      lonString = df.format(normLon);
    }
    String firstCoord = storeLongitudeFirst ? lonString : latString;
    String secondCoord = storeLongitudeFirst ? latString : lonString;
    loc.setValue(firstCoord + " " + secondCoord);
    loc.setIsNormalised(true);
  }

  /**
   * Replace smart quotes, curly quotes, back ticks and mid-dots with standard quotes and dots to
   * simplify the required regular expressions.
   */
  public static String normalizeQuotesAndDots(String s) {
    return s.replaceAll("[\\u201C\\u201D\\u2033\\u02BA\\u301E\\u3003]", "\"")
        .replaceAll("[\\u2018\\u2019\\u2032\\u00B4\\u02B9`]", "'")
        .replaceAll("[\\u00B7]", ".");
  }
}


text:
generate: Module Overview
---
This module is responsible of creating folders that can be consumed by the `order` module. In other words, this is an _adapter_.

### `p2_convert.py`
This takes a source directory of valid python scripts (`*.py` files) and converts them to `*.p2` files. This auto-generates some metadata for these files, and also accepts some values for other fields.

### `p2_so_crawl.py`
This takes [`Snippet`](../so_crawl/snippet.py) objects and saves them as `*.p2` files. The metadata is pulled from the relevant fields in the model.


text:
DROP FUNCTION IF EXISTS copy_answer_parts(
  old_questionnaire_id INTEGER, new_questionnaire_id INTEGER
);
DROP FUNCTION IF EXISTS copy_answer_parts_start(
  old_questionnaire_id INTEGER, new_questionnaire_id INTEGER
);
CREATE OR REPLACE FUNCTION copy_answer_parts_start(
  old_questionnaire_id INTEGER, new_questionnaire_id INTEGER
) RETURNS VOID
LANGUAGE plpgsql AS $$
BEGIN
  CREATE TEMP TABLE tmp_answer_parts () INHERITS (answer_parts);
  CREATE TEMP TABLE tmp_answer_part_matrix_options () INHERITS (answer_part_matrix_options);

  WITH answer_parts_to_copy AS (
    SELECT
      answer_parts.*,
      tmp_answers.id AS new_answer_id,
      tmp_answers.created_at AS new_created_at,
      tmp_answers.updated_at AS new_updated_at
    FROM answer_parts
    JOIN tmp_answers
    ON tmp_answers.original_id = answer_parts.answer_id
  ), answer_parts_to_copy_with_resolved_field_types AS (
    SELECT answer_parts_to_copy.*, fields.id AS new_field_type_id
    FROM answer_parts_to_copy
    JOIN tmp_text_answer_fields fields
    ON answer_parts_to_copy.field_type_type = 'TextAnswerField'
    AND fields.original_id = answer_parts_to_copy.field_type_id

    UNION

    SELECT answer_parts_to_copy.*, fields.id AS new_field_type_id
    FROM answer_parts_to_copy
    JOIN tmp_numeric_answers fields
    ON answer_parts_to_copy.field_type_type = 'NumericAnswer'
    AND fields.original_id = answer_parts_to_copy.field_type_id

    UNION

    SELECT answer_parts_to_copy.*, fields.id AS new_field_type_id
    FROM answer_parts_to_copy
    JOIN tmp_rank_answer_options fields
    ON answer_parts_to_copy.field_type_type = 'RankAnswerOption'
    AND fields.original_id = answer_parts_to_copy.field_type_id

    UNION

    SELECT answer_parts_to_copy.*, fields.id AS new_field_type_id
    FROM answer_parts_to_copy
    JOIN tmp_range_answer_options fields
    ON answer_parts_to_copy.field_type_type = 'RangeAnswerOption'
    AND fields.original_id = answer_parts_to_copy.field_type_id

    UNION

    SELECT answer_parts_to_copy.*, fields.id AS new_field_type_id
    FROM answer_parts_to_copy
    JOIN tmp_multi_answer_options fields
    ON answer_parts_to_copy.field_type_type = 'MultiAnswerOption'
    AND fields.original_id = answer_parts_to_copy.field_type_id

    UNION

    SELECT answer_parts_to_copy.*, fields.id AS new_field_type_id
    FROM answer_parts_to_copy
    JOIN tmp_matrix_answer_queries fields
    ON answer_parts_to_copy.field_type_type = 'MatrixAnswerQuery'
    AND fields.original_id = answer_parts_to_copy.field_type_id
  )
  INSERT INTO tmp_answer_parts (
    answer_text,
    answer_id,
    field_type_type,
    field_type_id,
    details_text,
    answer_text_in_english,
    original_language,
    sort_index,
    created_at,
    updated_at,
    original_id
  )
  SELECT
    answer_text,
    new_answer_id,
    field_type_type,
    answer_parts.new_field_type_id,
    details_text,
    answer_text_in_english,
    original_language,
    sort_index,
    new_created_at,
    new_updated_at,
    answer_parts.id
  FROM answer_parts_to_copy_with_resolved_field_types answer_parts;

  INSERT INTO tmp_answer_part_matrix_options (
    answer_part_id,
    matrix_answer_option_id,
    matrix_answer_drop_option_id,
    answer_text,
    created_at,
    updated_at
  )
  SELECT
    tmp_answer_parts.id,
    tmp_matrix_answer_options.id,
    tmp_matrix_answer_drop_options.id,
    answer_part_matrix_options.answer_text,
    tmp_answer_parts.created_at,
    tmp_answer_parts.updated_at
  FROM answer_part_matrix_options
  JOIN tmp_answer_parts
  ON tmp_answer_parts.original_id = answer_part_matrix_options.answer_part_id
  LEFT JOIN tmp_matrix_answer_options
  ON tmp_matrix_answer_options.original_id = answer_part_matrix_options.matrix_answer_option_id
  LEFT JOIN tmp_matrix_answer_drop_options
  ON tmp_matrix_answer_drop_options.original_id = answer_part_matrix_options.matrix_answer_drop_option_id;
END;
$$;

DROP FUNCTION IF EXISTS copy_answer_parts_end();
CREATE OR REPLACE FUNCTION copy_answer_parts_end()
RETURNS VOID
LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO answer_parts SELECT * FROM tmp_answer_parts;
  DROP TABLE tmp_answer_parts;
  INSERT INTO answer_part_matrix_options SELECT * FROM tmp_answer_part_matrix_options;
  DROP TABLE tmp_answer_part_matrix_options;
END;
$$;


text:
require 'spec_helper'

describe 'ButtonAction', 'when submitting' do

  include FormtasticSpecHelper

  before do
    @output_buffer = ''
    mock_everything

    concat(semantic_form_for(@new_post) do |builder|
      concat(builder.action(:submit, :as => :button))
    end)
  end

  it 'should render a submit type of button' do
    output_buffer.should have_tag('li.action.button_action button[@type="submit"]')
  end

end

describe 'ButtonAction', 'when resetting' do

  include FormtasticSpecHelper

  before do
    @output_buffer = ''
    mock_everything

    concat(semantic_form_for(@new_post) do |builder|
      concat(builder.action(:reset, :as => :button))
    end)
  end

  it 'should render a reset type of button' do
    output_buffer.should have_tag('li.action.button_action button[@type="reset"]', :text => "Reset Post")
  end

  it 'should not render a value attribute' do
    output_buffer.should_not have_tag('li.action.button_action button[@value]')
  end

end

describe 'InputAction', 'when cancelling' do

  include FormtasticSpecHelper

  before do
    @output_buffer = ''
    mock_everything
  end

  it 'should raise an error' do
    lambda {
      concat(semantic_form_for(@new_post) do |builder|
        concat(builder.action(:cancel, :as => :button))
      end)
    }.should raise_error(Formtastic::UnsupportedMethodForAction)
  end

end


text:
require 'net/http'
require 'active_support/core_ext/class/attribute_accessors'
require_relative '../../helpers/json'

module Aws
  module Instance
    module Document

      mattr_reader :uri do
        URI.parse('http://169.254.169.254/latest/dynamic/instance-identity/document')
      end

      mattr_reader :object do
        JSON
            .parse_with_cast(Net::HTTP.get(uri))
            .transform_keys!(&:underscore)
            .tap {|document| ENV['AWS_REGION'] = document.fetch(:region)}
      end

      def self.fetch(key)
        object.fetch(key)
      end

    end

  end
end


text:
import pprint
import logging
from faker import Factory
from workout import MongoWorkout

logger = logging.getLogger(__name__)

class FindDuplicates(MongoWorkout):
    """ Show how to find duplicates from file
    using aggregation pipeline
    """
    name = 'RemoveDuplicates'
    collection = 'removeDuplicates'

    # pipeline to find duplicates
    pipeline = [
        {
            "$group": {
                "_id": {
                    "number": "$number",
                    "name": "$name",
                },
                "duplicateIds": {"$addToSet": "$_id"},
                "count": {"$sum": 1},
            },
        },
        {
            "$match": {
                "count": {
                    "$gt": 1,
                }
            }
        },
        {
            "$project": {
                "_id": 0,
                "duplicateIds": "$duplicateIds",
                "count": "$count",
            }
        }
    ]

    def prepare(self):
        fake = Factory.create('en_US')
        for num in range(1, 6):
            document = {
                'number': num,
                'name': fake.name(),
            }
            doc = self.insert_document(document.copy())
            logger.info("Original: {}".format(doc))

            for _ in range(1, num):
                doc = self.insert_document(document.copy())
                logger.info("Duplicate: {}".format(doc))

    def run(self):
        results = self.db[self.collection].aggregate(self.pipeline)
        pp = pprint.PrettyPrinter(indent=2)
        pp.pprint(list(results))


text:
package org.spongepowered.common.data.provider.entity;

import org.spongepowered.api.data.Keys;
import org.spongepowered.common.accessor.world.entity.animal.OcelotAccessor;
import org.spongepowered.common.data.provider.DataProviderRegistrator;

public final class OcelotData {

    private OcelotData() {
    }

    // @formatter:off
    public static void register(final DataProviderRegistrator registrator) {
        registrator
                .asMutable(OcelotAccessor.class)
                    .create(Keys.IS_TRUSTING)
                        .get(OcelotAccessor::invoker$isTrusting)
                        .set(OcelotAccessor::invoker$setTrusting);
    }
    // @formatter:on
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="huyifei.mymvp.test.HashMapActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="horizontal">

        <TextView
            android:textSize="25sp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:padding="5dp"
            android:text="key: "/>

        <EditText
            android:id="@+id/key"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="3"
            android:padding="5dp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="horizontal">

        <TextView
            android:textSize="25sp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:padding="5dp"
            android:text="value: "/>

        <EditText
            android:id="@+id/value"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="3"
            android:padding="5dp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/put"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:text="put"/>

        <Button
            android:id="@+id/get"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:text="get"/>

        <Button
            android:id="@+id/remove"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:text="remove"/>

    </LinearLayout>

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"/>

</LinearLayout>


text:
package com.fit2cloud.aliyun.bss;

import java.util.Map;

import com.fit2cloud.aliyun.AliyunClientException;
import com.fit2cloud.aliyun.AliyunCredentials;
import com.fit2cloud.aliyun.AliyunServiceException;
import com.fit2cloud.aliyun.PageableRequest;
import com.fit2cloud.aliyun.bss.model.request.DescribeCashDetailRequest;
import com.fit2cloud.aliyun.bss.model.request.DescribeCouponListRequest;
import com.fit2cloud.aliyun.bss.model.response.DescribeCashDetailResponse;
import com.fit2cloud.aliyun.bss.model.response.DescribeCouponListResponse;
import com.fit2cloud.aliyun.bss.model.response.PageableResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class BSSClient
{
    private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm'Z'";
    private Gson gson = new GsonBuilder().setDateFormat(ISO8601_DATE_FORMAT).create();

    private BSSRequest request;

    public BSSClient(AliyunCredentials credentials){
    	request = new BSSRequest(credentials);
    }

    public DescribeCashDetailResponse describeCashDetail(final DescribeCashDetailRequest describeCashDetailRequest) throws JsonSyntaxException, AliyunClientException, AliyunServiceException {
    	return gson.fromJson(request.execute("DescribeCashDetail", describeCashDetailRequest.toMap()), DescribeCashDetailResponse.class);
    }

    public DescribeCouponListResponse describeCouponList(
    		final DescribeCouponListRequest describeCouponListRequest)
    				throws JsonSyntaxException, AliyunClientException, AliyunServiceException {
    	return (DescribeCouponListResponse) listPageableData(describeCouponListRequest, "DescribeCouponList", DescribeCouponListResponse.class);
    }

	private <T extends PageableResponse> T listPageableData(
			final PageableRequest pageableRequest, final String action, Class<T> responseClass)
			throws AliyunClientException, AliyunServiceException {
		boolean requestAll = false;
		if (pageableRequest.getPageNumber() == null
				&& pageableRequest.getPageSize() == null) {
			requestAll = true;
		}
		int pageNumber = pageableRequest.getPageNumber() == null ? 1
				: pageableRequest.getPageNumber();
		int pageSize = pageableRequest.getPageSize() == null ? 50
				: pageableRequest.getPageSize();
		int count = 0;

		T result = null;
		try {
			result = responseClass.newInstance();
			while (true) {
				Map<String, String> params = pageableRequest.toMap();
				params.put("PageNumber", String.valueOf(pageNumber++));
				params.put("pageSize", String.valueOf(pageSize));
				T response = gson.fromJson(
						request.execute(action, params),
						responseClass);
				if (!requestAll) {
					return response;
				}
				result.add(response);
				count += pageSize;
				if (count >= response.getTotalRecordCount()) {
					break;
				}
			}
			result.setPageNumber(1);
			result.setPageRecordCount(result.getTotalRecordCount());
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return result;
	}
}