text:
package calico.plugins.iip.components;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.Point;
import java.awt.RadialGradientPaint;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.prefs.BackingStoreException;

import javax.swing.SwingUtilities;

import calico.CalicoDataStore;
import calico.CalicoDraw;
import calico.components.CCanvas;
import calico.components.bubblemenu.BubbleMenu;
import calico.components.piemenu.PieMenuButton;
import calico.controllers.CCanvasController;
import calico.controllers.CHistoryController;
import calico.controllers.CCanvasController.HistoryFrame;
import calico.events.CalicoEventHandler;
import calico.events.CalicoEventListener;
import calico.networking.netstuff.CalicoPacket;
import calico.plugins.iip.IntentionalInterfacesClientPlugin;
import calico.plugins.iip.IntentionalInterfacesNetworkCommands;
import calico.plugins.iip.components.graph.IntentionGraph;
import calico.plugins.iip.components.piemenu.iip.CreateLinkButton;
import calico.plugins.iip.components.piemenu.iip.DeleteCanvasButton;
import calico.plugins.iip.components.piemenu.iip.SetCanvasTitleButton;
import calico.plugins.iip.components.piemenu.iip.UnpinCanvas;
import calico.plugins.iip.components.piemenu.iip.ZoomToBranchButton;
import calico.plugins.iip.components.piemenu.iip.ZoomToCenterRingButton;
import calico.plugins.iip.components.piemenu.iip.ZoomToClusterButton;
import calico.plugins.iip.controllers.CCanvasLinkController;
import calico.plugins.iip.controllers.CIntentionCellController;
import calico.plugins.iip.controllers.IntentionCanvasController;
import calico.plugins.iip.iconsets.CalicoIconManager;
import calico.plugins.iip.inputhandlers.CIntentionCellInputHandler;
import calico.plugins.iip.util.IntentionalInterfacesGraphics;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.nodes.PImage;
import edu.umd.cs.piccolo.nodes.PText;
import edu.umd.cs.piccolo.util.PBounds;
import edu.umd.cs.piccolo.util.PPaintContext;
import edu.umd.cs.piccolox.nodes.PComposite;

/**
 * Represents a canvas thumbnail in the Intention View, both in the plugin's internal model and in the Piccolo component
 * hierarchy (with inner class Shell). The classname CIntentionCell is generally abbreviated
 * "CIC" throughout the documentation.
 *
 * @author Byron Hawkins
 */
public class CIntentionCell implements CalicoEventListener
{
	public static final String DEFAULT_TITLE = "<default>";
	private static final double MINIMUM_SNAPSHOT_SCALE = 1.0;
	public static final Color COORDINATES_COLOR = Color.blue;
	private static final Insets THUMBNAIL_INSETS = new Insets(2, 2, 2, 2);
	public static final Dimension THUMBNAIL_SIZE = new Dimension(200, 130);
	public static final Font COORDINATES_FONT = new Font("Helvetica", Font.BOLD, THUMBNAIL_SIZE.width / 10);

	private static Image iconImage_create = CalicoIconManager.getIconImage("intention-graph.link-create");
	private static Image iconImage_delete = CalicoIconManager.getIconImage("intention-graph.link-delete");
	private static Image pinImage = CalicoIconManager.getIconImage(
			"intention-graph.cell-pin");
	private static Image pinSelectedImage= CalicoIconManager.getIconImage(
			"intention-graph.cell-pin-selected");

	public enum CellIconType {NONE, CREATE_LINK, DELETE_LINK};

	private CellIconType iconToShow = CellIconType.NONE;

	private static final int BUBBLE_MENU_TYPE_ID = BubbleMenu.registerType(new BubbleMenuComponentType());

	/**
	 * Simple button to delete a canvas and its associated CIC.
	 */
	private final DeleteCanvasButton deleteCanvasButton = new DeleteCanvasButton();
	/**
	 * Button for initiating the arrow creation phase, which is governed by CIntentionArrowPhase.
	 */
	private final CreateLinkButton linkButton = new CreateLinkButton();
	/**
	 * Simple button to zoom and pan the Intention View such that the cluster containing the selected CIC fits neatly in
	 * the Intention View.
	 */
	private final ZoomToClusterButton zoomToClusterButton = new ZoomToClusterButton();
	/**
	 * Opens a dialog to set the name of the canvas
	 */
	private final SetCanvasTitleButton setCanvasTitleButton = new SetCanvasTitleButton();
	/**
	 * Simple button to zoom into the center ring of the cluster
	 */
	private final ZoomToCenterRingButton zoomToCenterRingButton = new ZoomToCenterRingButton();
	/**
	 * Simple button to zoom into the center ring of the cluster
	 */
	private final ZoomToBranchButton zoomToBranchButton = new ZoomToBranchButton();
	/**
	 * Unpin the currently selected CIC
	 */
	private final UnpinCanvas unpinCanvas = new UnpinCanvas();

	private enum BorderColor
	{
		PLAIN(Color.black),
		HIGHLIGHTED(new Color(0xFFFF30));

		Color color;

		private BorderColor(Color color)
		{
			this.color = color;
		}
	}

	/**
	 * Identifies this cell.
	 */
	private long uuid;
	/**
	 * Identifies the canvas for which this cell renders thumbnails.
	 */
	private long canvas_uuid;
	/**
	 * Pixel position in the Intention View of the upper left corner of the canvas thumbnail.
	 */
	private Point2D location;
	/**
	 * Title of the canvas, which appears both on the CIC and on the canvas itself (represented there by
	 * CanvasTitlePanel). The title is maintained in this class because it is a feature of this plugin, but
	 * the title is still effectively associated with the canvas.
	 */
	private String title;
	/**
	 * Tag associated with the canvas of this CIC. The tag is maintained in this class because it is a feature of this
	 * plugin, but the tag is still effectively associated with the canvas.
	 */
	private long intentionTypeId = -1L;

	/**
	 * Rendering state flag indicating that the border of the CIC is currently drawn in the highlighted color.
	 */
	private boolean highlighted = false;
	/**
	 * State flag used in the construction process of a canvas. See CIntentionCellFactory for details.
	 */
	private boolean isNew = false;

	/**
	 * Represents the CIC in the Piccolo component hierarchy of the Intention View.
	 */
	private final Shell shell;

	private boolean isPinned = false;

	private PImage pin = new PImage(pinImage);

	/**
	 * Create a new CIC and add it to the Intention View.
	 */
	public CIntentionCell(long uuid, long canvas_uuid, Point2D location, String title)
	{
		this.uuid = uuid;
		this.canvas_uuid = canvas_uuid;
		this.location = location;
		this.title = title;

		shell = new Shell(location.getX(), location.getY());
		if (!IntentionGraph.getInstance().isClusterRoot(canvas_uuid))
			CalicoDraw.addChildToNode(IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT), shell);

		CalicoEventHandler.getInstance().addListener(IntentionalInterfacesNetworkCommands.CIC_TAG, this, CalicoEventHandler.PASSIVE_LISTENER);
		CalicoEventHandler.getInstance().addListener(IntentionalInterfacesNetworkCommands.CIC_UNTAG, this, CalicoEventHandler.PASSIVE_LISTENER);
		CalicoEventHandler.getInstance().addListener(IntentionalInterfacesNetworkCommands.CIC_SET_TITLE, this, CalicoEventHandler.PASSIVE_LISTENER);
		CalicoEventHandler.getInstance().addListener(IntentionalInterfacesNetworkCommands.CIC_UPDATE_FINISHED, this, CalicoEventHandler.PASSIVE_LISTENER);
		CalicoEventHandler.getInstance().addListener(IntentionalInterfacesNetworkCommands.CIC_TOPOLOGY, this, CalicoEventHandler.PASSIVE_LISTENER);
		CalicoEventHandler.getInstance().addListener(IntentionalInterfacesNetworkCommands.CLINK_CREATE, this, CalicoEventHandler.PASSIVE_LISTENER);

//		IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).addChild(shell);
	}

	public boolean isNew()
	{
		return isNew;
	}

	public void setNew(boolean isNew)
	{
		this.isNew = isNew;
	}

	/**
	 * Create and install the thumbnail image.
	 */
	public void initialize()
	{
		shell.updateContents();
	}

	/**
	 * Detach all the resources of the CIC from the Intention View.
	 */
	public void delete()
	{
		shell.delete();
	}

	private Color currentBorderColor()
	{
		if (false /*highlighted*/)
		{
			return BorderColor.HIGHLIGHTED.color;
		}
		else
		{
			return BorderColor.PLAIN.color;
		}
	}

	public long getId()
	{
		return uuid;
	}

	public long getCanvasId()
	{
		return canvas_uuid;
	}

	public String getTitle()
	{
		String ret = "";

		//Pre-append cluster prefix
		if (CIntentionCellController.getInstance().isRootCanvas(canvas_uuid))
		{
			long[] roots = calico.plugins.iip.components.graph.IntentionGraph.getInstance().getRootsOfAllClusters();
			int position = 0;
			while (position < roots.length)
				if (roots[position] == canvas_uuid)
					break;
				else
					position++;

			ret += (position+1) + ". ";

		}

		ret += getTitleWithoutPrefix();

		return ret;
	}

	public String getTitleWithoutPrefix() {
		String ret;

		if (title.equals(DEFAULT_TITLE))
		{
			if (CIntentionCellController.getInstance().isRootCanvas(canvas_uuid))
				ret = "Unnamed cluster";
			else if (CCanvasController.canvasdb.containsKey(canvas_uuid))
				ret = "Canvas " + CCanvasController.canvasdb.get(canvas_uuid).getIndex();
			else
				ret = "Canvas ";
		}
		else
			ret = title;
		return ret;
	}

	/**
	 * Return true if the user has set a title on the canvas associated to this CIC, or false if the canvas uses the
	 * default title.
	 */
	public boolean hasUserTitle()
	{
		return !title.equals(DEFAULT_TITLE);
	}

	public void setTitle(String title)
	{
		this.title = title;
//		shell.titleBar.updateTitle();
	}

	public Long getIntentionTypeId()
	{
		return intentionTypeId;
	}

	public void setIntentionType(long intentionTypeId)
	{
		this.intentionTypeId = intentionTypeId;
	}

	/**
	 * Return true if the user has assigned a tag to the canvas associated to this CIC.
	 */
	public boolean hasIntentionType()
	{
		return intentionTypeId >= 0L;
	}

	/**
	 * Remove any tag that may have been assigned to the canvas associated with this CIC.
	 */
	public void clearIntentionType()
	{
		intentionTypeId = -1L;
	}

	/**
	 * Return true when point contacts the physical coordinate region occupied by the canvas thumbnail of
	 * this CIC in the Intention View. It is assumed that point specifies screen coordinates.
	 */
	public boolean contains(Point2D point)
	{
		if (IntentionGraph.getInstance().isClusterRoot(this.getCanvasId()))
			return false;
		PBounds bounds = shell.getGlobalBounds();
		return ((point.getX() > bounds.x) && (point.getY() > bounds.y) && ((point.getX() - bounds.x) < bounds.width) && (point.getY() - bounds.y) < bounds.height);
	}

	/**
	 * Get the pixel position of this CIC within the Intention View.
	 */
	public Point2D getLocation()
	{
		return shell.getBounds().getOrigin();
	}

	/**
	 * Get the bounds of this CIC in screen coordinates.
	 */
	public PBounds getGlobalBounds()
	{
		PBounds bounds = shell.getBounds();
		// bounds.setOrigin(0.0, 0.0);
		return new PBounds(shell.localToGlobal(bounds)); // getBounds();
	}

	public PBounds getBounds()
	{
		PBounds bounds = shell.getBounds();
		return new PBounds(bounds);
	}

	/**
	 * Get the center point of this CIC in Intention View coordinates.
	 */
	public Point2D getCenter()
	{
		return shell.thumbnailBounds.getCenter2D();
	}

	/**
	 * Set the location of this CIC in Intention View coordinates.
	 */
	public void setLocation(final double x, final double y)
	{
//		SwingUtilities.invokeLater(
		IntentionalInterfacesClientPlugin.addNewEventDispatcherEvent(
				new Runnable() { public void run() {
					location.setLocation(x, y);
					shell.setX(x);
					shell.setY(y);
					shell.layoutChildren();
					if (CIntentionCellInputHandler.getInstance().getActiveCell() == getId())
						SwingUtilities.invokeLater(
								new Runnable() { public void run() {
									if (getBounds() != null)
										BubbleMenu.moveIconPositions(getBounds());
								}});

//					shell.repaint();
				}});

//		CalicoDraw.repaint(shell);
//		shell.repaint();
	}

	public Dimension2D getSize()
	{
		return shell.thumbnailBounds.getSize();
	}

	/**
	 * Clone the bounds of this CIC, which occur in Intention View coordinates.
	 */
	public PBounds copyBounds()
	{
		return (PBounds) shell.thumbnailBounds.clone();
	}

	public void setHighlighted(boolean highlighted)
	{
		this.highlighted = highlighted;
		CalicoDraw.repaint(shell);
//		shell.repaint();
	}

	/**
	 * Return true if this CIC can be seen in the present visible area of the Intention View.
	 */
	public boolean isInGraphFootprint()
	{
		return IntentionGraph.getInstance().getLocalBounds(IntentionGraph.Layer.CONTENT).intersects(shell.getBounds());
	}

	/**
	 * Update the canvas thumbnail to reflect its most recent contents.
	 */
	public void contentsChanged()
	{
		shell.canvasSnapshot.contentsChanged();
	}

	/**
	 * Update the iconification state of this CIC, based on the current zoom ratio and whether iconification mode is
	 * enabled. This feature is obsolete.
	 */
	public void updateIconification()
	{
		shell.updateIconification();
		CalicoDraw.repaint(shell);
//		shell.repaint();
	}

	/**
	 * Update the list of users drawn in the upper right corner of this CIC.
	 */
	public void updateUserList()
	{
		shell.userList.updateUsers();
	}

	/**
	 * Return true if the present zoom ratio allows the thumbnail to be drawn. This is used for iconification, which is
	 * obsolete.
	 */
	private boolean scaleAllowsSnapshot()
	{
		return ((!IntentionGraph.getInstance().getIconifyMode()) || (IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).getScale() >= MINIMUM_SNAPSHOT_SCALE));
	}

	private static final int BORDER_WIDTH = 1;

	/**
	 * Represents the CIC in the Piccolo component hierarchy of the Intention View. The size of a CIC is statically
	 * defined as THUMBNAIL_SIZE, so all scaling occurs globally to the Intention View.
	 *
	 * @author Byron Hawkins
	 */
	private class Shell extends PComposite implements PropertyChangeListener
	{
		private final Color BACKGROUND_COLOR = new Color(0xFF, 0xFF, 0xFF, 0xCC);

		/**
		 * Renders the canvas number in the upper left corner.
		 */
		private final PImage canvasAddress;
		/**
		 * Renders the thumbnail image.
		 */
		private final CanvasSnapshot canvasSnapshot = new CanvasSnapshot();

		private final PImage cellIcon = new PImage();
		/**
		 * Renders the title of the canvas, above the CIC and left justified.
		 */
		private final TitleBar titleBar = new TitleBar();
		/**
		 * Renders the list of users currently viewing the canvas associated with this CIC.
		 */
		private final UserList userList = new UserList();

		/**
		 * State flag indicating that the thumbnail is currently being displayed. This flag supports iconification,
		 * which is obsolete.
		 */
		private boolean showingSnapshot = false;

		/**
		 * Bounds of the thumbnail rectangle, not including the title sitting above the CIC.
		 */
		private PBounds thumbnailBounds = new PBounds();

		/**
		 * Maintains the last zoom ratio, to avoid regenerating the thumbnail image when the Intention View display
		 * changes in any way that does not affect the rendering of this thumbnail (including miniscule zoom changes
		 * that have no net effect).
		 */
		private double lastScale = Double.MIN_VALUE;

		public Shell(double x, double y)
		{
			canvasAddress = new PImage(IntentionalInterfacesGraphics.superimposeCellAddress(
					CalicoIconManager.getIconImage("intention-graph.obscured-intention-cell"), canvas_uuid));
			CalicoDraw.addChildToNode(this, canvasAddress);
//			addChild(canvasAddress);

			CalicoDraw.addChildToNode(this, titleBar);
			CalicoDraw.addChildToNode(this, userList);
//			addChild(titleBar);
//			addChild(userList);

			thumbnailBounds.setRect(x, y, THUMBNAIL_SIZE.width - (CCanvas.ROUNDED_RECTANGLE_OVERFLOW + CCanvas.CELL_MARGIN), THUMBNAIL_SIZE.height
					- (CCanvas.ROUNDED_RECTANGLE_OVERFLOW + CCanvas.CELL_MARGIN));
			CalicoDraw.setNodeBounds(this, thumbnailBounds);
//			setBounds(thumbnailBounds);

			titleBar.setWidth(thumbnailBounds.getWidth());

			updateIconification();

			cellIcon.setBounds(new Rectangle(0,0,64,64));
			cellIcon.setVisible(false);
			CalicoDraw.addChildToNode(this, cellIcon);

			pin.setVisible(false);
			CalicoDraw.addChildToNode(this, pin);
//			this.addChild(cellIcon);

			IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).addPropertyChangeListener(PNode.PROPERTY_TRANSFORM, this);

			CalicoDraw.moveNodeToFront(userList);
//			userList.moveToFront();
//			CalicoDraw.repaint(this);
//			repaint();
		}

		private void setIconImage(final Image image)
		{
			SwingUtilities.invokeLater(
					new Runnable() { public void run() {
						cellIcon.setImage(image);
					}});
		}

		void delete()
		{
			IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).removeChild(this);
			IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).removePropertyChangeListener(PNode.PROPERTY_TRANSFORM, this);
		}

		void updateIconification()
		{
			lastScale = IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).getScale();
			if (showingSnapshot != scaleAllowsSnapshot())
			{
				if (showingSnapshot)
				{
					CalicoDraw.removeChildFromNode(this, canvasSnapshot.snapshot);
//					removeChild(canvasSnapshot.snapshot);
					CalicoDraw.addChildToNode(this, canvasAddress);
//					addChild(canvasAddress);
				}
				else
				{
					CalicoDraw.removeChildFromNode(this, canvasAddress);
//					removeChild(canvasAddress);
					CalicoDraw.addChildToNode(this, canvasSnapshot.snapshot);
//					addChild(canvasSnapshot.snapshot);
				}

				showingSnapshot = !showingSnapshot;
			}
		}

		void updateContents()
		{
			if (IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).getScale() != lastScale)
			{
				updateIconification();
			}

			if (canvasSnapshot.isDirty)
			{
				canvasSnapshot.contentsChanged();
			}
		}

		@Override
		public void propertyChange(PropertyChangeEvent event)
		{
			updateContents();
		}

		@Override
		protected void paint(PPaintContext paintContext)
		{
			super.paint(paintContext);

			Graphics2D g = paintContext.getGraphics();
			Color c = g.getColor();
			Paint p = g.getPaint();

			g.setColor(BACKGROUND_COLOR);
			g.fill(getBounds());

			g.setColor(currentBorderColor());
			g.translate(thumbnailBounds.x, thumbnailBounds.y);

			if (highlighted)
				drawHighlight(g);
			drawHistoryHighlight(g);

			g.drawRoundRect(0, 0, ((int) thumbnailBounds.width) - 1, ((int) thumbnailBounds.height) - 1, 10, 10);
			IntentionalInterfacesGraphics.superimposeCellAddressInCorner(g, canvas_uuid, thumbnailBounds.width - (2 * BORDER_WIDTH), COORDINATES_FONT,
					COORDINATES_COLOR);

			g.translate(-thumbnailBounds.x, -thumbnailBounds.y);
			g.setPaint(p);
			g.setColor(c);

		}

		private void drawHighlight(Graphics2D g) {
			Stroke oldStroke = g.getStroke();
			Color oldColor = g.getColor();
			Paint oldPaint = g.getPaint();
			Stroke borderStroke;

			Color borderColor = Color.BLUE;
			Point2D center = new Point2D.Float((float)thumbnailBounds.getWidth()/2,
					(float)thumbnailBounds.getHeight()/2);
			float radius = (float)thumbnailBounds.getWidth() + 25;
			float[] dist = {.2f, .8f};

			borderStroke =
					new BasicStroke(50f,
							BasicStroke.CAP_BUTT,
							BasicStroke.JOIN_MITER);
			Color highlightColor = new Color(borderColor.getRed(),borderColor.getGreen(),borderColor.getBlue(), 255);
			Color[] colors = {highlightColor, Color.WHITE};
			RadialGradientPaint gradient =
					new RadialGradientPaint(center, radius, dist, colors);
			g.setPaint(gradient);

			g.drawRoundRect(0, 0, ((int) thumbnailBounds.width) - 1, ((int) thumbnailBounds.height) - 1, 10, 10);
			g.setStroke(borderStroke);
			g.drawRoundRect(0, 0, ((int) thumbnailBounds.width) - 1, ((int) thumbnailBounds.height) - 1, 10, 10);

			g.setStroke(oldStroke);
			g.setPaint(oldPaint);
			g.setColor(oldColor);
		}

		private void drawHistoryHighlight(Graphics2D g) {
			Stroke oldStroke = g.getStroke();
			Color oldColor = g.getColor();
			Paint oldPaint = g.getPaint();
			Stroke borderStroke;
			long[] mostRecentFrames = new long[1];
			for (int i = 0; i < mostRecentFrames.length; i++)
			{
				CHistoryController.Frame f = CHistoryController.getInstance().getFrame(i);
				if (f != null && f instanceof HistoryFrame)
					mostRecentFrames[i] =  ((HistoryFrame)f).getCanvasId();
				else
					mostRecentFrames[i] = 0l;
			}

//			for (int i = 0; i < mostRecentFrames.length; i++)
//			if (getCanvasId() == mostRecentFrames[i])
//			{
//				g.setColor(new Color(0, 0, 0, (int)(255 * (((float)5 - i)/5))));
//				borderStroke =
//		        new BasicStroke(4.0f,
//		                        BasicStroke.CAP_BUTT,
//		                        BasicStroke.JOIN_MITER);
//
//			}

			Color borderColor = Color.BLUE;
			Point2D center = new Point2D.Float((float)thumbnailBounds.getWidth()/2,
					(float)thumbnailBounds.getHeight()/2);
		     float radius = (float)thumbnailBounds.getWidth() + 25;
		     float[] dist = {.2f, .8f};

			if (getCanvasId() == mostRecentFrames[0])
			{
				borderStroke =
		        new BasicStroke(50f,
		                        BasicStroke.CAP_BUTT,
		                        BasicStroke.JOIN_MITER);
			     Color highlightColor = new Color(borderColor.getRed(),borderColor.getGreen(),borderColor.getBlue(), 255);
			     Color[] colors = {highlightColor, Color.WHITE};
			     RadialGradientPaint gradient =
			         new RadialGradientPaint(center, radius, dist, colors);
				g.setPaint(gradient);

				g.drawRoundRect(0, 0, ((int) thumbnailBounds.width) - 1, ((int) thumbnailBounds.height) - 1, 10, 10);
				g.setStroke(borderStroke);
				g.drawRoundRect(0, 0, ((int) thumbnailBounds.width) - 1, ((int) thumbnailBounds.height) - 1, 10, 10);
			}

			for (int i = 1; i < mostRecentFrames.length; i++)
				if (getCanvasId() == mostRecentFrames[i])
				{
					borderStroke =
							new BasicStroke(50f,
									BasicStroke.CAP_BUTT,
									BasicStroke.JOIN_MITER);
					int opacityFactor = (int)(255 * 0.5f * ((float)mostRecentFrames.length - i)/mostRecentFrames.length);
					Color highlightColor = new Color(borderColor.getRed(),borderColor.getGreen(),borderColor.getBlue(), opacityFactor);
					Color[] colors = {highlightColor, Color.WHITE};
					RadialGradientPaint gradient =
							new RadialGradientPaint(center, radius, dist, colors);
					g.setPaint(gradient);
					g.setStroke(borderStroke);
					g.drawRoundRect(0, 0, ((int) thumbnailBounds.width) - 1, ((int) thumbnailBounds.height) - 1, 10, 10);
				}
			g.setStroke(oldStroke);
			g.setPaint(oldPaint);
			g.setColor(oldColor);
		}

		@Override
		protected void layoutChildren()
		{
			titleBar.setX(getX());
			titleBar.setY(getY() - titleBar.HEIGHT);

			userList.setX(getX() + 4);
			userList.setY(getY() + 2);

			thumbnailBounds.setOrigin(getX(), getY());

			if (showingSnapshot)
			{
				canvasSnapshot.snapshot.setBounds(thumbnailBounds.x + BORDER_WIDTH, thumbnailBounds.y + BORDER_WIDTH, thumbnailBounds.width
						- (2 * BORDER_WIDTH), thumbnailBounds.height - (2 * BORDER_WIDTH));
			}
			else
			{
				canvasAddress.setBounds(thumbnailBounds.x + BORDER_WIDTH, thumbnailBounds.y + BORDER_WIDTH, thumbnailBounds.width - (2 * BORDER_WIDTH),
						thumbnailBounds.height - (2 * BORDER_WIDTH));
			}

			cellIcon.setBounds(new Rectangle((int)thumbnailBounds.x + BORDER_WIDTH, (int)thumbnailBounds.y + BORDER_WIDTH,64,64));
			cellIcon.setPaintInvalid(false);

			pin.setBounds(thumbnailBounds.x + thumbnailBounds.width - pin.getBoundsReference().width, thumbnailBounds.y, pin.getBoundsReference().width, pin.getBoundsReference().height);
//			cellIcon.moveToFront();
		}
	}

	private class TitleBar extends PComposite
	{
		private final int HEIGHT = THUMBNAIL_SIZE.width / 7;
		private final int LEFT_INSET = 2;
		private final int TEXT_INSET = 1;

		private final int FADE_HEIGHT = HEIGHT;
		private final Color MASK_COLOR = new Color(0xFF, 0xFF, 0xFF, 0xDD);
		private final Color TRANSPARENT = new Color(0xFF, 0xFF, 0xFF, 0x00);
		private final GradientPaint TOP_FADE = new GradientPaint(0f, 0f, TRANSPARENT, 0f, FADE_HEIGHT / 2, MASK_COLOR);
		private final GradientPaint BOTTOM_FADE = new GradientPaint(0f, FADE_HEIGHT / 2, MASK_COLOR, 0f, FADE_HEIGHT, TRANSPARENT);

		private final PText title = new PText();

		public TitleBar()
		{
			// width is arbitrary, it will be immediately changed by the Shell
			setBounds(0, 0, 100, HEIGHT);
			title.setFont(new Font("Helvetica", Font.PLAIN, THUMBNAIL_SIZE.width / 10));

			CalicoDraw.addChildToNode(this, title);
//			addChild(title);
			updateTitle();
		}

		private void updateTitle()
		{
			int index = getSiblingIndex();

//			String tag = "";
			String titlePrefix = "";
//			if (!CIntentionCellController.getInstance().isRootCanvas(canvas_uuid))
				titlePrefix = getTitlePrefix() /*+ getSiblingIndex() + ". "*/;

//			if (getIntentionTypeId() != -1
//					&&  IntentionCanvasController.getInstance().intentionTypeExists(getIntentionTypeId()))
//				tag = " (" + IntentionCanvasController.getInstance().getIntentionType(getIntentionTypeId()).getName() + ")";

			title.setText(titlePrefix + getTitle() /* + tag*/);
//			CalicoDraw.repaint(this);
//			repaint();
		}

		@Override
		protected void layoutChildren()
		{
			PBounds bounds = getBounds();
			title.setBounds(bounds.x + LEFT_INSET, bounds.y + TEXT_INSET, bounds.width - LEFT_INSET, bounds.height - (2 * TEXT_INSET));
		}

		@Override
		protected void paint(PPaintContext paintContext)
		{
			Graphics2D g = paintContext.getGraphics();
			int yTitle = (int) (title.getY() - (((FADE_HEIGHT - HEIGHT) / 2)));
			g.translate(title.getX(), yTitle);

			g.setPaint(TOP_FADE);
			g.fillRect(-2, 0, ((int) title.getBounds().width) + 4, FADE_HEIGHT / 2);
			g.setPaint(BOTTOM_FADE);
			g.fillRect(-2, FADE_HEIGHT / 2, ((int) title.getBounds().width) + 4, FADE_HEIGHT);
			g.translate(-title.getX(), -yTitle);

			super.paint(paintContext);
		}
	}

	public int getSiblingIndex() {
		long parentUUID = CIntentionCellController.getInstance().getCIntentionCellParent(canvas_uuid);
		long[] siblings = CIntentionCellController.getInstance().getCIntentionCellChildren(parentUUID);

		int index = 1;
		for (int i = 0; i < siblings.length; i++)
		{
			if (siblings[i] == canvas_uuid)
				index = i+1;
		}
		return index;
	}

	public String getTitlePrefix() {

		String titlePrefix = "";

		//get parent cell
		int centerRingIndex = 0;
		int jumpsToRoot = 0;
		long parentCanvasId = CIntentionCellController.getInstance().getCIntentionCellParent(canvas_uuid);
		while (parentCanvasId > 0l)
		{
			long nextParent = CIntentionCellController.getInstance().getCIntentionCellParent(parentCanvasId);
			if (nextParent > 0l)
			{
				jumpsToRoot++;
				centerRingIndex = CIntentionCellController.getInstance().getCellByCanvasId(parentCanvasId).getSiblingIndex();
			}
			parentCanvasId = nextParent;
		}

//		long parentCanvasId = CIntentionCellController.getInstance().getCIntentionCellParent(canvas_uuid);
//		if (parentCanvasId > 0l)
//		{
//			CIntentionCell parentCell = CIntentionCellController.getInstance().getCellByCanvasId(parentCanvasId);
//			titlePrefix += parentCell.getTitlePrefix();
//		}

		if (CIntentionCellController.getInstance().isRootCanvas(CIntentionCellController.getInstance().getCIntentionCellParent(canvas_uuid)))
			titlePrefix = getSiblingIndex() + ". ";
		else if (!CIntentionCellController.getInstance().isRootCanvas(canvas_uuid))
			titlePrefix = centerRingIndex + "." + jumpsToRoot + " ";
//			titlePrefix += getSiblingIndex() + ". ";
//		else
//		{
//			int clusterIndex = getClusterIndex();
//			if (clusterIndex != -1)
//				titlePrefix += "C" + clusterIndex + ".";
//			else
//				titlePrefix += "C#.";
//		}

		return titlePrefix;
	}

	public int getClusterIndex()
	{
		return IntentionGraph.getInstance().getClusterIndex(CIntentionCellController.getInstance().getClusterRootCanvasId(canvas_uuid)) + 1;
	}

	private class UserList extends PText
	{
		public UserList()
		{
			setText("Username"); // template, for sizing
			setFont(new Font("Helvetica", Font.BOLD, THUMBNAIL_SIZE.width / 10));
			setTextPaint(Color.BLUE);
			setBounds(this.getBounds().getBounds());
			setConstrainWidthToTextWidth(true);
			setConstrainHeightToTextHeight(true);

			setText("");
		}

		void updateUsers()
		{
			StringBuilder userListText = new StringBuilder();
			int[] clients = CCanvasController.canvasdb.get(canvas_uuid).getClients();
			for (int i = 0; i < clients.length; i++)
			{
				if (CalicoDataStore.clientInfo.containsKey(clients[i]) && !CalicoDataStore.clientInfo.get(clients[i]).equals(CalicoDataStore.Username))
				{
					userListText.append(CalicoDataStore.clientInfo.get(clients[i]) + "\n");
				}

			}

			if (!getText().equals(userListText.toString()))
			{
				setText(userListText.toString());
//				CalicoDraw.repaint(this);
//				repaint();
			}
		}

		@Override
		protected void paint(PPaintContext paintContext)
		{
			Graphics2D g = paintContext.getGraphics();
			g.setColor(Color.white);
			g.fill(getBounds());

			super.paint(paintContext);
		}
	}

	private class CanvasSnapshot
	{
		private final PImage snapshot = new PImage();

		private boolean isDirty = true;

		boolean isOnScreen()
		{
			return (isInGraphFootprint() && scaleAllowsSnapshot());
		}

		void contentsChanged()
		{
			if (isInGraphFootprint() && shell.showingSnapshot)
			{
				updateSnapshot();
			}
			else
			{
				isDirty = true;
			}
		}

		private void updateSnapshot()
		{
			long start = System.currentTimeMillis();
			snapshot.setImage(IntentionalInterfacesGraphics.createCanvasThumbnail(canvas_uuid, THUMBNAIL_INSETS));
			CalicoDraw.setNodeBounds(snapshot, shell.thumbnailBounds);
//			snapshot.setBounds(shell.thumbnailBounds);
			isDirty = false;

//			CalicoDraw.repaint(snapshot);
//			snapshot.repaint();
		}
	}

	@Override
	public void handleCalicoEvent(int event, CalicoPacket p) {

		if (event == IntentionalInterfacesNetworkCommands.CIC_TAG
				|| event == IntentionalInterfacesNetworkCommands.CIC_UNTAG
				|| event == IntentionalInterfacesNetworkCommands.CIC_SET_TITLE
				|| event == IntentionalInterfacesNetworkCommands.CIC_UPDATE_FINISHED
				|| event == IntentionalInterfacesNetworkCommands.CIC_TOPOLOGY
				|| event == IntentionalInterfacesNetworkCommands.CLINK_CREATE)
		{
			shell.titleBar.updateTitle();
//			removeIfRootCanvas();
		}
		if (event == IntentionalInterfacesNetworkCommands.CIC_TOPOLOGY
				|| event == IntentionalInterfacesNetworkCommands.CLINK_CREATE)
		{
			SwingUtilities.invokeLater(
					new Runnable() { public void run() {
						hideIfRootCanvas();
					}});

		}

	}

	public void hideIfRootCanvas() {
		//This line of code is added to prevent new cluster centers from appearing in the user's view
		if (
			//There is already a check to not add the shell, but it fails to detect that it's a cluster center so
				//it was added anyways. This next line checks if it's inside.
			IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).getChildrenReference().contains(shell)
			//This next line checks that it's a cluster root. This line returns true when it shouldn't for new
				//CICs, not sure why.
				&& IntentionGraph.getInstance().isClusterRoot(canvas_uuid)
			//The last check that makes this work is to look for links. This if-clause will remove ALL new
				//CICs because they're flagged as canvas centers (even when they're not). Another way to check
				//if the new CIC is a new cluster is to check for CCanvasLinks.
				&& CCanvasLinkController.getInstance().getAnchorIdsByCanvasId(canvas_uuid).size() == 0)
			CalicoDraw.removeChildFromNode(IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT), shell);
		else if (
				!IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT).getChildrenReference().contains(shell)
				&& !IntentionGraph.getInstance().isClusterRoot(canvas_uuid)
				&& CCanvasLinkController.getInstance().getAnchorIdsByCanvasId(canvas_uuid).size() > 0)
			CalicoDraw.addChildToNode(IntentionGraph.getInstance().getLayer(IntentionGraph.Layer.CONTENT), shell);

	}

	public void setCellIcon(CellIconType iconToShow)
	{
		switch (iconToShow)
		{
		case NONE:
			CalicoDraw.setVisible(shell.cellIcon,false);
			break;
		case CREATE_LINK:
			shell.setIconImage(CIntentionCell.iconImage_create);
			CalicoDraw.setVisible(shell.cellIcon,true);
			break;
		case DELETE_LINK:
			shell.setIconImage(CIntentionCell.iconImage_delete);
			CalicoDraw.setVisible(shell.cellIcon,true);
			break;
		}

		this.iconToShow = iconToShow;
	}

	public void moveToFront()
	{
		shell.moveToFront();
	}

	public void hide()
	{
		shell.setVisible(false);
	}

	public void show()
	{
		shell.setVisible(true);
	}

	public boolean getVisible()
	{
		return shell.getVisible();
	}

	public boolean getIsPinned()
	{
		return isPinned;
	}

	public void setIsPinned(boolean value)
	{
		if (isPinned == value)
			return;

		long[] children = CIntentionCellController.getInstance().getCIntentionCellChildren(getCanvasId());
		if (children.length > 0)
			 CIntentionCellController.getInstance().getCellByCanvasId(children[0]).setIsPinned(value);

		isPinned = value;
		pin.setVisible(isPinned);
		CalicoDraw.repaint(pin);
		//show/hide pin
	}

	public void setPinHighlighted(boolean value)
	{
		if (value)
			pin.setImage(pinSelectedImage);
		else
			pin.setImage(pinImage);
	}

	/**
	 *
	 * @param p Point in global bounds
	 * @return
	 */
	public boolean pinImageContainsPoint(Point p)
	{
//		System.out.println("Rect: " + pin.getGlobalBounds().toString() + "\nPoint: " + p.toString() );
		return pin.getGlobalBounds().contains(p);
	}

	public void setDragging(boolean value)
	{
		if (value)
			shell.setTransparency(.7f);
		else
			shell.setTransparency(1.0f);
	}

	public void showBubbleMenu() {
		boolean isRootCanvas = CIntentionCellController.getInstance().isRootCanvas(getCanvasId());
		boolean isRootChildCanvas = CIntentionCellController.getInstance().isRootCanvas(
				CIntentionCellController.getInstance().getCIntentionCellParent(getCanvasId()));

		ArrayList<PieMenuButton> buttons = new ArrayList<PieMenuButton>();

		buttons.add(setCanvasTitleButton);

		if (CCanvasController.canvasdb.size() > 1
				&& isRootChildCanvas)
		{
			buttons.add(deleteCanvasButton);
			buttons.add(linkButton);
			buttons.add(zoomToCenterRingButton);
			if (CIntentionCellController.getInstance().getCIntentionCellChildren(getCanvasId()).length > 0)
				buttons.add(zoomToBranchButton);
		}
		else if (CCanvasController.canvasdb.size() > 1
				&& !isRootCanvas)
		{
			buttons.add(deleteCanvasButton);
			buttons.add(linkButton);
			buttons.add(zoomToCenterRingButton);
			buttons.add(zoomToBranchButton);
		}

		if (getIsPinned())
			buttons.add(unpinCanvas);

		BubbleMenu.displayBubbleMenu(getId(), true, BUBBLE_MENU_TYPE_ID, buttons.toArray(new PieMenuButton[buttons.size()]));
	}

	/**
	 * Integration point for a CIC with the bubble menu.
	 *
	 * @author Byron Hawkins
	 */
	private static class BubbleMenuComponentType implements BubbleMenu.ComponentType
	{
		@Override
		public PBounds getBounds(long uuid)
		{
			PBounds local = CIntentionCellController.getInstance().getCellById(uuid).getGlobalBounds();
			if (CCanvasController.exists(CCanvasController.getCurrentUUID()))
				return new PBounds(CCanvasController.canvasdb.get(CCanvasController.getCurrentUUID()).getLayer().globalToLocal(local));
			else
				return local;
		}

		@Override
		public void highlight(boolean b, long uuid)
		{
			if (CIntentionCellController.getInstance().getCellById(uuid) != null)
				CIntentionCellController.getInstance().getCellById(uuid).setHighlighted(b);
		}

		@Override
		public int getButtonPosition(String buttonClassname)
		{
			if (buttonClassname.equals(DeleteCanvasButton.class.getName()))
			{
				return 1;
			}
			if (buttonClassname.equals(CreateLinkButton.class.getName()))
			{
				return 2;
			}
			if (buttonClassname.equals(ZoomToClusterButton.class.getName()))
			{
				return 3;
			}
			if (buttonClassname.equals(SetCanvasTitleButton.class.getName()))
			{
				return 3;
			}
			if (buttonClassname.equals(UnpinCanvas.class.getName()))
			{
				return 5;
			}
			if (buttonClassname.equals(ZoomToCenterRingButton.class.getName()))
			{
				return 7;
			}
			if (buttonClassname.equals(ZoomToBranchButton.class.getName()))
			{
				return 8;
			}

			return 0;
		}
	}
}


text:
extern Engine engine;

class Controller : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int windowWidth READ windowWidth WRITE setWindowWidth NOTIFY windowWidthChanged)
    Q_PROPERTY(int windowHeight READ windowHeight WRITE setWindowHeight NOTIFY windowHeightChanged)
    Q_PROPERTY(int t READ t WRITE setT NOTIFY tChanged)
    Q_PROPERTY(QString room READ room NOTIFY roomChanged)
    Q_PROPERTY(State state READ state NOTIFY stateChanged)
    Q_PROPERTY(QQmlListProperty<QGuiData> currentFrame READ currentFrame NOTIFY currentFrameChanged)
    Q_ENUMS(State)
public:

    enum State {
        INITIALIZING = Engine::INITIALIZING,
        GAME = Engine::GAME,
        DIALOG = Engine::DIALOG,
        TRANSITION = Engine::TRANSITION
    };

    explicit Controller(QObject *parent = 0);
    ~Controller();

    int windowWidth() const;
    void setWindowWidth(int width);

    int windowHeight() const;
    void setWindowHeight(int height);

    int t() const {return _t;}
    void setT(int t);

    QString room() const;

    State state() const;

    QQmlListProperty<QGuiData> currentFrame();

    static int listCount(QQmlListProperty<QGuiData> *list);
    static QGuiData *listAt(QQmlListProperty<QGuiData> *list, int index);

signals:
    void windowWidthChanged();
    void windowHeightChanged();
    void tChanged();
    void roomChanged();
    void stateChanged();
    void currentFrameChanged();

public slots:
    void update();
    void click(float x, float y);
    void updateBgm();
    void updateSFX();

private:
    void clearCurrentFrameData();

private:
    int _t;
    QString current_room;
    State current_state;
    QList<QGuiData *> _currentFrameData;
    QSound *bgm;

};

#endif // CONTROLLER_H

redpajama_set_name: RedPajamaGithub


text:
class NestedInteger(object):
   def __init__(self, value=None):
       """
       If value is not specified, initializes an empty list.
       Otherwise initializes a single integer equal to value.
       """

   def isInteger(self):
       """
       @return True if this NestedInteger holds a single integer, rather than a nested list.
       :rtype bool
       """

   def add(self, elem):
       """
       Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
       :rtype void
       """

   def setInteger(self, value):
       """
       Set this NestedInteger to hold a single integer equal to value.
       :rtype void
       """

   def getInteger(self):
       """
       @return the single integer that this NestedInteger holds, if it holds a single integer
       Return None if this NestedInteger holds a nested list
       :rtype int
       """

   def getList(self):
       """
       @return the nested list that this NestedInteger holds, if it holds a nested list
       Return None if this NestedInteger holds a single integer
       :rtype List[NestedInteger]
       """

class Solution(object):
    def deserialize(self, s):
        if not s:
            return NestedInteger()

        if s[0] != '[':
            return NestedInteger(int(s))

        stk = []

        i = 0
        for j in xrange(len(s)):
            if s[j] == '[':
                stk += NestedInteger(),
                i = j+1
            elif s[j] in ',]':
                if s[j-1].isdigit():
                    stk[-1].add(NestedInteger(int(s[i:j])))
                if s[j] == ']' and len(stk) > 1:
                    cur = stk[-1]
                    stk.pop();
                    stk[-1].add(cur)
                i = j+1

        return stk[-1]


text:
package tfprotov5

import (
	"bytes"
	"errors"

	"github.com/hashicorp/terraform-plugin-go/tfprotov5/tftypes"
	"github.com/vmihailenco/msgpack"
)

// ErrUnknownDynamicValueType is returned when a DynamicValue has no MsgPack or
// JSON bytes set. This should never be returned during the normal operation of
// a provider, and indicates one of the following:
//
// 1. terraform-plugin-go is out of sync with the protocol and should be
// updated.
//
// 2. terrafrom-plugin-go has a bug.
//
// 3. The `DynamicValue` was generated or modified by something other than
// terraform-plugin-go and is no longer a valid value.
var ErrUnknownDynamicValueType = errors.New("DynamicValue had no JSON or msgpack data set")

// NewDynamicValue creates a DynamicValue from a tftypes.Value. You must
// specify the tftype.Type you want to send the value as, and it must be a type
// that is compatible with the Type of the Value. Usually it should just be the
// Type of the Value, but it can also be the DynamicPseudoType.
func NewDynamicValue(t tftypes.Type, v tftypes.Value) (DynamicValue, error) {
	b, err := v.MarshalMsgPack(t) //nolint:staticcheck
	if err != nil {
		return DynamicValue{}, err
	}
	return DynamicValue{
		MsgPack: b,
	}, nil
}

// DynamicValue represents a nested encoding value that came from the protocol.
// The only way providers should ever interact with it is by calling its
// `Unmarshal` method to retrive a `tftypes.Value`. Although the type system
// allows for other interactions, they are explicitly not supported, and will
// not be considered when evaluating for breaking changes. Treat this type as
// an opaque value, and *only* call its `Unmarshal` method.
type DynamicValue struct {
	MsgPack []byte
	JSON    []byte
}

// Unmarshal returns a `tftypes.Value` that represents the information
// contained in the DynamicValue in an easy-to-interact-with way. It is the
// main purpose of the DynamicValue type, and is how provider developers should
// obtain config, state, and other values from the protocol.
//
// Pass in the type you want the `Value` to be interpreted as. Terraform's type
// system encodes in a lossy manner, meaning the type information is not
// preserved losslessly when going over the wire. Sets, lists, and tuples all
// look the same, as do user-specified values when the provider has a
// DynamicPseudoType in its schema. Objects and maps all look the same, as
// well, as do DynamicPseudoType values sometimes. Fortunately, the provider
// should already know the type; it should be the type of the schema, or
// PseudoDynamicType if that's what's in the schema. `Unmarshal` will then
// parse the value as though it belongs to that type, if possible, and return a
// `tftypes.Value` with the appropriate information. If the data can't be
// interpreted as that type, an error will be returned saying so. In these
// cases, double check to make sure the schema is declaring the same type being
// passed into `Unmarshal`.
//
// In the event an ErrUnknownDynamicValueType is returned, one of three things
// has happened:
//
// 1. terraform-plugin-go is out of date and out of sync with the protocol, and
// an issue should be opened on its repo to get it updated.
//
// 2. terraform-plugin-go has a bug somewhere, and an issue should be opened on
// its repo to get it fixed.
//
// 3. The provider or a dependency has modified the `DynamicValue` in an
// unsupported way, or has created one from scratch, and should treat it as
// opaque and not modify it, only calling `Unmarshal` on `DynamicValue`s
// received from RPC requests.
func (d DynamicValue) Unmarshal(typ tftypes.Type) (tftypes.Value, error) {
	if d.JSON != nil {
		return jsonUnmarshal(d.JSON, typ, tftypes.AttributePath{})
	}
	if d.MsgPack != nil {
		r := bytes.NewReader(d.MsgPack)
		dec := msgpack.NewDecoder(r)
		return msgpackUnmarshal(dec, typ, tftypes.AttributePath{})
	}
	return tftypes.Value{}, ErrUnknownDynamicValueType
}


text:
namespace Microsoft.OData.Core.Metadata
{
    #region Namespaces
    using System.Diagnostics.CodeAnalysis;
    #endregion Namespaces

    /// <summary>Represents an annotation to hold information for a particular property.</summary>
    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm", Justification = "Camel-casing in class name.")]
    public sealed class ODataEdmPropertyAnnotation
    {
        /// <summary> Gets the behavior for readers when reading property with null value. </summary>
        /// <returns>The behavior for readers when reading property with null value.</returns>
        public ODataNullValueBehaviorKind NullValueReadBehaviorKind
        {
            get;
            set;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.vividsolutions.jts.util Class Hierarchy
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package com.vividsolutions.jts.util

Package Hierarchies:
All Packages

Class Hierarchy

class java.lang.Object

class com.vividsolutions.jts.util.Assert
class com.vividsolutions.jts.util.CollectionUtil
class com.vividsolutions.jts.util.CoordinateArrayFilter (implements com.vividsolutions.jts.geom.CoordinateFilter)

class com.vividsolutions.jts.util.CoordinateCountFilter (implements com.vividsolutions.jts.geom.CoordinateFilter)

class com.vividsolutions.jts.util.Debug
class com.vividsolutions.jts.util.GeometricShapeFactory
class com.vividsolutions.jts.util.Stopwatch
class java.lang.Throwable (implements java.io.Serializable)

class java.lang.Exception

class java.lang.RuntimeException

class com.vividsolutions.jts.util.AssertionFailedException

class com.vividsolutions.jts.util.UniqueCoordinateArrayFilter (implements com.vividsolutions.jts.geom.CoordinateFilter)

Interface Hierarchy

interface com.vividsolutions.jts.util.CollectionUtil.Function

      Overview
      Package
      Class
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
package proguard.classfile.constant;

import proguard.classfile.*;
import proguard.classfile.constant.visitor.ConstantVisitor;

/**
 * This Constant represents a method reference constant in the constant pool.
 *
 * @author Eric Lafortune
 */
public class MethodrefConstant extends RefConstant
{
    /**
     * Creates an uninitialized MethodrefConstant.
     */
    public MethodrefConstant()
    {
    }

    /**
     * Creates a new MethodrefConstant with the given name and type indices.
     * @param u2classIndex         the index of the class in the constant pool.
     * @param u2nameAndTypeIndex   the index of the name and type entry in the constant pool.
     * @param referencedClass      the referenced class.
     * @param referencedMember     the referenced member info.
     */
    public MethodrefConstant(int    u2classIndex,
                             int    u2nameAndTypeIndex,
                             Clazz  referencedClass,
                             Member referencedMember)
    {
        this.u2classIndex       = u2classIndex;
        this.u2nameAndTypeIndex = u2nameAndTypeIndex;
        this.referencedClass    = referencedClass;
        this.referencedMember   = referencedMember;
    }

    // Implementations for Constant.

    public int getTag()
    {
        return ClassConstants.CONSTANT_Methodref;
    }

    public void accept(Clazz clazz, ConstantVisitor constantVisitor)
    {
        constantVisitor.visitMethodrefConstant(clazz, this);
    }
}


text:
package com.infinities.keystone4j.credential.api.command;

import java.util.List;

import com.infinities.keystone4j.NonTruncatedCommand;
import com.infinities.keystone4j.credential.CredentialDriver;
import com.infinities.keystone4j.model.credential.Credential;

public class ListCredentialsForUserCommand extends AbstractCredentialCommand implements
		NonTruncatedCommand<List<Credential>> {

	private final String userid;

	public ListCredentialsForUserCommand(CredentialDriver credentialDriver, String userid) {
		super(credentialDriver);
		this.userid = userid;
	}

	@Override
	public List<Credential> execute() throws Exception {
		return this.getCredentialDriver().listCredentialsForUser(userid);
	}

}


text:
namespace Incoding.UnitTest.MSpecGroup
{
    #region << Using >>

    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;
    using System.Text;
    using FluentValidation.Results;
    using Incoding.Data;
    using Incoding.Extensions;
    using Incoding.MSpecContrib;
    using Machine.Specifications;
    using Machine.Specifications.Annotations;

    #endregion

    [Subject(typeof(ShouldExtensions))]
    public class When_should_extensions
    {
        It should_be_conditional = () => Pleasure.Generator.TheRuCulture().Name.ShouldEqual("ru-RU");

        It should_be_date = () => DateTime.Now.ShouldBeDate(DateTime.Now.AddMinutes(2));

        It should_be_date_nullable = () =>
                                     {
                                         DateTime? leftNullable = DateTime.Now;
                                         var rightNullable = leftNullable;
                                         leftNullable.ShouldBeDate(rightNullable);
                                     };

        It should_be_date_nullable_with_wrong_has_value = () => Catch.Exception(() =>
                                                                                {
                                                                                DateTime? leftNullable = DateTime.Now;
                                                                                DateTime? rightNullable = null;
                                                                                leftNullable.ShouldBeDate(rightNullable);
                                                                                }).ShouldBeAssignableTo<SpecificationException>();

        It should_be_equal_weak_dictionary = () =>
                                             {
                                                 IDictionary<string, int> left = Pleasure.ToDynamicDictionary<int>(new { value = 2 });
                                                 IDictionary<string, int> right = Pleasure.ToDynamicDictionary<int>(new { value = 2 });
                                                 left.ShouldEqualWeak(right);
                                             };

        It should_be_equal_weak_dual = () =>
                                       {
                                           var left = new { Field = 1 };
                                           var right = new { Field = 1 };
                                           left.ShouldEqualWeakDual(right);
                                       };

        It should_be_equal_weak_specification = () =>
                                                {
                                                    var spec1 = new FakeSpecification(Pleasure.Generator.TheSameString());
                                                    var spec2 = new FakeSpecification(Pleasure.Generator.TheSameString());
                                                    spec1.ShouldEqualWeak(spec2);
                                                };

        It should_be_failure_by_count = () =>
                                        {
                                            var valResult = new ValidationResult();
                                            valResult.Errors.Add(new ValidationFailure("Property", Pleasure.Generator.TheSameString()));
                                            string error = Pleasure.Generator.String();
                                            valResult.Errors.Add(new ValidationFailure("Property", error));
                                            var exception = Catch.Exception(() => valResult.ShouldBeFailure<When_should_extensions>(r => r.Property, Pleasure.Generator.TheSameString()));
                                            exception.ShouldBeAssignableTo<SpecificationException>();

                                            var st = new StringBuilder();
                                            st.AppendLine("Expected: 2 failure But was:  1 failure");
                                            st.AppendLine("Property:TheSameString;Property:{0};".F(error));
                                            exception.Message.ShouldEqual(st.ToString());
                                        };

        It should_be_failure_by_property = () =>
                                           {
                                               var valResult = new ValidationResult();
                                               valResult.Errors.Add(new ValidationFailure("AnyProperty", Pleasure.Generator.TheSameString()));
                                               Catch.Exception(() => valResult.ShouldBeFailure<When_should_extensions>(r => r.Property, Pleasure.Generator.TheSameString())).ShouldBeAssignableTo<SpecificationException>();
                                           };

        It should_be_failure_without_error = () =>
                                             {
                                                 var validationResult = new ValidationResult();
                                                 var errorMessages = Pleasure.ToArray(Pleasure.Generator.String(), Pleasure.Generator.String(), Pleasure.Generator.String());
                                                 var exception = Catch.Exception(() => validationResult.ShouldBeFailure<When_should_extensions>(r => r.Property, errorMessages));
                                                 exception.ShouldBeAssignableTo<SpecificationException>();
                                                 exception.Message.ShouldContain("Expected: {0} failure But was:  {1} failure".F(validationResult.Errors.Count, errorMessages.Length));
                                             };

        It should_be_is_weak = () => Pleasure.Generator.Invent<FakeCompareObject>().IsEqualWeak(Pleasure.Generator.Invent<FakeCompareObject>()).ShouldBeFalse();

        It should_be_key_value = () => Pleasure
                                               .ToDictionary(new KeyValuePair<string, int>(Pleasure.Generator.TheSameString(), Pleasure.Generator.TheSameNumber()))
                                               .ShouldBeKeyValue(Pleasure.Generator.TheSameString(), Pleasure.Generator.TheSameNumber());

        It should_be_key_value_with_wrong_key = () => Catch
                                                              .Exception(() => Pleasure
                                                                                .ToDictionary(new KeyValuePair<string, int>(Pleasure.Generator.TheSameString(), Pleasure.Generator.TheSameNumber()))
                                                                                .ShouldBeKeyValue(Pleasure.Generator.String(), Pleasure.Generator.TheSameNumber()))
                                                              .ShouldBeAssignableTo<SpecificationException>();

        It should_be_key_value_with_wrong_value = () => Catch
                                                                .Exception(() => Pleasure
                                                                                .ToDictionary(new KeyValuePair<string, int>(Pleasure.Generator.TheSameString(), Pleasure.Generator.TheSameNumber()))
                                                                                .ShouldBeKeyValue(Pleasure.Generator.TheSameString(), Pleasure.Generator.PositiveNumber()))
                                                                .ShouldBeAssignableTo<SpecificationException>();

        It should_be_not_failure = () =>
                                   {
                                       var valResult = new ValidationResult();
                                       valResult.Errors.Add(new ValidationFailure("Property", Pleasure.Generator.TheSameString()));
                                       string customMessage = Pleasure.Generator.String();
                                       valResult.Errors.Add(new ValidationFailure("Property", customMessage));
                                       valResult.ShouldBeFailure<When_should_extensions>(r => r.Property, Pleasure.Generator.TheSameString(), customMessage);
                                   };

        It should_be_not_key = () => Pleasure
                                             .ToDictionary(new KeyValuePair<string, int>(Pleasure.Generator.TheSameString(), 1))
                                             .ShouldNotBeKey(Pleasure.Generator.String());

        It should_be_not_key_with_exists_key = () => Catch
                                                             .Exception(() => Pleasure
                                                                                .ToDictionary(new KeyValuePair<string, int>(Pleasure.Generator.TheSameString(), 1))
                                                                                .ShouldNotBeKey(Pleasure.Generator.TheSameString()))
                                                             .ShouldBeAssignableTo<SpecificationException>();

        It should_be_not_satisfy = () => DateTime.Now.ShouldNotSatisfy(time => time.Date != DateTime.Now.Date);

        It should_be_satisfy = () => DateTime.Now.ShouldSatisfy(time => time.Date == DateTime.Now.Date);

        It should_be_the_same_string = () => Pleasure.Generator.TheSameString().ShouldBeTheSameString();

        It should_be_time_with_date = () => new DateTime(1, 2, 3, 4, 5, 6).ShouldBeTime(4, 5, 6);

        It should_be_time_with_date_and_date = () =>
                                               {
                                                   var time = new DateTime(1, 2, 3, 4, 5, 6);
                                                   time.ShouldBeTime(new DateTime(2006, 2, 5, time.Hour, time.Minute, time.Second, time.Millisecond));
                                               };

        It should_be_time_with_time_span = () => new TimeSpan(1, 2, 3).ShouldBeTime(1, 2, 3);

        It should_be_time_with_time_span_and_time_span = () =>
                                                         {
                                                             var timeSpan = new TimeSpan(1, 2, 3);
                                                             timeSpan.ShouldBeTime(new TimeSpan(timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds));
                                                         };

        It should_be_weak_each_with_forward_with_index = () =>
                                                         {
                                                             var left = Pleasure.Generator.Invent<FakeCompareObject>();
                                                             var right = new FakeCompareObject { Fake = left.Fake2, Fake2 = left.Fake };
                                                             var rightArray = Pleasure.ToReadOnly(right);
                                                             Pleasure.ToList(left).ShouldEqualWeakEach(rightArray, (factory, i) => factory
                                                                                .ForwardToValue(r => r.Fake, rightArray[i].Fake2)
                                                                                .ForwardToValue(r => r.Fake2, rightArray[i].Fake));
                                                         };

        It should_not_be_equal_weak_specification = () =>
                                                    {
                                                        var spec1 = new FakeSpecification(Pleasure.Generator.String());
                                                        var spec2 = new FakeSpecification(Pleasure.Generator.String());
                                                        spec1.ShouldEqualWeak(spec2);
                                                    };

        It should_not_be_failure = () => new ValidationResult()
                                                 .ShouldNotBeFailure<When_should_extensions>(r => r.Property);

        It should_not_be_failure_wrong = () =>
                                         {
                                             var valResult = new ValidationResult(new List<ValidationFailure>
                                                                                {
                                                                                new ValidationFailure("Property", Pleasure.Generator.TheSameString()),
                                                                                new ValidationFailure("Property", Pleasure.Generator.String())
                                                                                });
                                             Catch.Exception(() => valResult.ShouldNotBeFailure<When_should_extensions>(r => r.Property)).ShouldBeAssignableTo<SpecificationException>();
                                         };

        public string Property { get; set; }

        #region Fake classes

        class FakeCompareObject
        {
            #region Properties

            public string Fake { get; set; }

            public string Fake2 { get; set; }

            #endregion
        }

        class FakeSpecification : Specification<IEntity>
        {
            #region Fields

            [UsedImplicitly]
            readonly string id;

            #endregion

            #region Constructors

            public FakeSpecification(string id)
            {
                this.id = id;
            }

            #endregion

            public override Expression<Func<IEntity, bool>> IsSatisfiedBy()
            {
                throw new NotImplementedException();
            }
        }

        #endregion
    }
}


text:
/**
 *
 */
package com.withinet.opaas.controller.system;

import java.io.File;
import java.io.IOException;

/**
 * Object offering crud type interface for file system functions
 * @author Folarin
 *
 */
public interface FileService {
	public File createFile (String fileLocation);

	public boolean deleteFile (String fileLocation) throws IOException;

	public boolean updateFile (String fileLocation, File file) throws IOException;

	public void copyFile(String dest, String src) throws IOException;
}


text:
<?php
$pageTitle = 'Lab Assistant Home Page';
require("header.php");

if(isset($_SESSION['verified']) || isset($_SESSION['admin']))
{

?>

		<?php include('reload/showSchedChng.php'); ?>

<?php
	include ("footer.php");
}
else
	echo "
YOU ARE NOT AUTORIZED TO SEE THIS PAGE!
";
?>


text:
"""
Created on Fri Aug 29 16:06:47 2014

@author: Natural Solutions (Thomas)
"""

from sqlalchemy import (
    Column,
    DateTime,
    ForeignKey,
    func,
    Index,
    Integer,
    Numeric,
    Sequence,
    String,
    UniqueConstraint
)

from ecorelevesensor.models import Base, dbConfig

dialect = dbConfig['dialect']

class Object(Base):
    __tablename__ = 'T_Object'
    id = Column('PK_id', Integer, Sequence('seq_object_pk_id'),
                   primary_key=True)
    creator = Column('FK_creator', Integer, nullable=False)
    creation_date = Column(DateTime, server_default=func.now(), nullable=False)
    identifier = Column(String(32), nullable=False)
    type_ = Column(String(16), nullable=False)
    manufacturer = Column(String(64))
    model = Column(String(64))
    __table_args__ = (
            Index('idx_Tobject_type_identifier', type_, identifier),
            UniqueConstraint('identifier'),
    )
    __mapper_args__ = {
        'polymorphic_on':type_,
        'polymorphic_identity':'object'
    }

    def __json__(self, request):
        return {
            'id':self.id,
            'manufacturer':self.manufacturer,
            'model':self.model,
            'creator':self.creator,
            'identifier':self.identifier,
            'type':self.type_,
            'creation_date':str(self.creation_date),
        }

class ObjectRfid(Object):
    __mapper_args__ = {
        'polymorphic_identity':'rfid'
    }

class Transmitter(Object):
    platform_id = Column(Integer)

    def __json__(self, request):
        obj = super().__json__(request)
        obj['platform_id'] = self.platform_id
        return obj

    __mapper_args__ = {
        'polymorphic_identity':'transmitter'
    }

class ObjectArgos(Transmitter):
    program_id = Column(Integer)
    __mapper_args__ = {
        'polymorphic_identity':'argos'
    }

class ObjectGsm(Transmitter):
    serial_number = Column(String(32))

    def __json__(self, request):
        obj = super().__json__(request)
        obj['serial_number'] = self.serial_number
        return obj

    __mapper_args__ = {
        'polymorphic_identity':'gsm'
    }


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AzureStorage.Queue;
using Common;
using Core;
using Core.Repositories.Offchain;

namespace AzureRepositories.Offchain
{
    public class SpendCommitmentMonitoringWriter : ISpendCommitmentMonitoringWriter
    {
        private IQueueExt _queue;

        public SpendCommitmentMonitoringWriter(Func<string, IQueueExt> queuFactory)
        {
            _queue = queuFactory(Constants.SpendCommitmentOutputQueue);
        }

        public Task AddToMonitoring(Guid commitmentId, string transactionHash)
        {
            return _queue.PutRawMessageAsync(new SpendCommitmentMonitorindMessage()
            {
                PutDateTime = DateTime.UtcNow,
                TransactionHash = transactionHash,
                CommitmentId = commitmentId
            }.ToJson());
        }
    }
}


text:
package com.stream.fastdevelop.activity;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.stream.fastdevelop.fragment.CommonFragment;

/**
 * Created by 张川川 on 2016/8/21.
 * 通用的Activity
 */
public class CommonActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            String fragmentName = getIntent().getStringExtra("fragment");
            Class<?> aClass = Class.forName(fragmentName);
            CommonFragment commonFragment = ((CommonFragment) aClass.newInstance());
            getFragmentManager().beginTransaction().add(android.R.id.content, commonFragment).commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *
     * @param context 启动用的context
     * @param fragment 内嵌的fragment名字
     */
    public static void jumpToMe(Context context, String fragment){
        Intent intent = new Intent();
        intent.setClass(context, CommonActivity.class);
        intent.putExtra("fragment", fragment);
        context.startActivity(intent);
    }
}


text:
<?php

namespace Drupal\jsonapi\JsonApiResource;

/**
 * An interface for identifying a related resource.
 *
 * Implement this interface when an object is a stand-in for an Entity object.
 * For example, \Drupal\jsonapi\Exception\EntityAccessDeniedHttpException
 * implements this interface because it often replaces an entity in a JSON:API
 * Data object.
 *
 * @internal JSON:API maintains no PHP API. The API is the HTTP API. This class
 *   may change at any time and could break any dependencies on it.
 *
 * @see https://www.drupal.org/project/drupal/issues/3032787
 * @see jsonapi.api.php
 */
interface ResourceIdentifierInterface {

  /**
   * Gets the resource identifier's ID.
   *
   * @return string
   *   A resource ID.
   */
  public function getId();

  /**
   * Gets the resource identifier's JSON:API resource type name.
   *
   * @return string
   *   The JSON:API resource type name.
   */
  public function getTypeName();

  /**
   * Gets the resource identifier's JSON:API resource type.
   *
   * @return \Drupal\jsonapi\ResourceType\ResourceType
   *   The JSON:API resource type.
   */
  public function getResourceType();

}


text:
package com.atlassian.jira.plugins.dvcs.event;

import com.atlassian.jira.config.FeatureManager;
import com.atlassian.jira.plugins.dvcs.util.MockitoTestNgListener;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;

@Listeners (MockitoTestNgListener.class)
public class EventsFeatureTest
{
    @Mock
    FeatureManager featureManager;

    @InjectMocks
    EventsFeature eventsFeature;

    @Test
    public void shouldBeEnabledWhenFeatureIsDisabled() throws Exception
    {
        when(featureManager.isEnabled(EventsFeature.FEATURE_NAME)).thenReturn(false);
        assertThat(eventsFeature.isEnabled(), equalTo(true));
    }

    @Test
    public void shouldBeDisabledWhenFeatureIsEnabled() throws Exception
    {
        when(featureManager.isEnabled(EventsFeature.FEATURE_NAME)).thenReturn(true);
        assertThat(eventsFeature.isEnabled(), equalTo(false));
    }
}


text:
using System.IO;
using System.Text.Encodings.Web;
using Util.Biz.Enums;
using Util.Ui.Configs;
using Util.Ui.Extensions;
using Util.Ui.Material.Extensions;
using Util.Ui.Material.Lists;
using Xunit;
using Xunit.Abstractions;
using String = Util.Helpers.String;

namespace Util.Ui.Tests.Material.Lists {
    /// <summary>
    /// 选择列表测试
    /// </summary>
    public class SelectListTest {
        /// <summary>
        /// 输出工具
        /// </summary>
        private readonly ITestOutputHelper _output;
        /// <summary>
        /// 选择列表
        /// </summary>
        private readonly SelectList _component;

        /// <summary>
        /// 测试初始化
        /// </summary>
        public SelectListTest( ITestOutputHelper output ) {
            _output = output;
            _component = new SelectList();
            Config.IsValidate = false;
        }

        /// <summary>
        /// 获取结果
        /// </summary>
        private string GetResult( SelectList component ) {
            component.WriteTo( new StringWriter(), HtmlEncoder.Default );
            var result = component.ToString();
            _output.WriteLine( result );
            return result;
        }

        /// <summary>
        /// 测试默认输出
        /// </summary>
        [Fact]
        public void TestDefault() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component ) );
        }

        /// <summary>
        /// 测试添加标识
        /// </summary>
        [Fact]
        public void TestId() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper #a=\"\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.Id( "a" ) ) );
        }

        /// <summary>
        /// 测试设置名称
        /// </summary>
        [Fact]
        public void TestName() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper name=\"a\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.Name( "a" ) ) );
        }

        /// <summary>
        /// 测试禁用
        /// </summary>
        [Fact]
        public void TestDisable() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper [disabled]=\"true\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.Disable() ) );
        }

        /// <summary>
        /// 测试设置Url
        /// </summary>
        [Fact]
        public void TestUrl() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper url=\"a\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.Url( "a" ) ) );
        }

        /// <summary>
        /// 测试设置数据源
        /// </summary>
        [Fact]
        public void TestDataSource() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper [dataSource]=\"a\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.DataSource( "a" ) ) );
        }

        /// <summary>
        /// 测试模型绑定
        /// </summary>
        [Fact]
        public void TestModel() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper [(model)]=\"a\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.Model( "a" ) ) );
        }

        /// <summary>
        /// 测试变更事件
        /// </summary>
        [Fact]
        public void TestOnChange() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper (onChange)=\"a\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.OnChange( "a" ) ) );
        }

        /// <summary>
        /// 测试添加项
        /// </summary>
        [Fact]
        public void TestAdd_1() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper [dataSource]=\"[{" );
            result.Append( "'text':'a','value':'1'" );
            result.Append( "}]\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.Add( "a", "1" ) ) );
        }

        /// <summary>
        /// 测试添加项
        /// </summary>
        [Fact]
        public void TestAdd_2() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper [dataSource]=\"[{" );
            result.Append( "'text':'a','value':'1'" );
            result.Append( "}]\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.Add( new Item( "a", "1" ) ) ) );
        }

        /// <summary>
        /// 测试绑定bool
        /// </summary>
        [Fact]
        public void TestBool() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper [dataSource]=\"[" );
            result.Append( "{'text':'是','value':true}," );
            result.Append( "{'text':'否','value':false}" );
            result.Append( "]\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( _component.Bool() ) );
        }

        /// <summary>
        /// 测试绑定枚举
        /// </summary>
        [Fact]
        public void TestEnum() {
            var result = new String();
            result.Append( "<mat-select-list-wrapper [dataSource]=\"[" );
            result.Append( "{'text':'女','value':1,'sortId':1}," );
            result.Append( "{'text':'男','value':2,'sortId':2}" );
            result.Append( "]\"></mat-select-list-wrapper>" );
            Assert.Equal( result.ToString(), GetResult( (SelectList)_component.Enum<Gender>() ) );
        }
    }
}


text:
var select_periodo_aberto = false;
var btn_invest_visivel = false;
var div_limite_periodo;
var mediaVolumeMoeda;
var mediafechamentoMoeda;
var div_sugestao_aberta = false;
var div_resultado_simulacao_aberta = false;
var listaDadosFechamento = [];
var listaDadosVolume = [];
var idMoeda;
var descricao;
var dataInicial;
var dataFinal;
var quantidade;

$(document).ready(function () {
    $('#lista_menu_superior>li.active').removeClass('active');
    $('#menu_consulta_moeda').addClass('active');
    busca_moedas();
    div_limite_periodo = $('#div_limite_periodo');
    $('#data_inicial').mask('99/99/9999');
    $('#data_final').mask('99/99/9999');
    $('#quantidade').numeric({ altDecimal: ".", decimal : "," });
});

$("#modal_investir").on("hidden.bs.modal", function () {
    if(div_resultado_simulacao_aberta) {
        $('#div_resultado_simulacao').slideToggle();
        div_resultado_simulacao_aberta = false;
    }
    $('#descricao').val('');
    $('#data_inicial').val('');
    $('#data_final').val('');
    $('#quantidade').val('');
});

function busca_moedas(){
    $.ajax({
        url: 'buscar_moedas',
        async: true,
        type: 'POST',
        dataType: 'json',
        data: {'submit': true},
        success: function(data){
            if(data.isValid) {
                var lista = data.listaMoedas;

                var select = $('#select_moeda');
                var select_moeda_investimento = $('#select_moeda_investimento');
                $.each(lista, function(i) {
                    select.append($('<option>', {
                        value: lista[i].idMoeda,
                        text: lista[i].nome + ' (' + lista[i].sigla + ')'
                    }));

                    select_moeda_investimento.append($('<option>', {
                        value: lista[i].idMoeda,
                        text: lista[i].nome + ' (' + lista[i].sigla + ')'
                    }));
                });
                $('#btn_abre_modal_consulta').attr('disabled', false);
            }
            else {
                abreNotificacao('warning',data.msgErro);
            }
        },
        error: function (data) {
            abreNotificacao('danger', 'Houve uma falha para realizar a operação! Contate o administrador do sistema!');
        }
    });
}

$('#select_periodo').change(function(){
    var opcao = $(this).val();
    var txt_limite = '';
    var qtde_limite;
    if(opcao === '0'){
        div_limite_periodo.slideToggle();
        select_periodo_aberto = false;
    } else {
        switch (opcao) {
            case 's':
                txt_limite = 'Semana';
                qtde_limite = 12;
                break;
            case 'm':
                txt_limite = 'Mês';
                qtde_limite = 36;
                break;
            case 'a':
                txt_limite = 'Ano';
                qtde_limite = 3;
                break
        }

        var select_limite_periodo = $('#select_limite_periodo');
        select_limite_periodo.empty();
        select_limite_periodo.append($('<option>', {
            value: 0,
            text: 'Selecione uma opção...'
        }));
        select_limite_periodo.append($('<option>', {
            value: 1,
            text: '1 ' + txt_limite
        }));

        if(opcao === 'm')
            txt_limite = 'Meses';
        else
            txt_limite += 's';

        for (var i = 2; i < qtde_limite+1; i++) {
            select_limite_periodo.append($('<option>', {
                value: i,
                text: i + ' ' + txt_limite
            }));
        }

        if(!select_periodo_aberto) {
            div_limite_periodo.slideToggle();
            select_periodo_aberto = true;
        }

        $('#label_limite_periodo').html('Limite de ' + txt_limite + ' da Pesquisa');
    }
});

$('#btn_buscar').click(function(){
    var select_moeda = $('#select_moeda');
    var select_periodo = $('#select_periodo');
    var select_limite_periodo = $('#select_limite_periodo');

    if(div_sugestao_aberta){
        $('#div_sugestao').slideToggle();
        div_sugestao_aberta = false;
    }

    if(select_moeda.val() === '0'){
        abreNotificacao('warning', 'Informe a moeda!');
    } else if(select_periodo.val() === '0'){
        abreNotificacao('warning', 'Informe o período!');
    } else if(select_limite_periodo.val() === '0'){
        abreNotificacao('warning', 'Informe o limite do período!');
    } else {
        var btn_modal_investimento = $('#btn_abre_modal_investimento');
        $.ajax({
            url: 'historico_moeda',
            async: true,
            type: 'POST',
            dataType: 'json',
            data: {
                'id_moeda': select_moeda.val(),
                'periodo': select_periodo.val(),
                'limite': select_limite_periodo.val()
            },
            success: function (data) {
                if (data.isValid) {
                    idMoeda = select_moeda.val();
                    var lista = data.listaPeriodoHistorico;
                    var nomeMoeda = select_moeda.find(":selected").text();
                    var txtPeriodo = select_periodo.find(":selected").text();
                    $('#sub_titulo_pagina').html(nomeMoeda);
                    $('#moeda_selecionada').val(nomeMoeda);
                    $('#titulo_modal_investimento').html('Investimento - ' + nomeMoeda);
                    var listaLabels = [];
                    listaDadosFechamento = [];
                    listaDadosVolume = [];
                    var somatorioVolume = 0;
                    var somatorioFechamento = 0;

                    $.each(lista, function (i) {
                        somatorioVolume += lista[i].valorVolume;
                        somatorioFechamento += lista[i].valorFechamento;
                        listaLabels.push(lista[i].descricao);
                        listaDadosFechamento.push(lista[i].valorFechamento);
                        listaDadosVolume.push(lista[i].valorVolume);
                    });

                    mediaVolumeMoeda = somatorioVolume / lista.length;
                    mediafechamentoMoeda = somatorioFechamento / lista.length;

                    $('#modal_consulta').modal('hide');

                    if (!btn_invest_visivel) {
                        btn_modal_investimento.slideToggle();
                        btn_invest_visivel = true;
                    }

                    $('#div_grafico_fechamento').html('<canvas id="canvas_grafico_fechamento" ></canvas>');
                    $('#div_grafico_volume').html('<canvas id="canvas_grafico_volume" ></canvas>');
                    preencheGrafico(nomeMoeda, listaLabels, 'Fechamento', listaDadosFechamento, 'canvas_grafico_fechamento', 'rgb(75, 192, 192)', txtPeriodo);
                    preencheGrafico(nomeMoeda, listaLabels, 'Volume', listaDadosVolume, 'canvas_grafico_volume', 'rgb(220, 47, 47)', txtPeriodo);

                    $('#texto_sugestao').html('O melhor momento para investir em ' + nomeMoeda + ' é quando a moeda estiver com fechamento no mínimo de ' + mediafechamentoMoeda + ' para o período.');
                    $('#div_sugestao').slideToggle();
                    div_sugestao_aberta = true;
                }
                else {
                    abreNotificacao('warning', data.msgErro);
                }
            },
            error: function (data) {
                abreNotificacao('danger', 'Houve uma falha para realizar a operação! Contate o administrador do sistema!');
            }
        });
    }
});

function preencheGrafico(nomeMoeda, listaLabels, txtDescricao, listaDados, id_grafico, rgb_cor, txtPeriodo) {
    new Chart(document.getElementById(id_grafico),{
        type:"line",
        data:{
            labels:listaLabels,
            datasets:[
                {
                    label:txtDescricao,
                    data:listaDados,
                    fill:false,
                    borderColor:rgb_cor,
                    lineTension:0.1
                }
            ]
        },
        options:{
            responsive: true,
            title:{
                display:true,
                text:nomeMoeda
            },
            tooltips: {
                mode: 'index',
                intersect: false
            },
            hover: {
                mode: 'nearest',
                intersect: true
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: txtPeriodo
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'Valor'
                    }
                }]
            }
        }
    });
}

$('#btn_salvar_investimento').click(function(){
    pegaDadosInvestimento();
    if(validaData(dataInicial) && validaData(dataFinal) && periodoDataValido(dataInicial, dataFinal)) {
        $.ajax({
            url: 'novo_investimento',
            async: true,
            type: 'POST',
            dataType: 'json',
            data: {
                'id_moeda': idMoeda,
                'descricao': descricao,
                'data_inicial': dataInicial,
                'data_final': dataFinal,
                'quantidade': quantidade
            },
            success: function (data) {
                if (data.isValid) {
                    $('#modal_investir').modal('hide');
                    $('#div_resultado_simulacao').slideToggle();
                    div_resultado_simulacao_aberta = false;
                    $('#descricao').val('');
                    $('#data_inicial').val('');
                    $('#data_final').val('');
                    $('#quantidade').val('');
                    abreNotificacao('success', 'Investimento salvo com sucesso!');
                } else {
                    abreNotificacao('warning', data.msgErro);
                }
            },
            error: function (data) {
                abreNotificacao('danger', 'Houve uma falha para realizar a operação! Contate o administrador do sistema!');
            }
        });
    }
});

$('#btn_simular_investimento').click(function(){
    if(div_resultado_simulacao_aberta){
        $('#div_resultado_simulacao').slideToggle();
        div_resultado_simulacao_aberta = false;
    }
    pegaDadosInvestimento();
    if(validaData(dataInicial) && validaData(dataFinal) && periodoDataValido(dataInicial, dataFinal)) {
        $.ajax({
            url: 'simular_investimento',
            async: true,
            type: 'POST',
            dataType: 'json',
            data: {
                'id_moeda': idMoeda,
                'descricao': descricao,
                'data_inicial': dataInicial,
                'data_final': dataFinal,
                'quantidade': quantidade
            },
            success: function (data) {
                if (data.isValid) {
                    console.log(data);
                    var txt_sugestao = '';
                    if (data.simulacaoinvestimento.aceitavel)
                        txt_sugestao = 'É aconselhado investir o valor no período.';
                    else
                        txt_sugestao = 'É aconselhado NÃO INVESTIR o valor no período.';

                    var div_resultado_simulacao = $('#div_resultado_simulacao');
                    div_resultado_simulacao.html('A moeda teve o valor de fechamento, em média, de ' + data.simulacaoinvestimento.mediaPeriodo + ' entre ' +
                        dataInicial.substring(0, 5) + ' e ' + dataFinal.substring(0, 5) + ' nos últimos três anos. ' + txt_sugestao);
                    div_resultado_simulacao.slideToggle();
                    div_resultado_simulacao_aberta = true;
                } else {
                    abreNotificacao('warning', data.msgErro);
                }
            },
            error: function (data) {
                abreNotificacao('danger', 'Houve uma falha para realizar a operação! Contate o administrador do sistema!');
            }
        });
    }
});

function pegaDadosInvestimento() {
    descricao = $('#descricao').val();
    dataInicial = $('#data_inicial').val();
    dataFinal = $('#data_final').val();
    quantidade = $('#quantidade').val();
}

function validaData(data) {
    var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])      [\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;

    if (!((data.match(RegExPattern)) && (data!=''))) {
        abreNotificacao('warning', 'Informe uma data válida!');
        return false;
    }
    return true;
}

function periodoDataValido(dataInicialStr, dataFinalStr) {
    var partesData;
    partesData = dataInicialStr.split("/");
    var dataInicial = new Date(partesData[2], partesData[1] - 1, partesData[0]);

    partesData = dataFinalStr.split("/");
    var dataFinal = new Date(partesData[2], partesData[1] - 1, partesData[0]);

    if(dataInicial > dataFinal){
        abreNotificacao('warning', 'A data inicial deve ser menor que a final');
        return false;
    }
    return true;
}


text:
<?php

namespace App;

use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
use Windwalker\Edge\Cache\EdgeFileCache;
use Windwalker\Edge\Edge;
use Windwalker\Edge\Loader\EdgeFileLoader;
use Phroute\Phroute\RouteCollector;
use App\Models\Config;

/**
 *
 */
class App
{
    private static $router;
    public static $translations;
    private static $config;

    function __construct()
    {
        require('config.php');
        self::$config = $_CONFIG;
        if (isset($_SESSION['lang'])) {
            self::setLang($_SESSION['lang']);
        }
        $this->bootORM();
    }

    private function bootORM()
    {

        $capsule = new Capsule;

        $capsule->addConnection(self::$config['database']);

        $capsule->setEventDispatcher(new Dispatcher(new Container));
        $capsule->setAsGlobal();
        $capsule->bootEloquent();
    }

    public static function view($template, $data)
    {
        $paths = array(__DIR__ . '/Views');

        $edge = new Edge(new EdgeFileLoader($paths), null);
        $config = array();

        foreach (Config::get() as $key => $value) {
            $config[$value->name] = $value->value;
        }

        $data = array_merge($data, $config);
        echo $edge->render($template, $data);
    }

    public static function route($url)
    {
        self::$router = new RouteCollector();
        $router = self::$router;
        require('routes.php');
        $fixedURL = str_replace(self::$config['base_url'], "", $url);
        //$fixedURL = $url;
        $currentRoute = explode('/', $fixedURL);
        array_shift($currentRoute);
        $GLOBALS['route'] = implode("/", $currentRoute);

        $assetTypes = array("css","js");
        $parts = explode(".", end($currentRoute));

        $dispatcher = new \Phroute\Phroute\Dispatcher(self::$router->getData());

        $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], $fixedURL);
    }

    public function encrypt($value)
    {
        $strength = 10;
        $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
        $salt = sprintf("$2a$%02d$", $strength) . $salt;
        return crypt($value, $salt);
    }

    public static function setLang($locale)
    {
        require('Translations/' . $locale . '.php');
        self::$translations = $translation;
    }

    public static function trans($key)
    {
        if (isset(self::$translations[$key])) {
            return self::$translations[$key];
        } else {
            return 'missing translation for "' . $key . '"';
        }
    }

    public static function config($item)
    {
        return self::$config[$item];
    }

    public static function routeName($name)
    {
        return "/" . self::$config["base_url"] . self::$router->route($name);
    }

    public static function routeIs($name)
    {
        if ($GLOBALS['route'] == self::$router->route($name)) {
            return true;
        } else {
            return false;
        }
    }
}


text:
<?php

namespace Dflydev\EncryptedFigCookies\Validation;

class Message
{
    private $nonce;
    private $hmac;
    private $value;

    private function __construct($nonce, $hmac, $value)
    {
        $this->nonce = $nonce;
        $this->hmac = $hmac;
        $this->value = $value;
    }

    public function getNonce()
    {
        return $this->nonce;
    }

    public function getHmac()
    {
        return $this->hmac;
    }

    public function getValue()
    {
        return $this->value;
    }

    public static function fromString($value)
    {
        $nonce = substr($value, 0, 32);
        $hmac = substr($value, strrpos($value, '.') + 1);
        $value = substr($value, 32, strlen($value) - strlen($hmac) - 33);

        return new self($nonce, $hmac, $value);
    }
}


text:
#define SHOW_FPS 1
#include <pcl/apps/timer.h>
#include <pcl/common/common.h>
#include <pcl/common/angles.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <pcl/keypoints/susan.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/image_viewer.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>

using namespace pcl;
using namespace std;

typedef PointXYZRGBA PointT;
typedef PointXYZRGBL KeyPointT;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class SUSANDemo
{
  public:
    typedef PointCloud<PointT> Cloud;
    typedef Cloud::Ptr CloudPtr;
    typedef Cloud::ConstPtr CloudConstPtr;

    SUSANDemo (Grabber& grabber)
      : cloud_viewer_ ("SUSAN 2D Keypoints -- PointCloud")
      , grabber_ (grabber)
      , image_viewer_ ("SUSAN 2D Keypoints -- Image")
    {
    }

    /////////////////////////////////////////////////////////////////////////
    void
    cloud_callback (const CloudConstPtr& cloud)
    {
      FPS_CALC ("cloud callback");
      boost::mutex::scoped_lock lock (cloud_mutex_);
      cloud_ = cloud;

      // Compute SUSAN keypoints
      SUSAN<PointT, KeyPointT> susan;
      susan.setInputCloud (cloud);
      susan.setNumberOfThreads (6);
      susan.setNonMaxSupression (true);
      keypoints_.reset (new PointCloud<KeyPointT>);
      susan.compute (*keypoints_);
    }

    /////////////////////////////////////////////////////////////////////////
    void
    init ()
    {
      boost::function<void (const CloudConstPtr&) > cloud_cb = boost::bind (&SUSANDemo::cloud_callback, this, _1);
      cloud_connection = grabber_.registerCallback (cloud_cb);
    }

    /////////////////////////////////////////////////////////////////////////
    string
    getStrBool (bool state)
    {
      stringstream ss;
      ss << state;
      return (ss.str ());
    }

    /////////////////////////////////////////////////////////////////////////
    void
    run ()
    {
      grabber_.start ();

      bool image_init = false, cloud_init = false;
      bool keypts = true;

      while (!cloud_viewer_.wasStopped () && !image_viewer_.wasStopped ())
      {
        PointCloud<KeyPointT>::Ptr keypoints;
        CloudConstPtr cloud;

        if (cloud_mutex_.try_lock ())
        {
          cloud_.swap (cloud);
          keypoints_.swap (keypoints);

          cloud_mutex_.unlock ();
        }

        if (cloud)
        {
          if (!cloud_init)
          {
            cloud_viewer_.setPosition (0, 0);
            cloud_viewer_.setSize (cloud->width, cloud->height);
            cloud_init = !cloud_init;
          }

          if (!cloud_viewer_.updatePointCloud (cloud, "OpenNICloud"))
          {
            cloud_viewer_.addPointCloud (cloud, "OpenNICloud");
            cloud_viewer_.resetCameraViewpoint ("OpenNICloud");
          }

          if (!image_init)
          {
            image_viewer_.setPosition (cloud->width, 0);
            image_viewer_.setSize (cloud->width, cloud->height);
            image_init = !image_init;
          }

          image_viewer_.addRGBImage<PointT> (cloud);

          if (keypoints && !keypoints->empty ())
          {
            image_viewer_.removeLayer (getStrBool (keypts));
            for (size_t i = 0; i < keypoints->size (); ++i)
            {
              int u = int (keypoints->points[i].label % cloud->width);
              int v = cloud->height - int (keypoints->points[i].label / cloud->width);
              image_viewer_.markPoint (u, v, visualization::red_color, visualization::blue_color, 10, getStrBool (!keypts));
            }
            keypts = !keypts;

            visualization::PointCloudColorHandlerCustom<KeyPointT> blue (keypoints, 0, 0, 255);
            if (!cloud_viewer_.updatePointCloud (keypoints, blue, "keypoints"))
              cloud_viewer_.addPointCloud (keypoints, blue, "keypoints");
            cloud_viewer_.setPointCloudRenderingProperties (visualization::PCL_VISUALIZER_POINT_SIZE, 20, "keypoints");
            cloud_viewer_.setPointCloudRenderingProperties (visualization::PCL_VISUALIZER_OPACITY, 0.5, "keypoints");
          }
        }

        cloud_viewer_.spinOnce ();
        image_viewer_.spinOnce ();
        boost::this_thread::sleep (boost::posix_time::microseconds (100));
      }

      grabber_.stop ();
      cloud_connection.disconnect ();
    }

    visualization::PCLVisualizer cloud_viewer_;
    Grabber& grabber_;
    boost::mutex cloud_mutex_;
    CloudConstPtr cloud_;

    visualization::ImageViewer image_viewer_;

    PointCloud<KeyPointT>::Ptr keypoints_;

  private:
    boost::signals2::connection cloud_connection;
};

/* ---[ */
int
main (int, char**)
{
  string device_id ("#1");
  OpenNIGrabber grabber (device_id);
  SUSANDemo openni_viewer (grabber);

  openni_viewer.init ();
  openni_viewer.run ();

  return (0);
}
/* ]--- */


text:
package CIAPI.Java.core.dto;

/**
 * !This is an auto generated model object!
 *
 * request to create a session (log on).
 */
public class ApiLogOnRequestDTO {

	/**
	 * No argument constructor
	 */
	public ApiLogOnRequestDTO() {
	}

	private String UserName;

	/**
	 * Username is case sensitive
	 */
	public String getUserName() {
		return UserName;
	}

	public void setUserName(String UserName) {
		this.UserName = UserName;
	}
	private String Password;

	/**
	 * Password is case sensitive
	 */
	public String getPassword() {
		return Password;
	}

	public void setPassword(String Password) {
		this.Password = Password;
	}
}


text:
. ../../test_common.sh

function test_probes_textfilecontent54 {

    probecheck "textfilecontent54" || return 255

    local ret_val=0;
    local DF="${srcdir}/test_probes_textfilecontent54.xml"
    local RF="results.xml"

    [ -f $RF ] && rm -f $RF

    local FILE_A="/tmp/test_probes_textfilecontent54.tmp_file"
    local FILE_B="/tmp/test_probes_textfilecontent54.tmp_file_empty"
    local FILE_C="/tmp/test_probes_textfilecontent54.tmp_file_non_existing"

    touch "$FILE_A"
    touch "$FILE_B"

    echo "valid_key = valid_value" > "$FILE_A"
    echo "valid_key = valid_value" >> "$FILE_A"

    $OSCAP oval eval --results $RF $DF

    if [ -f $RF ]; then
	verify_results "def" $DF $RF 13 && verify_results "tst" $DF $RF 16
	ret_val=$?
    else
	ret_val=1
    fi

    rm -f $FILE_A $FILE_B $FILE_C

    return $ret_val
}

test_probes_textfilecontent54