text:
package org.yoon_technology.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Comparator;

import javax.swing.JPanel;
import javax.swing.SwingConstants;

import org.yoon_technology.engine.Engine;
import org.yoon_technology.engine.objects.World;
import org.yoon_technology.engine.objects.WorldObject;
import org.yoon_technology.engine.objects.WorldObjectProperty;
import org.yoon_technology.engine.objects.WorldText;
import org.yoon_technology.math.Function;
import org.yoon_technology.math.Vector3d;

/**
 * Refer to LICENSE
 *
 * @author Jaewan Yun (jay50@pitt.edu)
 */

public class Display extends JPanel implements ComponentListener {

	private static final long serialVersionUID = 3L;
	private Engine engine;
	private World world;
	private String displayInformation;
	private double scale;
	private volatile boolean beautify = true;

	public Display(int width, int height, Engine engine) {
		super(new FlowLayout(SwingConstants.CENTER));
		this.engine = engine;
		engine.addDisplay(this);
		setFocusable(true);
		setPreferredSize(new Dimension(width, height));

		addComponentListener(this);

		addMouseListener(new MouseListener() {
			@Override
			public void mouseEntered(MouseEvent e) {
				requestFocus();
			}
			@Override
			public void mousePressed(MouseEvent e) {
				requestFocus();
			}
			@Override
			public void mouseExited(MouseEvent e) {}
			@Override
			public void mouseReleased(MouseEvent e) {}
			@Override
			public void mouseClicked(MouseEvent e) {}
		});
	}

	public synchronized void setBeautify(boolean beautify) {
		this.beautify = beautify;
	}

	public synchronized void setWorld(World world) {
		this.world = world;
	}

	public synchronized void setDisplayInformation(String displayInformation) {
		this.displayInformation = displayInformation;
	}

	public synchronized void setScale(double scale) {
		this.scale = scale;
	}

	public synchronized double getScale() {
		return scale;
	}

	public synchronized void render() {
		revalidate();
		repaint();
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);

		// Antialiasing
		Graphics2D g2 = (Graphics2D)g;
		RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		rh.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
		g2.setRenderingHints(rh);

		double maxZ = 0.0000001;
		double minZ = -0.0000001;
		synchronized(world) {
			if(beautify) {
				// Depth buffer equivalent
				try {
					world.getPoints().sort(new Comparator<WorldObject>() {
						@Override
						public int compare(WorldObject o1, WorldObject o2) {
							Vector3d o1_ = engine.getCamera().project(o1.getPosition(), 1.0, 1.0);
							Vector3d o2_ = engine.getCamera().project(o2.getPosition(), 1.0, 1.0);
							return (int)(o1_.getZ() - o2_.getZ());
						}
					});
				} catch (IllegalArgumentException iae) {} // Non transient?

				// "Fog" scale
				if(world.getPoints().size() != 0) {
					Vector3d maxZPos;
					maxZPos = world.getPoints().get(world.getPoints().size()-1).getPosition();
					maxZ = engine.getCamera().project(
							maxZPos,
							(int)((double)getWidth()),
							(int)((double)getHeight())).getZ();

					Vector3d minZPos;
					minZPos = world.getPoints().get(0).getPosition();
					minZ = engine.getCamera().project(
							minZPos,
							(int)((double)getWidth()),
							(int)((double)getHeight())).getZ();
				}
			}

			// Particles
			for(WorldObject object : world.getPoints()) {
				// Get projection vector
				Vector3d projectionVector = engine.getCamera().project(
						object.getPosition().mul(scale),
						(int)((double)getWidth()),			// offset x
						(int)((double)getHeight()));		// offset y

				// "Fog"
				if(beautify) {
					Color objectColor = object.getColor();
					double factor = Function.clamp((projectionVector.getZ()+maxZ)/(maxZ-minZ), 0.15, 1.0);
					int red = (int) Function.clamp(factor * objectColor.getRed()*1.7, 30.0, 255.0);
					int green = (int) Function.clamp(factor * objectColor.getGreen()*1.7, 30.0, 255.0);
					int blue = (int) Function.clamp(factor * objectColor.getBlue()*1.7, 30.0, 255.0);
					g.setColor(new Color(red, green, blue));
				} else {
					g.setColor(object.getColor());
				}

				double radius = object.getRadius() * scale;
				if(radius < 1)
					radius = 1.0;

				g.fillOval((int)(projectionVector.getX() - radius),
						(int)(projectionVector.getY() - radius),
						(int)(radius*2.0),
						(int)(radius*2.0));
			}

			// Draw lines
			WorldObject lastObject = null; // For lines
			for(WorldObject line : world.getLines()) {
				// Get projection vector
				Vector3d projectionVector = engine.getCamera().project(
						line.getPosition().mul(scale),
						(int)((double)getWidth()),			// offset x
						(int)((double)getHeight()));		// offset y
				g.setColor(line.getColor());

				if(line.getProperties().getDrawMode() == WorldObjectProperty.LINES) {
					if(lastObject != null) {
						Vector3d projectionVector2 = engine.getCamera().project(
								lastObject.getPosition().mul(scale),
								(double)getWidth(),			// offset x to center at 0, 0
								(double)getHeight());		// offset y

						g.drawLine((int) projectionVector.getX(),
								(int) projectionVector.getY(),
								(int) projectionVector2.getX(),
								(int) projectionVector2.getY());
					}
					lastObject = line;

				} else if(line.getProperties().getDrawMode() == WorldObjectProperty.END_LINES) {
					if(lastObject == null) {
						g.drawOval((int)(projectionVector.getX() - 10),
								(int)(projectionVector.getY() - 10),
								(int)(20),
								(int)(20));
					} else {
						Vector3d projectionVector2 = engine.getCamera().project(
								lastObject.getPosition().mul(scale),
								(double)getWidth(),			// offset x to center at 0, 0
								(double)getHeight());		// offset y

						g.drawLine((int) projectionVector.getX(),
								(int) projectionVector.getY(),
								(int) projectionVector2.getX(),
								(int) projectionVector2.getY());
					}
					lastObject = null;
				}
			}

			// Draw rectangle
			int index = 0;
			int[] xPoints = new int[4];
			int[] yPoints = new int[4];
			for(WorldObject rectangle : world.getRectangles()) {
				Vector3d projectionVector = engine.getCamera().project(
						rectangle.getPosition().mul(scale),
						(double)getWidth(),			// offset x to center at 0, 0
						(double)getHeight());		// offset y;
				xPoints[index] = (int) projectionVector.getX();
				yPoints[index] = (int) projectionVector.getY();

				index++;
				if(index == 4) {
					g.setColor(rectangle.getColor());
					g.drawPolygon(xPoints, yPoints, 4);
					index = 0;
				}
			}

			// Draw text
			for(WorldText text : world.getTexts()) {
				Vector3d projectionVector = engine.getCamera().project(
						text.getPosition().mul(scale),
						(double)getWidth(),
						(double)getHeight());
				g.setColor(text.getColor());
				g.setFont(text.getFont());
				g.drawString(text.getText(), (int) projectionVector.getX(), (int) projectionVector.getY());
			}
		}

		if(displayInformation != null) {
			g.setColor(Color.WHITE);
			g.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 10));
			g.drawString(displayInformation, 10, 15);
		}
	}

	@Override
	public synchronized void componentResized(ComponentEvent e) {
		for(World world : engine.getWorld()) {
			this.scale = world.resized(getWidth(), getHeight());
		}
		render();
	}
	@Override
	public void componentShown(ComponentEvent e) {}
	@Override
	public void componentMoved(ComponentEvent e) {}
	@Override
	public void componentHidden(ComponentEvent e) {}
}


text:
/***********************************************************************
	created:	13/4/2004
	author:		Paul D Turner

	purpose:	Interface to base class for Combobox widget
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifndef _CEGUICombobox_h_
#define _CEGUICombobox_h_

#include "CEGUI/Base.h"
#include "CEGUI/Window.h"
#include "CEGUI/RegexMatcher.h"
#include "CEGUI/views/ItemView.h"
#include "CEGUI/views/StandardItemModel.h"

#if defined(_MSC_VER)
#	pragma warning(push)
#	pragma warning(disable : 4251)
#endif

// Start of CEGUI namespace section
namespace CEGUI
{

/*!
\brief
	Base class for the Combobox widget
*/
class CEGUIEXPORT Combobox : public Window
{
public:
    typedef RegexMatcher::MatchState MatchState;

	static const String EventNamespace;				//!< Namespace for global events
    static const String WidgetTypeName;             //!< Window factory name

	/*************************************************************************
		Constants
	*************************************************************************/
	// event names from edit box
    /** Event fired when the read-only mode for the edit box is changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose read only mode
     * has been changed.
     */
	static const String EventReadOnlyModeChanged;
    /** Event fired when the edix box validation string is changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose validation
     * string was changed.
     */
	static const String EventValidationStringChanged;
    /** Event fired when the maximum string length is changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose maximum edit box
     * string length has been changed.
     */
	static const String EventMaximumTextLengthChanged;
    /** Event fired when the validity of the Combobox text (as determined by a
     * RegexMatcher object) has changed.
     * Handlers are passed a const RegexMatchStateEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose text validity has
     * changed and RegexMatchStateEventArgs::matchState set to the new match
     * validity. Handler return is significant, as follows:
     * - true indicates the new state - and therfore text - is to be accepted.
     * - false indicates the new state is not acceptable, and the previous text
     *   should remain in place. NB: This is only possible when the validity
     *   change is due to a change in the text, if the validity change is due to
     *   a change in the validation regular expression string, then returning
     *   false will have no effect.
     */
    static const String EventTextValidityChanged;
    /** Event fired when the edit box text insertion position is changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose caret position has
     * been changed.
     */
	static const String EventCaretMoved;
    /** Event fired when the current edit box text selection is changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose edit box text selection
     * has been changed.
     */
	static const String EventTextSelectionChanged;
    /** Event fired when the number of characters in the edit box has reached
     * the currently set maximum.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose edit box has become
     * full.
     */
	static const String EventEditboxFull;
    /** Event fired when the user accepts the current edit box text by pressing
     * Return, Enter, or Tab.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose edit box text has been
     * accepted / confirmed by the user.
     */
	static const String EventTextAccepted;

    // event names from list widget
    /** Event fired when the contents of the list is changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose list content has
     * changed.
     */
	static const String EventListContentsChanged;
    /** Event fired when there is a change to the currently selected item in the
     * list.
     * @note This change in selection may be temporary (for example, when
     * hovering over an item in the combobox). See also the event
     * CEGUI::Combobox::EventListSelectionAccepted that is fired for a selection
     * that the user has 'confirmed' in some way.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose currently selected list
     * item has changed.
     */
	static const String EventListSelectionChanged;
    /** Event fired when the sort mode setting of the list is changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose list sorting mode has
     * been changed.
     */
	static const String EventSortModeChanged;
    /** Event fired when the vertical scroll bar 'force' setting for the list is
     * changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose vertical scroll bar
     * setting is changed.
     */
	static const String EventVertScrollbarModeChanged;
    /** Event fired when the horizontal scroll bar 'force' setting for the list
     * is changed.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose horizontal scroll bar
     * setting has been changed.
     */
	static const String EventHorzScrollbarModeChanged;

	// events we produce / generate ourselves
    /** Event fired when the drop-down list is displayed
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose drop down list has
     * been displayed.
     */
	static const String EventDropListDisplayed;
    /** Event fired when the drop-down list is removed / hidden.
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox whose drop down list has
     * been hidden.
     */
	static const String EventDropListRemoved;
    /** Event fired when the user accepts a selection from the drop-down list
     * Handlers are passed a const WindowEventArgs reference with
     * WindowEventArgs::window set to the Combobox in which the user has
     * confirmed a selection from the drop down list.
     */
	static const String EventListSelectionAccepted;

    /*************************************************************************
        Child Widget name constants
    *************************************************************************/
    static const String EditboxName;    //!< Widget name for the editbox component.
    static const String DropListName;   //!< Widget name for the drop list component.
    static const String ButtonName;     //!< Widget suffix for the button component.

    // override from Window class
    bool isHit(const glm::vec2& position,
               const bool allow_disabled = false) const;

	/*!
	\brief
		returns the mode of operation for the combo box.

	\return
        - true if the user can show the list and select an item with a single
        cursor activation.
        - false if the user must activate the cursor to show the list and then
        activate the cursor again to select an item.
	*/
	bool	getSingleCursorActivationEnabled(void) const;

	/*!
	\brief
		returns true if the drop down list is visible.

	\return
		true if the drop down list is visible, false otherwise.
	*/
	bool	isDropDownListVisible(void) const;

    /*!
    \brief
        Return a pointer to the Editbox component widget for this Combobox.

    \return
        Pointer to an Editbox object.

    \exception UnknownObjectException
        Thrown if the Editbox component does not exist.
    */
    Editbox* getEditbox() const;

    /*!
    \brief
        Return a pointer to the PushButton component widget for this Combobox.

    \return
        Pointer to a PushButton object.

    \exception UnknownObjectException
        Thrown if the PushButton component does not exist.
    */
    PushButton* getPushButton() const;

    /*!
    \brief
        Return a pointer to the ComboDropList component widget for this
        Combobox.

    \return
        Pointer to an ComboDropList object.

    \exception UnknownObjectException
        Thrown if the ComboDropList component does not exist.
    */
    ComboDropList* getDropList() const;

    //! return whether the drop-list will vertically auto size to content.
    bool getAutoSizeListHeightToContent() const;

    //! return whether the drop-list will horizontally auto size to content.
    bool getAutoSizeListWidthToContent() const;

	/*************************************************************************
		Editbox Accessors
	*************************************************************************/
	/*!
	\brief
		return true if the Editbox has input focus.

	\return
		true if the Editbox has input focus, false if the Editbox does not have input focus.
	*/
	bool	hasInputFocus(void) const;

	/*!
	\brief
		return true if the Editbox is read-only.

	\return
		true if the Editbox is read only and can't be edited by the user, false if the Editbox is not
		read only and may be edited by the user.
	*/
	bool	isReadOnly(void) const;

    /*!
    \brief
        return the validation MatchState for the current Combobox text, given
        the currently set validation string.

    \note
        Validation is performed by means of a regular expression.  If the text
        matches the regex, the text is said to have passed validation.  If the
        text does not match with the regex then the text fails validation.

    \return
        One of the MatchState enumerated values indicating the current match
        state.
    */
    MatchState getTextMatchState() const;

	/*!
	\brief
		return the currently set validation string

	\note
		Validation is performed by means of a regular expression.  If the text matches the regex, the text is said to have passed
		validation.  If the text does not match with the regex then the text fails validation.

	\return
		String object containing the current validation regex data
	*/
	const String&	getValidationString(void) const;

	/*!
	\brief
		return the current position of the caret.

	\return
		Index of the insert caret relative to the start of the text.
	*/
	size_t	getCaretIndex(void) const;

	/*!
	\brief
		return the current selection start point.

	\return
		Index of the selection start point relative to the start of the text.  If no selection is defined this function returns
		the position of the caret.
	*/
	size_t	getSelectionStartIndex(void) const;

	/*!
	\brief
		return the current selection end point.

	\return
		Index of the selection end point relative to the start of the text.  If no selection is defined this function returns
		the position of the caret.
	*/
	size_t	getSelectionEndIndex(void) const;

	/*!
	\brief
		return the length of the current selection (in code points / characters).

	\return
		Number of code points (or characters) contained within the currently defined selection.
	*/
	size_t	getSelectionLength(void) const;

	/*!
	\brief
		return the maximum text length set for this Editbox.

	\return
		The maximum number of code points (characters) that can be entered into this Editbox.

	\note
		Depending on the validation string set, the actual length of text that can be entered may be less than the value
		returned here (it will never be more).
	*/
	size_t	getMaxTextLength(void) const;

	/*************************************************************************
		List Accessors
	*************************************************************************/
	/*!
	\brief
        Return number of items attached to the list widget.

	\return
        the number of items currently attached to this list widget.
	*/
	size_t	getItemCount(void) const;

	/*!
	\brief
		Return a pointer to the currently selected item.

	\return
        Pointer to a StandardItem based object that is the selected item in the list.
        Will return NULL if no item is selected.
	*/
    StandardItem*   getSelectedItem(void) const;

	/*!
	\brief
		Return the item at index position \a index.

	\param index
		Zero based index of the item to be returned.

	\return
        Pointer to the StandardItem at index position \a index in the list widget.

	\exception	InvalidRequestException	thrown if \a index is out of range.
	*/
    StandardItem*   getItemFromIndex(size_t index) const;

	/*!
	\brief
        Return the index of StandardItem \a item

	\param item
        Pointer to a StandardItem who's zero based index is to be returned.

	\return
        Zero based index indicating the position of StandardItem \a item in the list widget.
	*/
    size_t  getItemIndex(const StandardItem* item) const;

	/*!
	\brief
		return whether list sorting is enabled

	\return
		true if the list is sorted, false if the list is not sorted
	*/
	bool	isSortEnabled(void) const;

	/*!
	\brief
		return whether the string at index position \a index is selected

	\param index
		Zero based index of the item to be examined.

	\return
		true if the item at \a index is selected, false if the item at \a index is not selected.

	\exception	InvalidRequestException	thrown if \a index is out of range.
	*/
	bool	isItemSelected(size_t index) const;

	/*!
	\brief
		Search the list for an item with the specified text

	\param text
		String object containing the text to be searched for.

	\param start_item
        StandardItem where the search is to begin, the search will not
        include \a item.  If \a item is NULL, the search will begin from the
        first item in the list.

	\return
        Pointer to the first StandardItem in the list after \a item that has
        text matching \a text. If no item matches the criteria NULL is returned.
	*/
    StandardItem*   findItemWithText(const String& text, const StandardItem* start_item);

	/*!
	\brief
        Return whether the specified StandardItem is in the List

	\return
       true if StandardItem \a item is in the list, false ifStandardItem
       \a item is not in the list.
	*/
    bool    isItemInList(const StandardItem* item) const;

	/*!
	\brief
		Return whether the vertical scroll bar is always shown.

	\return
		- true if the scroll bar will always be shown even if it is not required.
		- false if the scroll bar will only be shown when it is required.
	*/
	bool	isVertScrollbarAlwaysShown(void) const;

	/*!
	\brief
		Return whether the horizontal scroll bar is always shown.

	\return
		- true if the scroll bar will always be shown even if it is not required.
		- false if the scroll bar will only be shown when it is required.
	*/
	bool	isHorzScrollbarAlwaysShown(void) const;

	/*************************************************************************
		Combobox Manipulators
	*************************************************************************/
	/*!
	\brief
		Initialise the Window based object ready for use.

	\note
		This must be called for every window created.  Normally this is handled automatically by the WindowFactory for each Window type.

	\return
		Nothing
	*/
	virtual void	initialiseComponents(void);

	/*!
	\brief
		Show the drop-down list

	\return
		Nothing
	*/
	void	showDropList(void);

	/*!
	\brief
		Hide the drop-down list

	\return
		Nothing.
	*/
	void	hideDropList(void);

	/*!
	\brief
		Set the mode of operation for the combo box.

	\param setting
        - true if the user should be able to show the list and select an item
        with a single cursor activation.
        - false if the user must activate the cursor to show the list and then
        activate the cursor again to select an item.

	\return
		Nothing.
	*/
    void    setSingleCursorActivationEnabled(bool setting);

    //! Select item in list matching editbox text, clear selection if none match
    void selectListItemWithEditboxText();

    /*!
    \brief
        Sets whether the Combobox drop-down list will automatically resize
        it's height according to the total height of items added to the list.
    */
    void setAutoSizeListHeightToContent(bool auto_size);

    /*!
    \brief
        Sets whether the Combobox drop-down list will automatically resize
        it's width according to the width of the items added to the list.
    */
    void setAutoSizeListWidthToContent(bool auto_size);

    //! update drop list size according to auto-size options.
    void updateAutoSizedDropList();

	/*************************************************************************
		Editbox Manipulators
	*************************************************************************/
	/*!
	\brief
		Specify whether the Editbox is read-only.

	\param setting
		true if the Editbox is read only and can't be edited by the user, false if the Editbox is not
		read only and may be edited by the user.

	\return
		Nothing.
	*/
	void	setReadOnly(bool setting);

	/*!
	\brief
		Set the text validation string.

	\note
		Validation is performed by means of a regular expression.  If the text matches the regex, the text is said to have passed
		validation.  If the text does not match with the regex then the text fails validation.

	\param validation_string
		String object containing the validation regex data to be used.

	\return
		Nothing.
	*/
	void	setValidationString(const String& validation_string);

	/*!
	\brief
		Set the current position of the caret.

	\param caret_pos
		New index for the insert caret relative to the start of the text.  If the value specified is greater than the
		number of characters in the Editbox, the caret is positioned at the end of the text.

	\return
		Nothing.
	*/
	void	setCaretIndex(size_t caret_pos);

	/*!
	\brief
		Define the current selection for the Editbox

	\param start_pos
		Index of the starting point for the selection.  If this value is greater than the number of characters in the Editbox, the
		selection start will be set to the end of the text.

	\param end_pos
		Index of the ending point for the selection.  If this value is greater than the number of characters in the Editbox, the
		selection start will be set to the end of the text.

	\return
		Nothing.
	*/
	void	setSelection(size_t start_pos, size_t end_pos);
	/*!
	\brief
		Define the current selection start for the Editbox

	\param start_pos
		Index of the starting point for the selection.  If this value is greater than the number of characters in the Editbox, the
		selection start will be set to the end of the text.

	\return
		Nothing.
	*/
	void	setSelectionStart(size_t start_pos);

	/*!
	\brief
		Define the current selection for the Editbox

	\param start_pos
		Length of the selection.

	\return
		Nothing.
	*/
	void	setSelectionLength(size_t length);

	/*!
	\brief
		set the maximum text length for this Editbox.

	\param max_len
		The maximum number of code points (characters) that can be entered into this Editbox.

	\note
		Depending on the validation string set, the actual length of text that can be entered may be less than the value
		set here (it will never be more).

	\return
		Nothing.
	*/
	void	setMaxTextLength(size_t max_len);

	/*!
	\brief
		Activate the edit box component of the Combobox.

	\return
		Nothing.
	*/
	void	activateEditbox(void);

	/*************************************************************************
		List Manipulators
	*************************************************************************/
	/*!
	\brief
		Remove all items from the list.

		Note that this will cause 'AutoDelete' items to be deleted.
	*/
	void	resetList(void);

	/*!
	\brief
        Add the given StandardItem to the list.

	\param item
        Pointer to the StandardItem to be added to the list. Note that it is
        the passed object that is added to the list, a copy is not made.
        If this parameter is NULL, nothing happens.
	*/
    void    addItem(StandardItem* item);

	/*!
	\brief
        Insert an item into the list after a specified item already in the list.

		Note that if the list is sorted, the item may not end up in the requested position.

	\param item
        Pointer to the StandardItem to be inserted. Note that it is the passed
        object that is added to the list, a copy is not made.
        If this parameter is NULL, nothing happens.

	\param position
        Pointer to a StandardItem that \a item is to be inserted after. If this
        parameter is NULL, the item is inserted at the start of the list.
	*/
   void    insertItem(StandardItem* item, const StandardItem* position);

	/*!
	\brief
		Removes the given item from the list widget.

	\param item
        Pointer to the StandardItem that is to be removed.
        If \a item is not attached to this list widget then nothing will happen.
	*/
    void    removeItem(const StandardItem* item);

	/*!
	\brief
		Clear the selected state for all items.

	\return
		Nothing.
	*/
	void	clearAllSelections(void);

	/*!
	\brief
		Set whether the list should be sorted.

	\param setting
		true if the list should be sorted, false if the list should not be sorted.

	\return
		Nothing.
	*/
	void	setSortingEnabled(bool setting);

	/*!
	\brief
		Set whether the vertical scroll bar should always be shown.

	\param setting
		true if the vertical scroll bar should be shown even when it is not required.  false if the vertical
		scroll bar should only be shown when it is required.

	\return
		Nothing.
	*/
	void	setShowVertScrollbar(bool setting);

	/*!
	\brief
		Set whether the horizontal scroll bar should always be shown.

	\param setting
		true if the horizontal scroll bar should be shown even when it is not required.  false if the horizontal
		scroll bar should only be shown when it is required.

	\return
		Nothing.
	*/
	void	setShowHorzScrollbar(bool setting);

    /*!
    \brief
        Set the select state of an attached StandardItem.

    \param item
        The StandardItem to be affected.

    \param state
        true to select the item, false to de-select the item.
    */
    void    setItemSelectState(StandardItem* item, bool state);

	/*!
	\brief
        Set the select state of an attached StandardItem.

	\param item_index
        The zero based index of the StandardItem to be affected.
        This must be a valid index (0 <= index < getItemCount())

	\param state
		true to select the item, false to de-select the item.

    \exception  InvalidRequestException thrown if \a item_index is out of range for the list widget
	*/
	void	setItemSelectState(size_t item_index, bool state);

	/*!
	\brief
        Causes the list widget to update it's internal state after changes have
        been made to one or more attached StandardItem objects.

        Client code must call this whenever it has made any changes to
        StandardItem objects already attached to the list widget. If you are
        just adding items, or removed items to update them prior to re-adding
        them, there is no need to call this method.
	*/
	void	handleUpdatedListItemData(void);

	/*************************************************************************
		Construction and Destruction
	*************************************************************************/
	/*!
	\brief
		Constructor for Combobox base class
	*/
	Combobox(const String& type, const String& name);

	/*!
	\brief
		Destructor for Combobox base class
	*/
	virtual ~Combobox(void);

protected:
	/*************************************************************************
		Implementation Methods
	*************************************************************************/
	/*!
	\brief
		Handler function for button clicks.
	*/
	bool	button_PressHandler(const EventArgs& e);

	/*!
	\brief
		Handler for selections made in the drop-list
	*/
	bool	droplist_SelectionAcceptedHandler(const EventArgs& e);

	/*!
	\brief
		Handler for when drop-list hides itself
	*/
	bool	droplist_HiddenHandler(const EventArgs& e);

    /*!
    \brief
        Pointer press & hold handler attached to edit box
    */
    bool    editbox_PointerPressHoldHandler(const EventArgs& e);

    /*!
    \brief
        Update the Combobox text to reflect programmatically made changes to
        selected list item.
    */
    void itemSelectChangeTextUpdate(const StandardItem* const item,
                                    bool new_state, bool old_state);

	/*************************************************************************
		Handlers to relay child widget events so they appear to come from us
	*************************************************************************/
	bool editbox_ReadOnlyChangedHandler(const EventArgs& e);
	bool editbox_ValidationStringChangedHandler(const EventArgs& e);
	bool editbox_MaximumTextLengthChangedHandler(const EventArgs& e);
	bool editbox_TextValidityChangedHandler(const EventArgs& e);
	bool editbox_CaretMovedHandler(const EventArgs& e);
	bool editbox_TextSelectionChangedHandler(const EventArgs& e);
	bool editbox_EditboxFullEventHandler(const EventArgs& e);
	bool editbox_TextAcceptedEventHandler(const EventArgs& e);
	bool editbox_TextChangedEventHandler(const EventArgs& e);
    bool listwidget_ListContentsChangedHandler(const EventArgs& e);
    bool listwidget_ListSelectionChangedHandler(const EventArgs& e);
    bool listwidget_SortModeChangedHandler(const EventArgs& e);
    bool listwidget_VertScrollModeChangedHandler(const EventArgs& e);
    bool listwidget_HorzScrollModeChangedHandler(const EventArgs& e);

	/*************************************************************************
		New Events for Combobox
	*************************************************************************/
	/*!
	\brief
		Handler called internally when the read only state of the Combobox's Editbox has been changed.
	*/
	virtual	void	onReadOnlyChanged(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the Combobox's Editbox validation string has been changed.
	*/
	virtual	void	onValidationStringChanged(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the Combobox's Editbox maximum text length is changed.
	*/
	virtual	void	onMaximumTextLengthChanged(WindowEventArgs& e);

    /*!
    \brief
        Handler called when something has caused the validity state of the
        current text to change.
    */
    virtual void onTextValidityChanged(RegexMatchStateEventArgs& e);

	/*!
	\brief
		Handler called internally when the caret in the Comboxbox's Editbox moves.
	*/
	virtual	void	onCaretMoved(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the selection within the Combobox's Editbox changes.
	*/
	virtual	void	onTextSelectionChanged(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the maximum length is reached for text in the Combobox's Editbox.
	*/
	virtual	void	onEditboxFullEvent(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the text in the Combobox's Editbox is accepted (by various means).
	*/
	virtual	void	onTextAcceptedEvent(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the Combobox's Drop-down list contents are changed.
	*/
	virtual	void	onListContentsChanged(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the selection within the Combobox's drop-down list changes
		(this is not the 'final' accepted selection, just the currently highlighted item).
	*/
	virtual	void	onListSelectionChanged(WindowEventArgs& e);

	/*!
	\brief
		Handler called  fired internally when the sort mode for the Combobox's drop-down list is changed.
	*/
	virtual	void	onSortModeChanged(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the 'force' setting for the vertical scrollbar within the Combobox's
		drop-down list is changed.
	*/
	virtual	void	onVertScrollbarModeChanged(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the 'force' setting for the horizontal scrollbar within the Combobox's
		drop-down list is changed.
	*/
	virtual	void	onHorzScrollbarModeChanged(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the Combobox's drop-down list has been displayed.
	*/
	virtual	void	onDropListDisplayed(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the Combobox's drop-down list has been hidden.
	*/
	virtual	void	onDroplistRemoved(WindowEventArgs& e);

	/*!
	\brief
		Handler called internally when the user has confirmed a selection within the Combobox's drop-down list.
	*/
	virtual	void	onListSelectionAccepted(WindowEventArgs& e);

	/*************************************************************************
		Overridden Event handlers
	*************************************************************************/
	virtual	void	onFontChanged(WindowEventArgs& e);
	virtual void	onTextChanged(WindowEventArgs& e);
	virtual void	onActivated(ActivationEventArgs& e);
    void onSized(ElementEventArgs& e);

	/*************************************************************************
		Implementation Data
	*************************************************************************/
	bool			d_singleClickOperation;		//!< true if user can show and select from list in a single click.
    bool d_autoSizeHeight;
    bool d_autoSizeWidth;

private:
	/*************************************************************************
		Private methods
	*************************************************************************/
	void	addComboboxProperties(void);
};

} // End of  CEGUI namespace section

#if defined(_MSC_VER)
#	pragma warning(pop)
#endif

#endif	// end of guard _CEGUICombobox_h_

redpajama_set_name: RedPajamaGithub


text:
''' A runner script for all acme-web-fe tests

    If no arguments are given, this script will run the tests against a local
        server running at port 8000

    If you would like to test it against another server, give the address as an argument '''
import os
import sys
from subprocess import Popen, PIPE

server = 'localhost:8000'

if len(sys.argv) > 1:
    server = sys.argv[1]

def run_tests(test):
    process = Popen(
        ['pybot', '--outputdir', test, '--variable', 'SERVER:' + server, test], stdout=PIPE)
    (out, err) = process.communicate()
    exit_code = process.wait()
    print out

if __name__ == '__main__':
    for test in next(os.walk(os.getcwd()))[1]:
        print 'Running test', test
        run_tests(test)


text:
/* $FreeBSD$ */
/* This is an edited copy of the config.h generated by configure. */

/* config.h.  Generated from config.h.in by configure.  */
/* config.h.in.  Generated from configure.in by autoheader.  */

/* Enable optimizer debugging */
/* #undef BDEBUG */

/* define if you have a cloning BPF device */
#define HAVE_CLONING_BPF 1

/* define if you have the DAG API */
/* #undef HAVE_DAG_API */

/* define if you have dag_get_erf_types() */
/* #undef HAVE_DAG_GET_ERF_TYPES */

/* define if you have dag_get_stream_erf_types() */
/* #undef HAVE_DAG_GET_STREAM_ERF_TYPES */

/* define if you have streams capable DAG API */
/* #undef HAVE_DAG_STREAMS_API */

/* define if you have vdag_set_device_info() */
/* #undef HAVE_DAG_VDAG */

/* Define to 1 if you have the declaration of `ether_hostton', and to 0 if you
   don't. */
#define HAVE_DECL_ETHER_HOSTTON 1

/* define if you have a /dev/dlpi */
/* #undef HAVE_DEV_DLPI */

/* if passive_req_t primitive exists */
/* #undef HAVE_DLPI_PASSIVE */

/* Define to 1 if you have the `ether_hostton' function. */
#define HAVE_ETHER_HOSTTON 1

/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
#define HAVE_FSEEKO 1

/* on HP-UX 10.20 or later */
/* #undef HAVE_HPUX10_20_OR_LATER */

/* on HP-UX 9.x */
/* #undef HAVE_HPUX9 */

/* if ppa_info_t_dl_module_id exists */
/* #undef HAVE_HP_PPA_INFO_T_DL_MODULE_ID_1 */

/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1

/* if libdlpi exists */
/* #undef HAVE_LIBDLPI */

/* if libnl exists */
/* #undef HAVE_LIBNL */

/* if libnl exists and is version 2.x */
/* #undef HAVE_LIBNL_2_x */

/* if libnl exists and is version 3.x */
/* #undef HAVE_LIBNL_3_x */

/* libnl has NLE_FAILURE */
/* #undef HAVE_LIBNL_NLE */

/* libnl has new-style socket api */
/* #undef HAVE_LIBNL_SOCKETS */

/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1

/* Define to 1 if you have the <linux/compiler.h> header file. */
/* #undef HAVE_LINUX_COMPILER_H */

/* Define to 1 if you have the <linux/ethtool.h> header file. */
/* #undef HAVE_LINUX_ETHTOOL_H */

/* Define to 1 if you have the <linux/if_packet.h> header file. */
/* #undef HAVE_LINUX_IF_PACKET_H */

/* Define to 1 if you have the <linux/net_tstamp.h> header file. */
/* #undef HAVE_LINUX_NET_TSTAMP_H */

/* if tp_vlan_tci exists */
/* #undef HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI */

/* Define to 1 if you have the <linux/types.h> header file. */
/* #undef HAVE_LINUX_TYPES_H */

/* Define to 1 if you have the <linux/usbdevice_fs.h> header file. */
/* #undef HAVE_LINUX_USBDEVICE_FS_H */

/* Define to 1 if you have the <linux/wireless.h> header file. */
/* #undef HAVE_LINUX_WIRELESS_H */

/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1

/* Define to 1 if you have the <netinet/ether.h> header file. */
/* #undef HAVE_NETINET_ETHER_H */

/* Define to 1 if you have the <netinet/if_ether.h> header file. */
#define HAVE_NETINET_IF_ETHER_H 1

/* Define to 1 if you have the <netpacket/if_packet.h> header file. */
/* #undef HAVE_NETPACKET_IF_PACKET_H */

/* Define to 1 if you have the <netpacket/packet.h> header file. */
/* #undef HAVE_NETPACKET_PACKET_H */

/* Define to 1 if you have the <net/if_media.h> header file. */
#define HAVE_NET_IF_MEDIA_H 1

/* Define to 1 if you have the <net/pfvar.h> header file. */
/* See Makefile */
/* #undef HAVE_NET_PFVAR_H */

/* if there's an os_proto.h for this platform, to use additional prototypes */
/* #undef HAVE_OS_PROTO_H */

/* Define to 1 if you have the <paths.h> header file. */
#define HAVE_PATHS_H 1

/* define if net/pfvar.h defines PF_NAT through PF_NORDR */
#define HAVE_PF_NAT_THROUGH_PF_NORDR 1

/* define if you have a Septel API */
/* #undef HAVE_SEPTEL_API */

/* define if you have Myricom SNF API */
/* #undef HAVE_SNF_API */

/* Define to 1 if you have the `snprintf' function. */
#define HAVE_SNPRINTF 1

/* if struct sockaddr has the sa_len member */
#define HAVE_SOCKADDR_SA_LEN 1

/* if struct sockaddr_storage exists */
#define HAVE_SOCKADDR_STORAGE 1

/* define if socklen_t is defined */
#define HAVE_SOCKLEN_T 1

/* On solaris */
/* #undef HAVE_SOLARIS */

/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1

/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1

/* Define to 1 if you have the `strerror' function. */
#define HAVE_STRERROR 1

/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1

/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1

/* Define to 1 if you have the `strlcpy' function. */
#define HAVE_STRLCPY 1

/* Define to 1 if the system has the type `struct BPF_TIMEVAL'. */
/* #undef HAVE_STRUCT_BPF_TIMEVAL */

/* Define to 1 if the system has the type `struct ether_addr'. */
/* #undef HAVE_STRUCT_ETHER_ADDR */

/* Define to 1 if you have the <sys/bitypes.h> header file. */
/* #undef HAVE_SYS_BITYPES_H */

/* Define to 1 if you have the <sys/bufmod.h> header file. */
/* #undef HAVE_SYS_BUFMOD_H */

/* Define to 1 if you have the <sys/dlpi_ext.h> header file. */
/* #undef HAVE_SYS_DLPI_EXT_H */

/* Define to 1 if you have the <sys/ioccom.h> header file. */
#define HAVE_SYS_IOCCOM_H 1

/* Define to 1 if you have the <sys/sockio.h> header file. */
#define HAVE_SYS_SOCKIO_H 1

/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1

/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1

/* if if_packet.h has tpacket_stats defined */
/* #undef HAVE_TPACKET_STATS */

/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1

/* if struct usbdevfs_ctrltransfer has bRequestType */
/* #undef HAVE_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE */

/* define if version.h is generated in the build procedure */
#define HAVE_VERSION_H 1

/* Define to 1 if you have the `vsnprintf' function. */
#define HAVE_VSNPRINTF 1

/* define if the system supports zerocopy BPF */
#define HAVE_ZEROCOPY_BPF 1

/* define if your compiler has __attribute__ */
#define HAVE___ATTRIBUTE__ 1

/* IPv6 */
/* See Makefile */
/* #undef INET6 */

/* if unaligned access fails */
/* #undef LBL_ALIGN */

/* path for device for USB sniffing */
/* #undef LINUX_USB_MON_DEV */

/* if we need a pcap_parse wrapper around yyparse */
#define NEED_YYPARSE_WRAPPER

/* Define to 1 if netinet/ether.h declares `ether_hostton' */
/* #undef NETINET_ETHER_H_DECLARES_ETHER_HOSTTON */

/* Define to 1 if netinet/if_ether.h declares `ether_hostton' */
#define NETINET_IF_ETHER_H_DECLARES_ETHER_HOSTTON

/* do not use protochain */
/* #undef NO_PROTOCHAIN */

/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT ""

/* Define to the full name of this package. */
#define PACKAGE_NAME ""

/* Define to the full name and version of this package. */
#define PACKAGE_STRING ""

/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME ""

/* Define to the version of this package. */
#define PACKAGE_VERSION ""

/* /dev/dlpi directory */
/* #undef PCAP_DEV_PREFIX */

/* target host supports Bluetooth sniffing */
/* #undef PCAP_SUPPORT_BT */

/* target host supports CAN sniffing */
/* #undef PCAP_SUPPORT_CAN */

/* target host supports canusb */
/* #undef PCAP_SUPPORT_CANUSB */

/* target host supports netfilter sniffing */
/* #undef PCAP_SUPPORT_NETFILTER */

/* target host supports USB sniffing */
/* #undef PCAP_SUPPORT_USB */

/* target host supports netmap */
#define PCAP_SUPPORT_NETMAP 1

/* include ACN support */
/* #undef SITA */

/* if struct sockaddr_hci has hci_channel member */
/* #undef SOCKADDR_HCI_HAS_HCI_CHANNEL */

/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1

/* Enable parser debugging */
/* #undef YYDEBUG */

/* Number of bits in a file offset, on hosts where this is settable. */
/* #undef _FILE_OFFSET_BITS */

/* needed on HP-UX */
/* #undef _HPUX_SOURCE */

/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
/* #undef _LARGEFILE_SOURCE */

/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */

/* define on AIX to get certain functions */
/* #undef _SUN */

/* to handle Ultrix compilers that don't support const in prototypes */
/* #undef const */

/* Define as token for inline if inlining supported */
#define inline inline

/* Define to `short' if int16_t not defined. */
/* #undef int16_t */

/* Define to `int' if int32_t not defined. */
/* #undef int32_t */

/* Define to `long long' if int64_t not defined. */
/* #undef int64_t */

/* Define to `signed char' if int8_t not defined. */
/* #undef int8_t */

/* on sinix */
/* #undef sinix */

/* Define to `unsigned short' if u_int16_t not defined. */
/* #undef u_int16_t */

/* Define to `unsigned int' if u_int32_t not defined. */
/* #undef u_int32_t */

/* Define to `unsigned long long' if u_int64_t not defined. */
/* #undef u_int64_t */

/* Define to `unsigned char' if u_int8_t not defined. */
/* #undef u_int8_t */


text:
using ComponentFactory.Krypton.Toolkit;

namespace OpenInvoicePeru.WinApp
{
    public partial class PlantillaBase : KryptonForm
    {
        public PlantillaBase()
        {
            InitializeComponent();
        }
    }
}


text:
<?php get_header(); ?>

		<?php if (have_posts()) : ?>

		 <?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?>
<?php /* If this is a category archive */ if (is_category()) { ?>

<?php printf(__('Archive for the %s Category', 'black-letterhead'), single_cat_title('', false)); ?>

 	  <?php /* If this is a tag archive */ } elseif (is_tag()) { ?>

<?php printf(__('Archive for %s', 'black-letterhead'), single_tag_title('', false)); ?>

 	  <?php /* If this is a daily archive */ } elseif (is_day()) { ?>

<?php printf(__('Archive for %s', 'black-letterhead'), get_the_time(get_option('date_format'))); ?>

	 <?php /* If this is a monthly archive */ } elseif (is_month()) { ?>

<?php printf(__('Archive for %s', 'black-letterhead'), get_the_time('F, Y')); ?>

		<?php /* If this is a yearly archive */ } elseif (is_year()) { ?>

<?php printf(__('Archive for %s', 'black-letterhead'), get_the_time('Y')); ?>

	  <?php /* If this is a search */ } elseif (is_search()) { ?>

<?php _e('Search Results', 'black-letterhead'); ?>

	  <?php /* If this is an author archive */ } elseif (is_author()) { ?>

<?php _e('Author Archive', 'black-letterhead'); ?>

		<?php /* If this is a paged archive */ } elseif (isset($_GET['paged']) && !empty($_GET['paged'])) { ?>

<?php _e('Blog Archives', 'black-letterhead'); ?>

		<?php } ?>

<?php next_posts_link(__('« Older Entries', 'black-letterhead')) ?>

<?php previous_posts_link(__('Newer Entries »', 'black-letterhead')) ?>

		<?php while (have_posts()) : the_post(); ?>
		<?php require('post.php'); ?>

		<?php endwhile; ?>

<?php next_posts_link(__('« Older Entries', 'black-letterhead')) ?>

<?php previous_posts_link(__('Newer Entries »', 'black-letterhead')) ?>

	<?php else : ?>

<?php _e('Not Found', 'black-letterhead'); ?>

		<?php get_search_form(); ?>

	<?php endif; ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
layout: post
title: 'ReactJS : designing better component api (Functional)'
excerpt: 'ReactJS : designing better component api (Functional)'
date: 2020-05-08 00:05:00 IST
updated: 2020-05-08 00:05:00 IST
categories: javascript
tags: reactjs
---
Part 1 of this post is available at [designing better component api - UI][part 1]

# Part 2 : For Functional / Large UI components

In part 1 we discussed the API for primitive UI components. In this we will discuss about Functional (not stateless) components or
some large UI components composed using primitive UI components.

# Derive value from existing data

Refrain yourself from passing unwanted props, where its values can be derived from the other props which we are already passing to the component.
Consider the example below. We are passing an array of players and total count of them as props

```js
// bad
const PlayerList = ({ players, totalPlayerCount }) => {
   if (totalPlayerCount === 0) {
       // render empty message
   }
   // render player list
}
```

In this we can derive the `totalPlayerCount` from the array of players itself using the `.length` property.
Thus we can reduce the number of props we are passing into.

```js
// better
const PlayerList = ({ players }) => {
   if (players.length === 0) {
       // render empty message
   }
   // render player list
}
```

# Pass minimal data required for the component to render

I have seen many beginners passing the whole object to the component and use only one or two properties inside the component.
This will make the component difficult to optimize and test.

```js
// bad
const Player = ({ player }) => {
 return (
   <div>
     <div>{player.name}</div>
     <div>{player.score}</div>
   </div>
 )
}
```

In the above example player can have 20 or 30 properties which are not used in the `Player` component.
So instead of passing the player object, if pass the only properties needed for this component like `name` & `score`
will make this component simpler and easy to optimize.

```js
const Player = ({ name, score }) => {
 return (
   <div>
     <div>{name}</div>
     <div>{score}</div>
   </div>
 )
}
```

#  function.bind instead of calling from inside.

Sometimes passing minimum data into components won't work because we might need to pass the whole data into an action.
Considering the code below, we can't avoid passing the `player` object because it is required as the parameter for `onSelect` method.

```js
// bad
const Player = ({ player, onSelect }) => {
 return (
   <div>
     <div>{player.name}</div>
     <div>{player.score}</div>
     <div><button onClick={() => onSelect(player)}>Select</button></div>
   </div>
 )
}
```

In such a case, bind the `onSelect` method with the `player` object and pass it to the component.

```js
// better
const Player = ({ name, score, onSelect }) => {
 return (
   <div>
     <div>{name}</div>
     <div>{score}</div>
     <div><button onSelect={onSelect}>Select</button></div>
   </div>
 )
}

// usage

<Player
 name={player.name}
 score={player.score}
 onSelect={handleSelect.bind(this, player)}
/>
```

Now the `<Player />` component is no more depended on whole `player` object and we can pass only the `name` & `score` to it.

#  remove unwanted arrow functions wrapping

This is a common pattern I have seen in many codebase that instead of just passing the function to event listeners, they will be wrapped inside unnecessary arrow functions.

```js
// bad
const Player = ({ player, onSelect }) => {
 return (
   <div>
     <div>{player.name}</div>
     <div>{player.score}</div>
     <div><button onClick={(evt) => onSelect(evt)}>Select</button></div>
   </div>
 )
}
```

This mistake is mostly done by newbies who got confused between these two usages, `onClick={onSelect}` and `onClick={onSelect()}`. The later will cause function invocation on each re-render and to fix this they wrap in an arrow function.

```js
// better
const Player = ({ name, score, onSelect }) => {
 return (
   <div>
     <div>{name}</div>
     <div>{score}</div>
     <div><button onclick={onSelect}>Select</button></div>
   </div>
 )
}
```

Adding an arrow function does not necessarily add any performance overhead, but it can cause logical errors in case we decide to add a new param or remove a param later.
In such cases we have to make changes in all the instances of this unnecessary wrapping along the way from top most to the child component.

In case of `onClick={onSelect}` the changes required are only in 2 places, in function definition and at where it invokes.

[part 1]: /2020/03/reactjs-designing-better-component-api.html


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.nbandroid.netbeans.gradle.testrunner;

import com.android.ddmlib.testrunner.ITestRunListener;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import java.util.Map;
import java.util.logging.Logger;
import org.netbeans.api.project.Project;
import org.netbeans.modules.gsf.testrunner.api.CoreManager;
import org.netbeans.modules.gsf.testrunner.api.Status;
import org.netbeans.modules.gsf.testrunner.api.TestSession;
import org.netbeans.modules.gsf.testrunner.api.TestSuite;
import org.netbeans.modules.gsf.testrunner.api.Testcase;
import org.netbeans.modules.gsf.testrunner.api.Trouble;
import org.openide.util.Lookup;

/**
 * Test run listener that send output to GSF testrunner.
 */
class TestRunListener implements ITestRunListener {

    private static final CoreManager testManager = Lookup.getDefault().lookup(CoreManager.class);

    private static final Logger LOG = Logger.getLogger(TestRunListener.class.getName());

    private final Project project;
    private TestSession testSession;

    public TestRunListener(Project project) {
        this.project = Preconditions.checkNotNull(project);
    }

    @Override
    public void testRunStarted(String string, int i) {
        testSession = new TestSession("Android tests", project, TestSession.SessionType.TEST);
        String suiteName = string;
        TestSuite testSuite = new TestSuite(suiteName);
        testSession.addSuite(testSuite);
        testManager.displaySuiteRunning(testSession, testSuite);
    }

    @Override
    public void testStarted(TestIdentifier ti) {
        Testcase testcase = new Testcase(ti.getTestName(), null, testSession);
        testcase.setClassName(ti.getClassName());
        testSession.addTestCase(testcase);
        testManager.testStarted(testSession);
    }

    @Override
    public void testFailed(TestIdentifier ti, String string) {
        Trouble trouble = new Trouble(false);
        trouble.setStackTrace(Iterables.toArray(Splitter.on('\n').split(string), String.class));
        testSession.getCurrentTestCase().setTrouble(trouble);
        testSession.getCurrentTestCase().setStatus(Status.FAILED);
    }

    @Override
    public void testEnded(TestIdentifier ti, Map<String, String> map) {
        // no-op - called always
    }

    @Override
    public void testRunFailed(String string) {
        testManager.sessionFinished(testSession);
    }

    @Override
    public void testRunStopped(long l) {
        testManager.sessionFinished(testSession);
        testManager.displayReport(testSession, testSession.getReport(l));
    }

    @Override
    public void testRunEnded(long l, Map<String, String> map) {
        testManager.sessionFinished(testSession);
        testManager.displayReport(testSession, testSession.getReport(l));
    }

    @Override
    public void testAssumptionFailure(TestIdentifier ti, String msg) {
        // TODO how to report this?
        testSession.getCurrentTestCase().setStatus(Status.SKIPPED);
        // testSession.getCurrentTestCase().set(msg);
    }

    @Override
    public void testIgnored(TestIdentifier ti) {
        testSession.getCurrentTestCase().setStatus(Status.IGNORED);
    }

}


text:
package org.sakaiproject.attendance.tool.dataproviders;

import org.apache.wicket.model.IModel;
import org.sakaiproject.attendance.model.AttendanceEvent;
import org.sakaiproject.attendance.tool.models.DetachableEventModel;

import java.util.Collections;
import java.util.List;

/**
 * An EventDataProvider
 *
 * @author Leonardo Canessa [lcanessa1 (at) udayton (dot) edu]
 * @author David Bauer [dbauer1 (at) udayton (dot) edu]
 */
public class EventDataProvider extends BaseProvider<AttendanceEvent> {
    public EventDataProvider() {
        super();
    }

    /**
     * Constructor with the data provided
     * @param data, a List of AttendanceEvents
     */
    public EventDataProvider(List<AttendanceEvent> data) {
        super();
        if(data != null && !data.isEmpty()) {
            this.list = data;
        }
    }

    protected List<AttendanceEvent> getData() {
        if(this.list == null) {
            this.list = attendanceLogic.getAttendanceEventsForCurrentSite();
            Collections.reverse(this.list);
        }
        return this.list;
    }

    @Override
    public IModel<AttendanceEvent> model(AttendanceEvent object){
        return new DetachableEventModel(object);
    }
}


text:
import { createSelector, createStructuredSelector } from 'reselect';
import { showBlueprintButtonsSelector } from 'modules/workspace/containers/BlueprintControls/selectors';

export const pagesSelector = state => state.deskPage.pages;
export const deskPageSelector = state => state.deskPage;

export const currentPageSelector = createSelector(
  deskPageSelector,
  (deskPage) => {
    const {currentPageIndex, currentPageName, currentPagePath} = deskPage;
    return {
      pageIndex: currentPageIndex,
      pageName: currentPageName,
      pagePath: currentPagePath,
    };
  }
);

export const modelSelector = createStructuredSelector({
  componentModel: state => state.deskPage,
  clipboardIndicatorModel: state => state.clipboardIndicator,
  selectionBreadcrumbsModel: state => state.selectionBreadcrumbs,
  showBlueprintButtons: showBlueprintButtonsSelector,
});


text:
<?php

/*
 * This file is part of the WSDL2PHPGenerator package.
 * (c) WSDL2PHPGenerator.
 */

namespace Wsdl2PhpGenerator;

use Wsdl2PhpGenerator\PhpSource\PhpClass;

/**
 * Type is an abstract baseclass for all types in the wsdl.
 *
 * @author Fredrik Wallgren <fredrik.wallgren@gmail.com>
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
abstract class Type implements ClassGenerator
{
    /**
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @var PhpClass The class used to create the type. This is not used by patterns
     */
    protected $class;

    /**
     * @var string The name of the type
     */
    protected $identifier;

    /**
     * @var string The name of the type used in php code ie. the validated name
     */
    protected $phpIdentifier;

    /**
     * @var string The name of the type used in php code with namespace (if needed) ie. the validated name
     */
    protected $phpNamespacedIdentifier;

    /**
     * @var string The datatype the simple type is of. This not used by complex types
     */
    protected $datatype;

    /**
     * The minimum construction.
     *
     * @param ConfigInterface $config   The configuration
     * @param string          $name     The identifier for the type
     * @param string          $datatype The restriction(DataType)
     */
    public function __construct(ConfigInterface $config, $name, $datatype)
    {
        $this->config     = $config;
        $this->class      = null;
        $this->datatype   = $datatype;
        $this->identifier = $name;

        $this->phpIdentifier           = Validator::validateClass($name, $this->config->get('namespaceName'));
        $this->phpNamespacedIdentifier = $this->phpIdentifier;
        if ($this->config->get('namespaceName')) {
            $this->phpNamespacedIdentifier = '\\'.$this->config->get('namespaceName').'\\'.$this->phpIdentifier;
        }
    }

    /**
     * The abstract function for subclasses to implement
     * This should load the class data into $class
     * This is called by getClass if not previously called.
     */
    abstract protected function generateClass();

    /**
     * Getter for the class. Generates the class if it's null.
     *
     * @return PhpClass
     */
    public function getClass()
    {
        if ($this->class == null) {
            $this->generateClass();
        }

        return $this->class;
    }

    /**
     * Getter for the datatype.
     *
     * @return string
     */
    public function getDatatype()
    {
        return $this->datatype;
    }

    /**
     * Getter for the name.
     *
     * @return string
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

    /**
     * @return string The validated name of the type
     */
    public function getPhpIdentifier()
    {
        return $this->phpIdentifier;
    }
}


text:
	#include <io.h>
#endif
#include <fcntl.h>
#include <fstream>
#include "../imtjson/json.h"
#include "../imtjson/compress.tcc"

int main(int argc, char **argv)
{
#ifdef _WIN32
	_setmode(_fileno(stdout), _O_BINARY);
#endif
	try {

		using namespace json;
		Value v = Value::fromStream(std::cin);
		v.serialize(emitUtf8,compress(toStream(std::cout)));

		return 0;
	}
	catch (std::exception &e) {
		std::cerr << "Fatal error: " << e.what() << std::endl;
		return 1;
	}
}


text:
package com.intellij.codeInspection.dataFlow.instructions;

import com.intellij.codeInspection.dataFlow.DataFlowRunner;
import com.intellij.codeInspection.dataFlow.DfaInstructionState;
import com.intellij.codeInspection.dataFlow.DfaMemoryState;
import com.intellij.codeInspection.dataFlow.InstructionVisitor;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiPolyadicExpression;
import com.intellij.psi.PsiType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.Nullable;

import static com.intellij.psi.JavaTokenType.*;

public class BinopInstruction extends BranchingInstruction implements ExpressionPushingInstruction {
  private static final TokenSet ourSignificantOperations =
    TokenSet.create(EQEQ, NE, LT, GT, LE, GE, INSTANCEOF_KEYWORD, PLUS, MINUS, AND, PERC, DIV, GTGT, GTGTGT);
  private final IElementType myOperationSign;
  private final @Nullable PsiType myResultType;
  private final int myLastOperand;

  public BinopInstruction(IElementType opSign, @Nullable PsiExpression psiAnchor, @Nullable PsiType resultType) {
    this(opSign, psiAnchor, resultType, -1);
  }

  public BinopInstruction(IElementType opSign, @Nullable PsiExpression psiAnchor, @Nullable PsiType resultType, int lastOperand) {
    super(psiAnchor);
    myResultType = resultType;
    myOperationSign = ourSignificantOperations.contains(opSign) ? opSign : null;
    myLastOperand = lastOperand;
  }

  /**
   * @return range inside the anchor which evaluates this instruction, or null if the whole anchor evaluates this instruction
   */
  @Override
  @Nullable
  public TextRange getExpressionRange() {
    if (myLastOperand != -1 && getPsiAnchor() instanceof PsiPolyadicExpression) {
      PsiPolyadicExpression anchor = (PsiPolyadicExpression)getPsiAnchor();
      PsiExpression[] operands = anchor.getOperands();
      if (operands.length > myLastOperand + 1) {
        return new TextRange(0, operands[myLastOperand].getStartOffsetInParent()+operands[myLastOperand].getTextLength());
      }
    }
    return null;
  }

  @Nullable
  @Override
  public PsiExpression getExpression() {
    return (PsiExpression)getPsiAnchor();
  }

  @Override
  public DfaInstructionState[] accept(DataFlowRunner runner, DfaMemoryState stateBefore, InstructionVisitor visitor) {
    return visitor.visitBinop(this, runner, stateBefore);
  }

  @Nullable
  public PsiType getResultType() {
    return myResultType;
  }

  public String toString() {
    return "BINOP " + myOperationSign;
  }

  public IElementType getOperationSign() {
    return myOperationSign;
  }
}


text:
import os
import logging
import unittest

from telemetry.core import util
from telemetry.core.platform import proc_supporting_platform_backend

class TestBackend(
    proc_supporting_platform_backend.ProcSupportingPlatformBackend):

  # pylint: disable=W0223

  def __init__(self):
    super(TestBackend, self).__init__()
    self._mock_files = {}

  def SetMockFile(self, filename, output):
    self._mock_files[filename] = output

  def _GetFileContents(self, filename):
    return self._mock_files[filename]

class ProcSupportingPlatformBackendTest(unittest.TestCase):

  def testGetMemoryStatsBasic(self):
    if not proc_supporting_platform_backend.resource:
      logging.warning('Test not supported')
      return

    backend = TestBackend()
    backend.SetMockFile(
        '/proc/1/stat',
        open(os.path.join(util.GetUnittestDataDir(), 'stat')).read())
    backend.SetMockFile(
        '/proc/1/status',
        open(os.path.join(util.GetUnittestDataDir(), 'status')).read())
    result = backend.GetMemoryStats(1)
    self.assertEquals(result, {'VM': 1025978368,
                               'VMPeak': 1050099712,
                               'WorkingSetSize': 84000768,
                               'WorkingSetSizePeak': 144547840})

  def testGetMemoryStatsNoHWM(self):
    if not proc_supporting_platform_backend.resource:
      logging.warning('Test not supported')
      return

    backend = TestBackend()
    backend.SetMockFile(
        '/proc/1/stat',
        open(os.path.join(util.GetUnittestDataDir(), 'stat')).read())
    backend.SetMockFile(
        '/proc/1/status',
        open(os.path.join(util.GetUnittestDataDir(), 'status_nohwm')).read())
    result = backend.GetMemoryStats(1)
    self.assertEquals(result, {'VM': 1025978368,
                               'VMPeak': 1025978368,
                               'WorkingSetSize': 84000768,
                               'WorkingSetSizePeak': 84000768})


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cell.user.dao.mapper.SysUserMapper">
  <resultMap id="BaseResultMap" type="com.cell.user.dao.entiy.SysUser">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="mobile" jdbcType="VARCHAR" property="mobile" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="salt" jdbcType="VARCHAR" property="salt" />
    <result column="device" jdbcType="VARCHAR" property="device" />
    <result column="status" jdbcType="BIT" property="status" />
    <result column="deleted" jdbcType="BIT" property="deleted" />
    <result column="admin" jdbcType="BIT" property="admin" />
    <result column="created_time" jdbcType="TIMESTAMP" property="createdTime" />
    <result column="created_by" jdbcType="VARCHAR" property="createdBy" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    id, username, email, mobile, password, salt, device, status, deleted, admin, created_time,
    created_by
  </sql>
  <select id="selectByExample" parameterType="com.cell.user.dao.entiy.SysUserExample" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from sys_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
    <if test="limitStart != null and limitStart>=0">
      limit #{limitStart} , #{limitEnd}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    select
    <include refid="Base_Column_List" />
    from sys_user
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    delete from sys_user
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <delete id="deleteByExample" parameterType="com.cell.user.dao.entiy.SysUserExample">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    delete from sys_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.cell.user.dao.entiy.SysUser">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    insert into sys_user (id, username, email,
      mobile, password, salt,
      device, status, deleted, admin,
      created_time, created_by)
    values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR},
      #{mobile,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{salt,jdbcType=VARCHAR},
      #{device,jdbcType=VARCHAR}, #{status,jdbcType=BIT}, #{deleted,jdbcType=BIT}, #{admin,jdbcType=BIT},
      #{createdTime,jdbcType=TIMESTAMP}, #{createdBy,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.cell.user.dao.entiy.SysUser" useGeneratedKeys="true" keyProperty="id">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    insert into sys_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="email != null">
        email,
      </if>
      <if test="mobile != null">
        mobile,
      </if>
      <if test="password != null">
        password,
      </if>
      <if test="salt != null">
        salt,
      </if>
      <if test="device != null">
        device,
      </if>
      <if test="status != null">
        status,
      </if>
      <if test="deleted != null">
        deleted,
      </if>
      <if test="admin != null">
        admin,
      </if>
      <if test="createdTime != null">
        created_time,
      </if>
      <if test="createdBy != null">
        created_by,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        #{email,jdbcType=VARCHAR},
      </if>
      <if test="mobile != null">
        #{mobile,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="salt != null">
        #{salt,jdbcType=VARCHAR},
      </if>
      <if test="device != null">
        #{device,jdbcType=VARCHAR},
      </if>
      <if test="status != null">
        #{status,jdbcType=BIT},
      </if>
      <if test="deleted != null">
        #{deleted,jdbcType=BIT},
      </if>
      <if test="admin != null">
        #{admin,jdbcType=BIT},
      </if>
      <if test="createdTime != null">
        #{createdTime,jdbcType=TIMESTAMP},
      </if>
      <if test="createdBy != null">
        #{createdBy,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.cell.user.dao.entiy.SysUserExample" resultType="java.lang.Integer">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    select count(*) from sys_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    update sys_user
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.username != null">
        username = #{record.username,jdbcType=VARCHAR},
      </if>
      <if test="record.email != null">
        email = #{record.email,jdbcType=VARCHAR},
      </if>
      <if test="record.mobile != null">
        mobile = #{record.mobile,jdbcType=VARCHAR},
      </if>
      <if test="record.password != null">
        password = #{record.password,jdbcType=VARCHAR},
      </if>
      <if test="record.salt != null">
        salt = #{record.salt,jdbcType=VARCHAR},
      </if>
      <if test="record.device != null">
        device = #{record.device,jdbcType=VARCHAR},
      </if>
      <if test="record.status != null">
        status = #{record.status,jdbcType=BIT},
      </if>
      <if test="record.deleted != null">
        deleted = #{record.deleted,jdbcType=BIT},
      </if>
      <if test="record.admin != null">
        admin = #{record.admin,jdbcType=BIT},
      </if>
      <if test="record.createdTime != null">
        created_time = #{record.createdTime,jdbcType=TIMESTAMP},
      </if>
      <if test="record.createdBy != null">
        created_by = #{record.createdBy,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    update sys_user
    set id = #{record.id,jdbcType=BIGINT},
      username = #{record.username,jdbcType=VARCHAR},
      email = #{record.email,jdbcType=VARCHAR},
      mobile = #{record.mobile,jdbcType=VARCHAR},
      password = #{record.password,jdbcType=VARCHAR},
      salt = #{record.salt,jdbcType=VARCHAR},
      device = #{record.device,jdbcType=VARCHAR},
      status = #{record.status,jdbcType=BIT},
      deleted = #{record.deleted,jdbcType=BIT},
      admin = #{record.admin,jdbcType=BIT},
      created_time = #{record.createdTime,jdbcType=TIMESTAMP},
      created_by = #{record.createdBy,jdbcType=VARCHAR}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.cell.user.dao.entiy.SysUser">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    update sys_user
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="mobile != null">
        mobile = #{mobile,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="salt != null">
        salt = #{salt,jdbcType=VARCHAR},
      </if>
      <if test="device != null">
        device = #{device,jdbcType=VARCHAR},
      </if>
      <if test="status != null">
        status = #{status,jdbcType=BIT},
      </if>
      <if test="deleted != null">
        deleted = #{deleted,jdbcType=BIT},
      </if>
      <if test="admin != null">
        admin = #{admin,jdbcType=BIT},
      </if>
      <if test="createdTime != null">
        created_time = #{createdTime,jdbcType=TIMESTAMP},
      </if>
      <if test="createdBy != null">
        created_by = #{createdBy,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.cell.user.dao.entiy.SysUser">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Mar 24 17:07:32 CST 2017.
    -->
    update sys_user
    set username = #{username,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR},
      mobile = #{mobile,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      salt = #{salt,jdbcType=VARCHAR},
      device = #{device,jdbcType=VARCHAR},
      status = #{status,jdbcType=BIT},
      deleted = #{deleted,jdbcType=BIT},
      admin = #{admin,jdbcType=BIT},
      created_time = #{createdTime,jdbcType=TIMESTAMP},
      created_by = #{createdBy,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>


text:
<?php
namespace Cerad\Bundle\CommonBundle\EntityRepository;

use Doctrine\ORM\EntityRepository;
use Cerad\Bundle\CommonBundle\Doctrine\QueryBuilder;

class BaseRepository extends EntityRepository
{
    // Kind of hokay but think of this as an extended EntityManager
    public function clear()        { $this->_em->clear(); }
    public function flush()        { $this->_em->flush(); }
    public function merge  ($item) { $this->_em->merge  ($item); }
    public function remove ($item) { $this->_em->remove ($item); }
    public function detach ($item) { $this->_em->detach ($item); }
    public function persist($item) { $this->_em->persist($item); }
    public function refresh($item) { $this->_em->refresh($item); }

    public function getReference($id)       { return $this->_em->getReference($this->_entityName,$id); }
    public function getEventManager      () { return $this->_em->getEventManager(); }
    public function getDatabaseConnection() { return $this->_em->getConnection(); }

    /* ===================================================
     * Probably trying to do too much but many entities have
     * Identifiers, Project relations and self relations
     * Might be a good use for traits
     */
  //public function getClassName()           { return $this->_entityName; }
    public function getIdentifierClassName() { return $this->_entityName . 'Identifier'; }

    public function getEntityEntityClassName()
    {
        $entityName = $this->_entityName;
        $baseName = substr($entityName,strrpos($entityName,'\\')+1);
        return $entityName . $baseName;;
    }

    public function newEntity() // new by itself is a keyword
    {
        $className = $this->getClassName();
        return new $className();
    }
    public function newIdentifier()
    {
        $className = $this->getIdentifierClassName();
        return new $className();
    }
    public function getIdentifierManager()
    {
        return $this->_em->getRepository($this->getIdentifierClassName());
    }
    public function findByIdentifierValue($value)
    {
        $manager = $this->getIdentifierManager();

        $identifier = $manager->findOneByValue($value);

        return $identifier? $identifier->getEntity() : null;
    }
    public function newEntityEntity()
    {
        $className = $this->getEntityEntityClassName();
        return new $className();
    }
    /* ==========================================================
     * This also comes under the heading of hokay but
     * the convience methods in my query buider really reduces code
     */
    public function createQueryBuilder($alias)
    {
        $qb = new QueryBuilder($this->_em);
        $qb->from($this->_entityName, $alias);
        return $qb;
    }

    /* =====================================================
     * Reinitialize the entire database
     */
    public function resetDatabase()
    {
        $conn = $this->getEntityManager()->getConnection();

        $database = $conn->getDatabase();

        $schema = $conn->getSchemaManager()->createSchema();

        $sqls = $schema->toSql($conn->getDatabasePlatform());

        $conn->executeUpdate('DROP   DATABASE ' . $database . ';');
        $conn->executeUpdate('CREATE DATABASE ' . $database . ';');
        $conn->executeUpdate('USE '             . $database . ';');

        foreach($sqls as $sql)
        {
            $conn->executeUpdate($sql);
        }
    }
    /* ========================================================================
     * Standard hashing
     * Either value or array
     * Remove some punctuation
     * Return actual hash or canocial string
     */
    public function hash($value, $crc = false)
    {
        if (is_array($value))
        {
            $array = $value;
            $value = null;

            // Trim and cat
            array_walk($array, function($val) use (&$value) { $value .= trim($val); });
        }
        // Probably just get rid of everything but letters/numbers,undersocres
        $value = strtoupper(preg_replace("/[^a-zA-Z0-9_]/", '', $value));

        if (!$crc) return $value;

        return hash('crc32',$value);
    }
}
?>


text:
using Microsoft.Extensions.DependencyInjection;

namespace DragonSpark.Composition.Scopes;

sealed class Scopes : IScopes
{
	readonly IServiceScopeFactory _scopes;

	public Scopes(IServiceScopeFactory scopes) => _scopes = scopes;

	public IServiceScope Get() => _scopes.CreateScope();
}


text: search_result['1557']=["topic_00000000000003B8.html","tlece_PostVacancy.LocationName Property",""];


text:
#ifndef SERIALPORT_H
#define SERIALPORT_H

#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QStringList>

//расширенный QSerialPort с возможностью установки настроек через строки
//отслеживанием Command Terminator и расширенным набором ошибок
class serialPort : public QSerialPort
{
    Q_OBJECT
public:
    explicit serialPort();
    ~serialPort();

private:
    QString buff;

signals:
    void readData(QString);
    void error(QString);

public slots:
    void baudRateChanged(QString);
    void dataBitsChanged(QString);
    void flowControlChanged(QString);
    void parityChanged(QString);
    void stopBitsChanged(QString);
    void serialPortChanged(QString);

    void sendData(QString);
    void checkForCommandTerminator();
};

#endif // SERIALPORT_H


text:
angular.module('flight').controller('filterCtrl',['$scope','cityService','$timeout','$q','flightService',function($scope,cityService,$timeout,$q,flightService){

    var self = this;
    self.cities = cityService.list();
    self.querySearch = querySearch;
    self.validCount = [1,2,3,4,5,6];
    self.toggleTab = toggleTab;
    self.currTab = 'oneway';
    self.query = {};
    self.search = search;
    self.filterPrice = filterPrice;

    function querySearch (query) {
      var results = query ? self.cities.filter( createFilterFor(query) ) : self.cities,
          deferred;
      deferred = $q.defer();
      $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
      return deferred.promise;
    }

    function createFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(city) {
        return (city.value.indexOf(lowercaseQuery) >= 0);
      };
    }

    function toggleTab(tab) {
      self.currTab = tab;
      self.query.return = (tab == 'return') ? self.query.return : null;
    }

    function search(){
      flightService.triggerSearch(self.query);
    }

    function filterPrice(){
      flightService.broadcast('filter-price',self.query.range);
    }

}]);