text:
/*
 * Changes for GemFireXD distributed data platform (some marked by "GemStone changes")
 *
 * Portions Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
 *
 * 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. See accompanying
 * LICENSE file.
 */

package	com.pivotal.gemfirexd.internal.impl.sql.compile;

import com.pivotal.gemfirexd.internal.engine.sql.compile.CollectExpressionOperandsVisitor;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.reference.ClassName;
import com.pivotal.gemfirexd.internal.iapi.reference.Limits;
import com.pivotal.gemfirexd.internal.iapi.reference.SQLState;
import com.pivotal.gemfirexd.internal.iapi.services.classfile.VMOpcode;
import com.pivotal.gemfirexd.internal.iapi.services.compiler.MethodBuilder;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.iapi.sql.compile.C_NodeTypes;
import com.pivotal.gemfirexd.internal.iapi.sql.compile.CompilerContext;
import com.pivotal.gemfirexd.internal.iapi.sql.compile.CostEstimate;
import com.pivotal.gemfirexd.internal.iapi.sql.compile.RequiredRowOrdering;
import com.pivotal.gemfirexd.internal.iapi.sql.compile.RowOrdering;
import com.pivotal.gemfirexd.internal.iapi.store.access.ColumnOrdering;
import com.pivotal.gemfirexd.internal.iapi.store.access.SortCostController;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.iapi.util.JBitSet;
import com.pivotal.gemfirexd.internal.impl.sql.compile.ActivationClassBuilder;

/**
 * An OrderByList is an ordered list of columns in the ORDER BY clause.
 * That is, the order of columns in this list is significant - the
 * first column in the list is the most significant in the ordering,
 * and the last column in the list is the least significant.
 *
 */
public class OrderByList extends OrderedColumnList
						implements RequiredRowOrdering {

	private boolean allAscending = true;
	private boolean alwaysSort;
	private ResultSetNode resultToSort;
	private SortCostController scc;
	private Object[] resultRow;
	private ColumnOrdering[] columnOrdering;
	private int estimatedRowSize;
	private boolean sortNeeded = true;

	/**
		Add a column to the list

		@param column	The column to add to the list
	 */
	public void addOrderByColumn(OrderByColumn column)
	{
		addElement(column);

		if (! column.isAscending())
			allAscending = false;
	}

	/**
	 * Are all columns in the list ascending.
	 *
	 * @return	Whether or not all columns in the list ascending.
	 */
	boolean allAscending()
	{
		return allAscending;
	}

	/**
		Get a column from the list

		@param position	The column to get from the list
	 */
	//GemStone changes BEGIN
	/*public OrderByColumn getOrderByColumn(int position) {
		if (SanityManager.DEBUG)
		SanityManager.ASSERT(position >=0 && position < size());
		return (OrderByColumn) elementAt(position);
	}*/

	//GemStone changes END

	/**
		Print the list.

		@param depth		The depth at which to indent the sub-nodes
	 */
	public void printSubNodes(int depth) {

		if (SanityManager.DEBUG)
		{
			for (int index = 0; index < size(); index++)
			{
				( (OrderByColumn) (elementAt(index)) ).treePrint(depth);
			}
		}
	}

	/**
		Bind the update columns by their names to the target resultset
		of the cursor specification.

		@param target	The underlying result set

		@exception StandardException		Thrown on error
	 */
	public void bindOrderByColumns(ResultSetNode target)
					throws StandardException {

		/* Remember the target for use in optimization */
		resultToSort = target;

		int size = size();

		/* Only 1012 columns allowed in ORDER BY clause */
		if (size > Limits.DB2_MAX_ELEMENTS_IN_ORDER_BY)
		{
			throw StandardException.newException(SQLState.LANG_TOO_MANY_ELEMENTS,
			    Limits.DB2_MAX_ELEMENTS_IN_ORDER_BY /* GemStoneAddition */);
		}

		for (int index = 0; index < size; index++)
		{
			OrderByColumn obc = (OrderByColumn) elementAt(index);
			obc.bindOrderByColumn(target, this);

			/*
			** Always sort if we are ordering on an expression, and not
			** just a column.
			*/
			if ( !
			 (obc.getResultColumn().getExpression() instanceof ColumnReference))
			{
				alwaysSort = true;
			}
		}
	}

	/**
	 * Adjust addedColumnOffset values due to removal of a duplicate column
	 *
	 * This routine is called by bind processing when it identifies and
	 * removes a column from the result column list which was pulled up due
	 * to its presence in the ORDER BY clause, but which was later found to
	 * be a duplicate. The OrderByColumn instance for the removed column
	 * has been adjusted to point to the true column in the result column
	 * list and its addedColumnOffset has been reset to -1. This routine
	 * finds any other OrderByColumn instances which had an offset greater
	 * than that of the column that has been deleted, and decrements their
	 * addedColumOffset to account for the deleted column's removal.
	 *
	 * @param gap   column which has been removed from the result column list
	 */
	void closeGap(int gap)
	{
		for (int index = 0; index < size(); index++)
		{
			OrderByColumn obc = (OrderByColumn) elementAt(index);
			obc.collapseAddedColumnGap(gap);
		}
	}

	/**
		Pull up Order By columns by their names to the target resultset
		of the cursor specification.

		@param target	The underlying result set

	 */
	public void pullUpOrderByColumns(ResultSetNode target)
					throws StandardException {

		/* Remember the target for use in optimization */
		resultToSort = target;

		int size = size();
		for (int index = 0; index < size; index++)
		{
			OrderByColumn obc = (OrderByColumn) elementAt(index);
			obc.pullUpOrderByColumn(target);
		}

	}

	/**
	 * Is this order by list an in order prefix of the specified RCL.
	 * This is useful when deciding if an order by list can be eliminated
	 * due to a sort from an underlying distinct or union.
	 *
	 * @param sourceRCL	The source RCL.
	 *
	 * @return Whether or not this order by list an in order prefix of the specified RCL.
	 */
	boolean isInOrderPrefix(ResultColumnList sourceRCL)
	{
		boolean inOrderPrefix = true;
		int rclSize = sourceRCL.size();

		if (SanityManager.DEBUG)
		{
			if (size() > sourceRCL.size())
			{
				SanityManager.THROWASSERT(
					"size() (" + size() +
					") expected to be <= sourceRCL.size() (" +
					sourceRCL.size() + ")");
			}
		}

		int size = size();
		for (int index = 0; index < size; index++)
		{
			if (((OrderByColumn) elementAt(index)).getResultColumn() !=
				(ResultColumn) sourceRCL.elementAt(index))
			{
				return false;
			}
		}
		return true;
	}

	/**
	 * Order by columns now point to the PRN above the node of interest.
	 * We need them to point to the RCL under that one.  This is useful
	 * when combining sorts where we need to reorder the sorting
	 * columns.
	 */
	void resetToSourceRCs()
	{
		int size = size();
		for (int index = 0; index < size; index++)
		{
			OrderByColumn obc = (OrderByColumn) elementAt(index);
			obc.resetToSourceRC();
		}
	}

	/**
	 * Build a new RCL with the same RCs as the passed in RCL
	 * but in an order that matches the ordering columns.
	 *
	 * @param resultColumns	The RCL to reorder.
	 *
	 *	@exception StandardException		Thrown on error
	 */
	ResultColumnList reorderRCL(ResultColumnList resultColumns)
		throws StandardException
	{
		ResultColumnList newRCL = (ResultColumnList) getNodeFactory().getNode(
												C_NodeTypes.RESULT_COLUMN_LIST,
												getContextManager());

		/* The new RCL starts with the ordering columns */
		int size = size();
		for (int index = 0; index < size; index++)
		{
			OrderByColumn obc = (OrderByColumn) elementAt(index);
			newRCL.addElement(obc.getResultColumn());
			resultColumns.removeElement(obc.getResultColumn());
		}

		/* And ends with the non-ordering columns */
		newRCL.destructiveAppend(resultColumns);
		newRCL.resetVirtualColumnIds();
		newRCL.copyOrderBySelect(resultColumns);
		return newRCL;
	}

	/**
		Remove any constant columns from this order by list.
		Constant columns are ones where all of the column references
		are equal to constant expressions according to the given
		predicate list.
	 */
	void removeConstantColumns(PredicateList whereClause)
	{
		/* Walk the list backwards so we can remove elements safely */
		for (int loc = size() - 1;
			 loc >= 0;
			 loc--)
		{
			OrderByColumn obc = (OrderByColumn) elementAt(loc);

			if (obc.constantColumn(whereClause))
			{
				removeElementAt(loc);
			}
		}
	}

	/**
		Remove any duplicate columns from this order by list.
		For example, one may "ORDER BY 1, 1, 2" can be reduced
		to "ORDER BY 1, 2".
		Beetle 5401.
	 */
	void removeDupColumns()
	{
		/* Walk the list backwards so we can remove elements safely */
		for (int loc = size() - 1; loc > 0; loc--)
		{
			OrderByColumn obc = (OrderByColumn) elementAt(loc);
			int           colPosition = obc.getColumnPosition();

			for (int inner = 0; inner < loc; inner++)
			{
				OrderByColumn prev_obc = (OrderByColumn) elementAt(inner);
				if (colPosition == prev_obc.getColumnPosition())
				{
					removeElementAt(loc);
					break;
				}
			}
		}
	}

	/**
    	generate the sort result set operating over the source
		expression.

		@param acb the tool for building the class
		@param mb	the method the generated code is to go into
		@exception StandardException thrown on failure
	 */
	public void generate(ActivationClassBuilder acb,
								MethodBuilder mb,
								ResultSetNode child)
							throws StandardException
	{
		/*
		** If sorting is not required, don't generate a sort result set -
		** just return the child result set.
		*/
		if ( ! sortNeeded) {
			child.generate(acb, mb);
			return;
		}

		/* Get the next ResultSet#, so we can number this ResultSetNode, its
		 * ResultColumnList and ResultSet.
		 *
		 * REMIND: to do this properly (if order bys can live throughout
		 * the tree) there ought to be an OrderByNode that holds its own
		 * ResultColumnList that is a lsit of virtual column nodes pointing
		 * to the source's result columns.  But since we know it is outermost,
		 * we just gloss over that and get ourselves a resultSetNumber
		 * directly.
		 */
		CompilerContext cc = getCompilerContext();

		/*
			create the orderItem and stuff it in.
		 */
		int orderItem = acb.addItem(acb.getColumnOrdering(this));

		/* Generate the SortResultSet:
		 *	arg1: childExpress - Expression for childResultSet
		 *  arg2: distinct - always false, we have a separate node
		 *				for distincts
		 *  arg3: isInSortedOrder - is the source result set in sorted order
		 *  arg4: orderItem - entry in saved objects for the ordering
		 *  arg5: rowAllocator - method to construct rows for fetching
		 *			from the sort
		 *  arg6: row size
		 *  arg7: resultSetNumber
		 *  arg8: estimated row count
		 *  arg9: estimated cost
		 */

		acb.pushGetResultSetFactoryExpression(mb);

		child.generate(acb, mb);

		int resultSetNumber = cc.getNextResultSetNumber();

		// is a distinct query
		mb.push(false);

		// not in sorted order
		mb.push(false);

		mb.push(orderItem);

		// row allocator
		child.getResultColumns().generateHolder(acb, mb);

		mb.push(child.getResultColumns().getTotalColumnSize());

		mb.push(resultSetNumber);

		// Get the cost estimate for the child
		// RESOLVE - we will eventually include the cost of the sort
		CostEstimate costEstimate = child.getFinalCostEstimate();

		mb.push(costEstimate.rowCount());
		mb.push(costEstimate.getEstimatedCost());

		mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getSortResultSet",
							ClassName.NoPutResultSet, 9);

	}

	/* RequiredRowOrdering interface */

	/**
	 * @see RequiredRowOrdering#sortRequired
	 *
	 * @exception StandardException		Thrown on error
	 */
	public int sortRequired(RowOrdering rowOrdering) throws StandardException
	{
		return sortRequired(rowOrdering, (JBitSet) null);
	}

	/**
	 * @see RequiredRowOrdering#sortRequired
	 *
	 * @exception StandardException		Thrown on error
	 */
	public int sortRequired(RowOrdering rowOrdering, JBitSet tableMap)
				throws StandardException
	{
		/*
		** Currently, all indexes are ordered ascending, so a descending
		** ORDER BY always requires a sort.
		*/
		if (alwaysSort)
		{
			return RequiredRowOrdering.SORT_REQUIRED;
		}

		/*
		** Step through the columns in this list, and ask the
		** row ordering whether it is ordered on each column.
		*/
		int position = 0;
		int size = size();
		for (int loc = 0; loc < size; loc++)
		{
		  //GemStone changes BEGIN
			OrderedColumn obc = getOrderedColumn(loc);
	                  //GemStone changes RND
            // If the user specified NULLS FIRST or NULLS LAST in such a way
            // as to require NULL values to be re-sorted to be lower than
            // non-NULL values, then a sort is required, as the index holds
            // NULL values unconditionally higher than non-NULL values
            //
            if (obc.isNullsOrderedLow())
				return RequiredRowOrdering.SORT_REQUIRED;

			// ResultColumn rc = obc.getResultColumn();

			/*
			** This presumes that the OrderByColumn refers directly to
			** the base column, i.e. there is no intervening VirtualColumnNode.
			*/
			// ValueNode expr = obc.getNonRedundantExpression();
			ValueNode expr = obc.getResultColumn().getExpression();

			if ( ! (expr instanceof ColumnReference))
			{
				return RequiredRowOrdering.SORT_REQUIRED;
			}

			ColumnReference cr = (ColumnReference) expr;

			/*
			** Check whether the table referred to is in the table map (if any).
			** If it isn't, we may have an ordering that does not require
			** sorting for the tables in a partial join order.  Look for
			** columns beyond this column to see whether a referenced table
			** is found - if so, sorting is required (for example, in a
			** case like ORDER BY S.A, T.B, S.C, sorting is required).
			*/
			if (tableMap != null)
			{
				if ( ! tableMap.get(cr.getTableNumber()))
				{
					/* Table not in partial join order */
					for (int remainingPosition = loc + 1;
						 remainingPosition < size();
						 remainingPosition++)
					{
					     //GemStone changes BEGIN
						OrderedColumn remainingobc = getOrderedColumn(loc);
	                                             //GemStone changes END
						ResultColumn remainingrc =
												remainingobc.getResultColumn();

						ValueNode remainingexpr = remainingrc.getExpression();

						if (remainingexpr instanceof ColumnReference)
						{
							ColumnReference remainingcr =
											(ColumnReference) remainingexpr;
							if (tableMap.get(remainingcr.getTableNumber()))
							{
								return RequiredRowOrdering.SORT_REQUIRED;
							}
						}
					}

					return RequiredRowOrdering.NOTHING_REQUIRED;
				}
			}

			if ( ! rowOrdering.alwaysOrdered(cr.getTableNumber()))
			{
				/*
				** Check whether the ordering is ordered on this column in
				** this position.
				*/
				if ( ! rowOrdering.orderedOnColumn(
			  		obc.isAscending() ?
								RowOrdering.ASCENDING : RowOrdering.DESCENDING,
			  		position,
			  		cr.getTableNumber(),
			  		cr.getColumnNumber()
			  		))
				{
					return RequiredRowOrdering.SORT_REQUIRED;
				}

				/*
				** The position to ask about is for the columns in tables
				** that are *not* always ordered.  The always-ordered tables
				** are not counted as part of the list of ordered columns
				*/
				position++;
			}
		}

		return RequiredRowOrdering.NOTHING_REQUIRED;
	}

	/**
	 * @see RequiredRowOrdering#estimateCost
	 *
	 * @exception StandardException		Thrown on error
	 */
	public void estimateCost(double estimatedInputRows,
								RowOrdering rowOrdering,
								CostEstimate resultCost)
					throws StandardException
	{
		/*
		** Do a bunch of set-up the first time: get the SortCostController,
		** the template row, the ColumnOrdering array, and the estimated
		** row size.
		*/
		if (scc == null)
		{
			scc = getCompilerContext().getSortCostController();

			resultRow =
				resultToSort.getResultColumns().buildEmptyRow().getRowArray();
			columnOrdering = getColumnOrdering();
			estimatedRowSize =
						resultToSort.getResultColumns().getTotalColumnSize();
		}

		long inputRows = (long) estimatedInputRows;
		long exportRows = inputRows;
		double sortCost;

		sortCost = scc.getSortCost(
									(DataValueDescriptor[]) resultRow,
									columnOrdering,
									false,
									inputRows,
									exportRows,
									estimatedRowSize
									);

		resultCost.setCost(sortCost, estimatedInputRows, estimatedInputRows);
	}

	/** @see RequiredRowOrdering#sortNeeded */
	public void sortNeeded()
	{
		sortNeeded = true;
	}

	/** @see RequiredRowOrdering#sortNotNeeded */
	public void sortNotNeeded()
	{
		sortNeeded = false;
	}

	/**
	 * Remap all ColumnReferences in this tree to be clones of the
	 * underlying expression.
	 *
	 * @exception StandardException		Thrown on error
	 */
	void remapColumnReferencesToExpressions() throws StandardException
	{
	}

	/**
	 * Get whether or not a sort is needed.
	 *
	 * @return Whether or not a sort is needed.
	 */
	public boolean getSortNeeded()
	{
		return sortNeeded;
	}

	/**
	 * Determine whether or not this RequiredRowOrdering has a
	 * DESCENDING requirement for the column referenced by the
	 * received ColumnReference.
	 */
	boolean requiresDescending(ColumnReference cRef, int numOptimizables)
		throws StandardException
	{
		int size = size();

		/* Start by getting the table number and column position for
		 * the table to which the ColumnReference points.
		 */
		JBitSet tNum = new JBitSet(numOptimizables);
		BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(tNum);

		cRef.accept(btnVis);
		int crTableNumber = tNum.getFirstSetBit();
		int crColPosition = btnVis.getColumnNumber();

		if (SanityManager.DEBUG)
		{
			/* We assume that we only ever get here if the column
			 * reference points to a specific column in a specific
			 * table...
			 */
			if ((crTableNumber < 0) || (crColPosition < 0))
			{
				SanityManager.THROWASSERT(
					"Failed to find table/column number for column '" +
					cRef.getColumnName() + "' when checking for an " +
					"ORDER BY requirement.");
			}

			/* Since we started with a single ColumnReference there
			 * should be exactly one table number.
			 */
			if (!tNum.hasSingleBitSet())
			{
				SanityManager.THROWASSERT(
					"Expected ColumnReference '" + cRef.getColumnName() +
					"' to reference exactly one table, but tables found " +
					"were: " + tNum);
			}
		}

		/* Walk through the various ORDER BY elements to see if
		 * any of them point to the same table and column that
		 * we found above.
		 */
		for (int loc = 0; loc < size; loc++)
		{
		  //GemStone changes BEGIN
			OrderedColumn obc = getOrderedColumn(loc);
		               //GemStone changes END
			ResultColumn rcOrderBy = obc.getResultColumn();

			btnVis.reset();
			rcOrderBy.accept(btnVis);
			int obTableNumber = tNum.getFirstSetBit();
			int obColPosition = btnVis.getColumnNumber();

			/* ORDER BY target should always have a table number and
			 * a column position.  It may not necessarily be a base
			 * table, but there should be some FromTable for which
			 * we have a ResultColumnList, and the ORDER BY should
			 * reference one of the columns in that list (otherwise
			 * we shouldn't have made it this far).
			 */
			if (SanityManager.DEBUG)
			{
				/* Since we started with a single ResultColumn there
				 * should exactly one table number.
				 */
				if (!tNum.hasSingleBitSet())
				{
					SanityManager.THROWASSERT("Expected ResultColumn '" +
						rcOrderBy.getColumnName() + "' to reference " +
						"exactly one table, but found: " + tNum);
				}

				if (obColPosition < 0)
				{
					SanityManager.THROWASSERT(
						"Failed to find orderBy column number " +
						"for ORDER BY check on column '" +
						cRef.getColumnName() + "'.");
				}
			}

			if (crTableNumber != obTableNumber)
				continue;

			/* They point to the same base table, so check the
			 * column positions.
			 */

			if (crColPosition == obColPosition)
			{
				/* This ORDER BY element points to the same table
				 * and column as the received ColumnReference.  So
				 * return whether or not this ORDER BY element is
				 * descending.
				 */
				return !obc.isAscending();
			}
		}

		/* None of the ORDER BY elements referenced the same table
		 * and column as the received ColumnReference, so there
		 * is no descending requirement for the ColumnReference's
		 * source (at least not from this OrderByList).
		 */
		return false;
	}

	/**
	 * Adjust the OrderByList after removal of window function columns.
	 *
	 * @exception StandardException		Thrown on error
	 */
	public void adjustForWindowFunctionColumns()
		throws StandardException
	{
		/*
		 * Recreate the template due to removal of window function columns
		 * in the resultToSort RCL.
		 */
		resultRow =
				resultToSort.getResultColumns().buildEmptyRow().getRowArray();
		/*
		 * Adjust the VirtualColumnIds OrderByColumns to the updated RCL.
		 */
		for (int index = 0; index < size(); index++)
		{
			OrderByColumn obc = (OrderByColumn) elementAt(index);
			obc.bindOrderByColumn(resultToSort, this);
		}
		/*
		 * Update the columOrdering
		 *
		 * TODO - is this really necessary?
		 */
		columnOrdering = getColumnOrdering();
	}

// GemStone changes BEGIN
	/**
	 * This function determines if distinctAndOrderBy
	 * can be merged. OrderBy is bound by Projection
	 * columns and Projection is bound by Group By
	 * columns but order by can have expression constituting
	 * grouping columns that may not be part of projection.
	 *
	 * e.g. select d+q from t group by q,d order by q+d
	 * e.g. select distinct d+q from t order by q*d
	 *
	 * So, we treat expression as a black box and only
	 * ColumnReferences in order by are allowed to be
	 * merged with distinct select.
	 *
	 * @returns true - indicating order by columns and distinct
	 *  columns can be merged.
	 *
	 */
	public boolean isDistinctOrderable() {
	  // first check if there is any NULLS FIRST specification
	  if (hasNullsOrderedLow()) {
	    return false;
	  }
	  boolean isExpr = false;
	  for(int i = 0, size = size(); i < size && !isExpr ; i++) {

	    OrderByColumn obc = (OrderByColumn) elementAt(i);
	    ValueNode expr = obc.getResultColumn().getExpression();

	    isExpr = (expr instanceof ColumnReference
	           || expr instanceof VirtualColumnNode );
	  }

	  return isExpr;
	}

	/** Returns true if there is an order by with nulls ordered low */
	public final boolean hasNullsOrderedLow() {
	  final int size = size();
	  for (int loc = 0; loc < size; loc++) {
	    OrderedColumn obc = getOrderedColumn(loc);
	    if (obc.isNullsOrderedLow()) {
	      return true;
	    }
	  }
	  return false;
	}

	/*
	 * @return true if any column in order by list is aggreagate
	 */
        public boolean hasAnyAgrregateInOrderByList(
            boolean isCompilationAsDataStoreNode) throws StandardException {
          boolean isAgg = false;
          CollectExpressionOperandsVisitor exprSubstitutor = new CollectExpressionOperandsVisitor(
              null, null, isCompilationAsDataStoreNode);
          for (int i = 0, size = size(); i < size && !isAgg; i++) {
            OrderByColumn obc = (OrderByColumn)elementAt(i);
            ValueNode expr = obc.getResultColumn().getExpression();
            isAgg = exprSubstitutor.visitHasAggregateVisitorOnly(expr);
          }

          return isAgg;
        }
// GemStone changes END
}


text:
/* -------------------------------------------------------------------------
// WINX: a C++ template GUI library - MOST SIMPLE BUT EFFECTIVE
//
// This file is a part of the WINX Library.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.txt at this distribution. By using
// this software in any fashion, you are agreeing to be bound by the terms
// of this license. You must not remove this notice, or any other, from
// this software.
//
// Module: std/set.h
// Creator: xushiwei
// Email: xushiweizh@gmail.com
// Date: 2006-8-18 18:56:07
//
// $Id: set.h,v 1.1 2006/10/18 12:13:39 xushiwei Exp $
// -----------------------------------------------------------------------*/
#ifndef STD_SET_H
#define STD_SET_H

#ifndef STDEXT_PLATFORM_H
#include "../stdext/Platform.h"
#endif

// -------------------------------------------------------------------------

#if defined(X_STL_SGI)
	#ifndef __SGI_STL_SET_H
	#include "../../../stl/set.h"
	#endif
#else
	#if !defined(_SET_) && !defined(_SET)
	#include <set>
	#endif
#endif

// -------------------------------------------------------------------------
// $Log: set.h,v $

#endif /* STD_SET_H */

redpajama_set_name: RedPajamaGithub


text:
Write a program that, given a word and a list of possible anagrams, selects the correct sublist.

Given `"listen"` and a list of candidates like `"enlists" "google"
"inlets" "banana"` the program should return a list containing
`"inlets"`.

### Submitting Exercises

Note that, when trying to submit an exercise, make sure you're exercise file you're submitting is in the `exercism/csharp/<exerciseName>` directory.

For example, if you're submitting `bob.cs` for the Bob exercise, the submit command would be something like `exercism submit <path_to_exercism_dir>/csharp/bob/bob.cs`.

## Source

Inspired by the Extreme Startup game [https://github.com/rchatley/extreme_startup](https://github.com/rchatley/extreme_startup)


text:
package cs543.project1.connectfour;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.UnknownHostException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;

/**
 * The object to keep track of player and AI movements as well as mouse events
 *
 * @author Natacha Gabbamonte
 * @author Gabriel Gheorghian
 * @author Mark Scerbo
 *
 */
public class C4BoardPanel extends JPanel {

	public enum GameType {
		SINGLEPLAYER, MULTIPLAYER
	}

	private static final long serialVersionUID = -4107255535013778600L;
	private int[] fullColumns = new int[7];

	private ImageIcon DEFAULT;
	private ImageIcon PLAYER_ONE;
	private ImageIcon PLAYER_TWO;
	private ImageIcon currentPlayer = null;

	private final Color DEFAULT_PANEL_BACK = new JPanel().getBackground();
	private final Color HOVER_PANEL_BACK = new Color(0xFAFAD2);
	private final Color CLICK_PANEL_BACK = HOVER_PANEL_BACK.darker().darker();

	private C4Model model;
	private C4ServerConnection connection;
	private JPanel[] columns = new JPanel[7];
	private GridBagLayout layout = new GridBagLayout();
	private JLabel[][] allLabels = new JLabel[6][7];
	@SuppressWarnings("unused")
	private String ipNumber = null;

	private boolean waitingForMove = false;

	private GameType gameType = null;
	/*
	 * The MouseAdapter that listens for clicks on the columns.
	 */
	private MouseAdapter mouseAdapter = new MouseAdapter() {
		/**
		 * This will change the color of the column as the client Hovers over
		 * the column
		 */
		public void mouseEntered(MouseEvent e) {
			JPanel panel = (JPanel) e.getSource();
			for (int i = 0; i < columns.length; i++)
				if (columns[i] == panel)
					columns[i].setBackground(HOVER_PANEL_BACK);
				else
					columns[i].setBackground(DEFAULT_PANEL_BACK);

		}

		/**
		 * This is to set all of the columns' backgrounds back to default.
		 */
		public void mouseExited(MouseEvent e) {
			for (int i = 0; i < columns.length; i++)
				columns[i].setBackground(DEFAULT_PANEL_BACK);
		}

		/**
		 * This will do all the processing of the move once a player clicks on a
		 * column (attemps to add a piece to that column).
		 */
		public void mousePressed(MouseEvent e) {
			if (waitingForMove) {
				waitingForMove = false;
				JPanel panel = (JPanel) e.getSource();
				int i = 0;
				for (i = 0; i < columns.length; i++)
					if (columns[i] == panel) {
						columns[i].setBackground(CLICK_PANEL_BACK);
						break;
					}
				if (fullColumns[i] > 0)
					try {
						model.setMessage(" ");
						connection.sendPacket(new byte[] {
								C4Messages.NORMAL_MOVE, (byte) i });
						checkForNextAction();
					} catch (IOException e1) {
						model.setMessage("An error occured with the connection with the server: "
								+ e1.getMessage());
					}
				else {
					waitingForMove = true;
					model.setMessage("You cannot add a coin to that column, it is full.");
				}
			}

		}

		/**
		 * Reverts the background of the column back to original color.
		 */
		public void mouseReleased(MouseEvent e) {
			JPanel panel = (JPanel) e.getSource();
			panel.setBackground(HOVER_PANEL_BACK);
		}
	};

	/*
	 * The KeyAdapter for the board so that the user can press 1-7 so "click" on
	 * the columns.
	 */
	private KeyAdapter keyAdapter = new KeyAdapter() {

		/**
		 * Will generate a MouseEvent if a number from 1-7 was pressed.
		 */
		@Override
		public void keyPressed(KeyEvent e) {
			char key = e.getKeyChar();
			int col = -1;
			switch (key) {
			case '1':
				col = 0;
				break;
			case '2':
				col = 1;
				break;
			case '3':
				col = 2;
				break;
			case '4':
				col = 3;
				break;
			case '5':
				col = 4;
				break;
			case '6':
				col = 5;
				break;
			case '7':
				col = 6;
				break;
			}
			if (col != -1) {
				columns[col].dispatchEvent(new MouseEvent(columns[col],
						MouseEvent.MOUSE_PRESSED, 0, 0, 0, 0, 1, false,
						MouseEvent.BUTTON1));
				columns[col].dispatchEvent(new MouseEvent(columns[col],
						MouseEvent.MOUSE_EXITED, 0, 0, 0, 0, 1, false,
						MouseEvent.BUTTON1));
			}
		}
	};

	/**
	 * Constructor: Creates the C4BoardPanel Object
	 *
	 * @param model
	 *            :handle to the model
	 * @param ipNumber
	 *            :ip of the server connecting to
	 * @throws UnknownHostException
	 *             If the host that was entered is invalid.
	 * @throws IOException
	 *             If an error occurs with the connection.
	 */
	public C4BoardPanel(C4Model model, String ipNumber)
			throws UnknownHostException, IOException {
		super();
		gameType = GameType.SINGLEPLAYER;
		this.addKeyListener(keyAdapter);
		DEFAULT = new ImageIcon(
				C4GuiApp.class.getResource("images/default.png"));
		PLAYER_ONE = new ImageIcon(
				C4GuiApp.class.getResource("images/green_coin.png"));
		PLAYER_TWO = new ImageIcon(
				C4GuiApp.class.getResource("images/red_coin.png"));
		this.model = model;
		this.setLayout(layout);
		for (int i = 0; i < fullColumns.length; i++)
			fullColumns[i] = 6;
		populatePanel();
		this.ipNumber = ipNumber;
		connection = new C4ServerConnection(ipNumber);
		model.resetGameIsOver();
		requestFocusForPanel();
		checkForNextAction();
	}

	/**
	 * Requests the focus to be on this panel.
	 */
	public void requestFocusForPanel() {
		this.requestFocusInWindow();
	}

	/**
	 * This lets server know the client forfeits.
	 *
	 * @throws IOException
	 *             If an error occurs with the connection.
	 */
	public void forfeit(GameType gameType) throws IOException {
		if (this.gameType != gameType) {
			model.setNextIsNewGame(true);
			if (gameType == GameType.SINGLEPLAYER)
				model.setGameOverMessage(2);
			else
				model.setGameOverMessage(1);
		}

		this.gameType = gameType;
		connection.sendPacket(new byte[] { C4Messages.FORFEIT,
				C4Messages.GARBAGE });
		checkForNextAction();
	}

	/**
	 * This populates the panel with all the inner grid bags (one per column)
	 * and all the labels contained by said gridbags.
	 */
	private void populatePanel() {
		Border border = BorderFactory.createLineBorder(Color.BLACK);
		for (int i = 0; i < columns.length; i++) {
			columns[i] = new JPanel();
			columns[i].setLayout(new GridBagLayout());
			columns[i].setPreferredSize(new Dimension(50, 300));
			for (int x = 0; x < 6; x++) {
				JLabel label = new JLabel();
				label.setBorder(border);
				label.setHorizontalAlignment(JLabel.CENTER);
				// label.setOpaque(true);
				label.setIcon(DEFAULT);
				label.setMinimumSize(new Dimension(50, 50));
				allLabels[x][i] = label;
				columns[i].add(label, makeConstraints(0, x, 1, 1));
			}

			// Adding the board
			this.add(columns[i], makeConstraints(i, 0, 1, 6));
			columns[i].addMouseListener(mouseAdapter);
		}
	}

	/**
	 * Sets constraints based on the values sent in.
	 *
	 * @param gridx
	 *            x coordinates
	 * @param gridy
	 *            y coordinates
	 * @param gridwidth
	 *            number of columns to go across
	 * @param gridheight
	 *            number of rows to go across
	 * @return constraints (the constraints to be added to a component
	 */
	private GridBagConstraints makeConstraints(int gridx, int gridy,
			int gridwidth, int gridheight) {
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.gridheight = gridheight;
		constraints.gridwidth = gridwidth;
		constraints.gridx = gridx;
		constraints.gridy = gridy;

		// Default for all the components.
		constraints.insets = new Insets(1, 1, 1, 1);
		constraints.weightx = 1.0;
		constraints.weighty = 1.0;
		constraints.fill = GridBagConstraints.BOTH;
		return constraints;
	}

	/**
	 * this displays message and process based on who's move it is and what may
	 * be going on at the moment
	 *
	 * @throws IOException
	 *             If an error occurs with the connection.
	 */
	private void checkForNextAction() throws IOException {
		byte[] messages = connection.receivePacket();

		switch (messages[0]) {
		case C4Messages.WHAT_TYPE:
			switch (gameType) {
			case MULTIPLAYER:
				connection.sendPacket(new byte[] { C4Messages.GAME_TYPE,
						C4Messages.MULTIPLAYER });
				break;
			case SINGLEPLAYER:
				connection.sendPacket(new byte[] { C4Messages.GAME_TYPE,
						C4Messages.SINGLEPLAYER });
				break;
			}
			checkForNextAction();
			break;
		case C4Messages.PLAYER_ONE_PLAY:
			currentPlayer = PLAYER_ONE;
			model.setMessage("Player One's turn.");
			waitingForMove = true;
			break;
		case C4Messages.PLAYER_TWO_PLAY:
			currentPlayer = PLAYER_TWO;
			if (gameType == GameType.SINGLEPLAYER) {
				updateBoard(messages[1], currentPlayer);
				model.setMessage(" ");
				checkForNextAction();
			} else {
				model.setMessage("Player Two's turn.");
				waitingForMove = true;
			}
			break;
		case C4Messages.ERROR_WITH_PLAY:
			model.setMessage("You cannot add a coin to that column, it is full.");
			checkForNextAction();
			break;
		case C4Messages.PLAY_IS_GOOD:
			updateBoard(messages[1], currentPlayer);
			model.setMessage(" ");
			checkForNextAction();
			break;
		case C4Messages.GAME_OVER:
			String gameOverMessage = "Game Over! ";
			switch (messages[1]) {
			case C4Messages.PLAYER_ONE_WON:
				gameOverMessage += "PLAYER ONE WON!";
				model.addWin();
				model.setWinner(1);
				break;
			case C4Messages.PLAYER_TWO_WON:
				gameOverMessage += "PLAYER TWO WON!";
				model.addLoss();
				model.setWinner(2);
				break;
			case C4Messages.DRAW:
				gameOverMessage += "IT'S A DRAW!";
				model.addDraw();
				model.setWinner(0);
				break;
			}
			model.setMessage(gameOverMessage);
			model.gameIsOver();
			break;
		}
	}

	/**
	 * This updates the board and places the image based on the player playing.
	 *
	 * @param column
	 *            :column the move was done in
	 * @param player
	 *            :player making move
	 */
	private void updateBoard(byte column, ImageIcon player) {
		allLabels[fullColumns[column] - 1][column].setIcon(player);
		fullColumns[column]--;
	}

	/**
	 * This is used to reset the board to original settings
	 */
	private void resetValues() throws IOException {
		for (int x = 0; x < allLabels.length; x++)
			for (int y = 0; y < allLabels[0].length; y++)
				allLabels[x][y].setIcon(DEFAULT);
		for (int i = 0; i < fullColumns.length; i++)
			fullColumns[i] = 6;
	}

	/**
	 * This will inform the server that the player wishes to play again.
	 *
	 * @throws IOException
	 *             If an error occurs with the connection.
	 */
	public void playerWantsToPlayAgain() throws IOException {
		connection.sendPacket(new byte[] { C4Messages.PLAY_AGAIN,
				C4Messages.GARBAGE });
		model.resetGameIsOver();

		checkForNextAction();
		resetValues();
		model.setMessage(" ");
		requestFocusForPanel();
	}

	/**
	 * This lets server know player is done playing C4.
	 *
	 * @throws IOException
	 *             If an error occurs with the connection.
	 */
	public void playerDoesntWantToPlayAgain() throws IOException {
		connection.sendPacket(new byte[] { C4Messages.NOT_PLAY_AGAIN,
				C4Messages.GARBAGE });
		connection.closeConnection();
	}

}


text:
package brandy.mark.model;

import java.util.List;

/**
 * Created by lenovo on 2016/12/1.
 */
public class AllMovieListData {
    private String name;
    private String img_url;
    private List<SingleMovieListData> cat;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImg_url() {
        return img_url;
    }

    public void setImg_url(String img_url) {
        this.img_url = img_url;
    }

    public List<SingleMovieListData> getCat() {
        return cat;
    }

    public void setCat(List<SingleMovieListData> cat) {
        this.cat = cat;
    }
}


text:
namespace Google.Cloud.Billing.V1.Snippets
{
    // [START cloudbilling_v1_generated_CloudBilling_ListBillingAccounts_sync]
    using Google.Api.Gax;
    using Google.Cloud.Billing.V1;
    using System;

    public sealed partial class GeneratedCloudBillingClientSnippets
    {
        /// <summary>Snippet for ListBillingAccounts</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListBillingAccountsRequestObject()
        {
            // Create client
            CloudBillingClient cloudBillingClient = CloudBillingClient.Create();
            // Initialize request argument(s)
            ListBillingAccountsRequest request = new ListBillingAccountsRequest { Filter = "", };
            // Make the request
            PagedEnumerable<ListBillingAccountsResponse, BillingAccount> response = cloudBillingClient.ListBillingAccounts(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (BillingAccount item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListBillingAccountsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (BillingAccount item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<BillingAccount> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (BillingAccount item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END cloudbilling_v1_generated_CloudBilling_ListBillingAccounts_sync]
}


text:
package ml.alternet.facet;

import java.util.Optional;

import ml.alternet.misc.Position;

/**
 * A trackable object can supply informations about its position (within an
 * input stream).
 *
 * @author Philippe Poulard
 */
public interface Trackable {

    /**
     * When available, return the given position.
     *
     * @return The current position.
     *
     * @see Position#$(long, long, long)
     */
    Optional<Position> getPosition();

}


text:
package com.tle.web.api.item.tasks.interfaces;

import com.tle.common.interfaces.CsvList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("task")
@Api(value = "Task searching", description = "task")
@Produces(MediaType.APPLICATION_JSON)
@SuppressWarnings("nls")
public interface TaskResource {
  static final String DEFAULT_FILTER = "all";

  @GET
  @Path("/")
  @ApiOperation(value = "Search tasks")
  public Response tasksSearch(
      // @formatter:off
      @Context UriInfo uriInfo,
      @ApiParam(
              value = "The filtering to apply to the task list",
              allowableValues = "all,assignedme,assignedothers,assignednone,mustmoderate",
              required = false,
              defaultValue = DEFAULT_FILTER)
          @QueryParam("filter")
          String filtering,
      @ApiParam(value = "Query string", required = false) @QueryParam("q") String q,
      @ApiParam(
              value = "The first record of the search results to return",
              required = false,
              defaultValue = "0")
          @QueryParam("start")
          int start,
      @ApiParam(
              value = "The number of results to return",
              required = false,
              defaultValue = "10",
              allowableValues = "range[1,100]")
          @QueryParam("length")
          int length,
      @ApiParam(value = "List of collections", required = false) @QueryParam("collections")
          CsvList collections,
      @ApiParam(
              value = "The order of the search results",
              allowableValues = "priority,duedate,waiting, name",
              required = false)
          @QueryParam("order")
          String order,
      @ApiParam(
              value = "Reverse the order of the search results",
              allowableValues = ",true,false",
              defaultValue = "false",
              required = false)
          @QueryParam("reverse")
          String reverse);
  // @formatter:on
}


text:
module Admin::UsersHelper
  def user_timeline_data(user)
    data = [{
      start: user.created_at,
      content: "Joined the game"
    }]
    user.scores.each do |score|
      data << {
        start: score.created_at,
        content: score.task ? "Completed #{score.task.name} for #{score.points} points" : "Admin assigned #{score.points} points"
      }
    end
    data
  end
end


text:
var EntityLayoutView;
(function ($, _, Backbone, Marionette, entityListLayoutTpl, EntityLayoutModel, PagerBehavior, FilterFormView) {
    EntityLayoutView = Marionette.EntityLayoutView = Marionette.View.extend({
        template: entityListLayoutTpl,
        regions: {
            'entityRegion': {
                el: '.entityRegion',
                replaceElement: true
            },
            'pagerRegion': {
                el: '.pagerRegion',
                replaceElement: true
            },
            'pageSizeRegion': {
                el: '.page-size-region',
                replaceElement: true
            },
            'filterRegion': {
                el: '.filter-region',
                replaceElement: true
            }
        },
        behaviors: {
            Pager: {
                behaviorClass: PagerBehavior
            }
        },
        constructor: function (options) {
            _.extend(this, options);

            Marionette.View.prototype.constructor.apply(this, arguments);

            this.listView.allowableOperations = this.allowableOperations;
            this.listView.route = this.route;
            this.listView.parentViewCid = this.cid;

            this._channel = Backbone.Radio.channel(this.route);
            Marionette.bindEvents(this, this._channel, this.radioEvents);

            this.on('render', this.runRenderers, this);
            this.on('dom:refresh', this.runInitializers, this);
        },
        className: function () {
            var entityLayoutClass = ' entity-layout';
            if (this.getOption('embedded')) {
                entityLayoutClass = ' entity-layout-nested';
            }

            return 'entity-layout-view-' + this.cid + entityLayoutClass;
        },
        model: EntityLayoutModel,
        radioEvents: {
            'view.list.activated': 'listViewActivated',
            'view.form.activated': 'formViewActivated'
        },
        events: {
            'click .edit': 'editClick',
            'click .multi-action': 'showMultiActions'
        },
        childViewEvents: function () {
            var events = {};
            if (this.getOption('embedded')) {
                events['modal:delete-all-modal-embedded:yes'] = 'deleteAllYes';
                events['modal:delete-item-modal-embedded:yes'] = 'deleteItemYes';
            } else {
                events['modal:delete-all-modal:yes'] = 'deleteAllYes';
                events['modal:delete-item-modal:yes'] = 'deleteItemYes';
            }

            return events;
        },
        ui: {
            '$subNav': '.sub-nav',
            '$filters': '.filterEntities',
            '$multiActionRequests': '.multi-action-requests',
            '$treeBtn': '.get-tree',
            '$header': '.entity-header',
            '$actions': '.actions',
            '$filterForm': '.filter-form'
        },
        templateContext: function () {
            var route = this.route,
                btnClass = this.btnClass;

            return {
                route: route,
                btnClass: btnClass,
                embedded: this.getOption('embedded')
            };
        },
        createClick: function (e) {
            e.preventDefault();
            e.stopPropagation();

            if (!this.routing) {
                this._channel.trigger('create');
            } else {
                App.router.transitionTo(this.route + '.create');
            }
        },
        runInitializers: function () {
            this.showMultiActions();
        },
        runRenderers: function () {
            this.renderHeader();
            this.renderFilters();
            this.renderModals();
            this.renderActions();

            if (this.getOption('embedded')) {
                this.ui.$filterForm.addClass('form-inline');
            }

            this.bindUIElements();
        },
        renderModals: function () {
            var embedded = this.getOption('embedded') ? 'Embedded' : '';
            this.modal('deleteAllModal' + embedded)
                .message('Are you sure you want to delete these items?')
                .title('Delete All?')
                .choice('Yes', 'yes')
                .choice('No', 'no', true)
                .add();

            this.modal('deleteItemModal' + embedded)
                .message('Are you sure you want to delete this item?')
                .title('Delete Item?')
                .choice('Yes', 'yes')
                .choice('No', 'no', true)
                .add();
        },
        renderActions: function () {
            var embedded = this.getOption('embedded') ? 'Embedded' : '',
                btnClass = embedded !== '' ? 'btn-sm ' : 'btn ';

            this.action('getAll')
                .text('All')
                .className(btnClass + 'btn-outline-primary')
                .callBack(this.getAllClick)
                .add(true);

            this.action('create', false)
                .text('Create')
                .className(btnClass + 'btn-outline-secondary')
                .callBack(this.createClick)
                .add();

            this.action('deleteAll', true)
                .text('Delete All')
                .className(btnClass + 'btn-outline-danger')
                .withModal('deleteAllModal' + embedded)
                .add();
        },
        renderFilters: function () {
            var FiltersView = FilterFormView.extend({
                events: {
                    'keyup .name': 'filterByName'
                },
                onRender: function () {
                    this.field('name')
                        .label('Filter By Name', true)
                        .singleLine('Filter By Name');
                },
                filterByName: function (e) {
                    var $target = $(e.target),
                        name = $target.val(),
                        channel = this.getOption('channel');

                    _.debounce(_.bind(function () {
                        if (name.length === 0) {
                            channel.trigger('getAll', 1);
                            return;
                        }

                        channel.trigger('textSearch', name, 'name');
                    }, this), 400)();
                }
            });

            this.showChildView('filterRegion', new FiltersView({channel: this._channel}));
        },
        listViewActivated: function () {
            this.ui.$filters.show();
            this.showMultiActions();
        },
        formViewActivated: function () {
            this.ui.$filters.hide();
        },
        deleteAllYes: function (view, e) {
            var itemsSelected = this.$el.find('.multi-action:checked'),
                ids = [],
                fullCollection = this.listView.collection;

            _.each(itemsSelected, function (item) {
                ids.push($(item).data('id'));
            });

            fullCollection.deleteByIds(ids)
                .done(function () {
                    view.$el.modal('hide');
                });
        },
        deleteItemYes: function (view, e) {
            var data = view.modalData;
            this._channel.trigger('delete', data.id);
            view.$el.modal('hide');
        },
        showMultiActions: function (e) {
            if (e) {
                e.stopPropagation();
            }

            var itemsSelected = this.$el.find('.multi-action:checked');
            if (itemsSelected.length > 0) {
                this.ui.$multiActionRequests.show();
            } else {
                this.ui.$multiActionRequests.hide();
            }
        },
        renderHeader: function () {
            if (_.isUndefined(this.header)) {
                return;
            }

            var html = this.header.template(this.header.params);
            this.ui.$header.append(html);
        },
        action: function (name, isMultiAction) {
            var options = {},
                returnObj = {};

            options.name = name;
            options.isMultiAction = isMultiAction;
            options.withModal = false;
            options.safeName = this._formatRegionName(options.name);

            var text = function (text) {
                options.text = text;
                return returnObj;
            };

            var className = function (className) {
                options.className = className;
                return returnObj;
            };

            var callBack = function (callBack) {
                options.callBack = callBack;
                return returnObj;
            };

            var template = function (template) {
                options.template = template;
            };

            var withModal = _.bind(function (modalName) {
                var modalSafeName = this._formatRegionName(modalName);
                options.withModal = true;
                options.template = _.template('<button  data-toggle="modal" data-target="#' + modalSafeName + '" type="button" class="<%= safeName %> ' +
                    '<% if(isMultiAction) { %> multi-action-requests <% } %>' +
                    ' <%= className %>">' +
                    '<%= text %>' +
                    '</button>');

                return returnObj;
            }, this);

            var add = _.bind(function (forceShow) {
                if (this.allowableOperations.indexOf(options.safeName) === -1 && !forceShow) {
                    return;
                }

                var template = null;
                if (!_.isUndefined(options.template)) {
                    template = options.template;
                } else {
                    template = _.template('<button type="button" class="<%= safeName %> <% if(isMultiAction) { %> multi-action-requests <% } %>' +
                        ' <%= className %>">' +
                        '<%= text %>' +
                        '</button>');
                }

                var html = template(options);
                this.ui.$actions.append(html);

                if (!_.isUndefined(options.callBack) && !options.withModal) {
                    var $el = this.ui.$actions.find('.' + options.safeName);
                    $el.on('click', _.bind(function (e) {
                        e.preventDefault();
                        e.stopPropagation();

                        _.bind(options.callBack, this)(e)
                    }, this));
                    this.on('destroy', function () {
                        $el.off('click');
                    });
                }
            }, this);

            returnObj = _.extend(returnObj, {
                text: text,
                className: className,
                callBack: callBack,
                template: template,
                withModal: withModal,
                add: add
            });

            return returnObj;
        },
        getAllClick: function (e) {
            var page = 1;
            if (!_.isUndefined(this.listView.currentPage) && this.listView.currentPage !== 0) {
                page = this.listView.currentPage;
            }

            var route = this.route + '/' + page + '/';
            if (!this.routing) {
                this._channel.trigger('getAll', page);
            } else {
                location.hash = route;
            }
        },
        getChannel: function () {
            return this._channel;
        }
    });
})(jQuery, _, Backbone, Marionette, this['Templates']['entityLayoutTemplate'], EntityLayoutModel, PagerBehavior, FilterFormView);


text:
package de.sourcestream.movieDB.controller;

import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

import de.sourcestream.movieDB.MainActivity;
import de.sourcestream.movieDB.R;
import de.sourcestream.movieDB.adapter.GalleryPreviewSlideAdapter;

/**
 * This fragment creates our ViewPager and holds GalleryPreviewDetail for each image loaded.
 */
public class GalleryPreviewSlide extends Fragment {
    private MainActivity activity;
    private ArrayList<String> galleryList;
    private View rootView;
    private int mUIFlag = View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;

    /**
     * Called to have the fragment instantiate its user interface view.
     *
     * @param inflater           sets the layout for the current view.
     * @param container          the container which holds the current view.
     * @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given here.
     *                           Return the View for the fragment's UI, or null.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        rootView = inflater.inflate(R.layout.gallerypreview, container, false);
        activity = ((MainActivity) getActivity());
        if (this.getArguments() != null)
            galleryList = this.getArguments().getStringArrayList("galleryList");
        return rootView;
    }

    /**
     * Called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle) has returned,
     * but before any saved state has been restored in to the view.
     *
     * @param view               The View returned by onCreateView(LayoutInflater, ViewGroup, Bundle).
     * @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given here.
     */
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Get the ViewPager and set it's PagerAdapter so that it can display items
        GalleryPreviewSlideAdapter galleryPreviewSlideAdapter = new GalleryPreviewSlideAdapter(getFragmentManager(), getResources(), galleryList);
        ViewPager mViewPager = (ViewPager) rootView.findViewById(R.id.galleryPager);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(galleryPreviewSlideAdapter);
        if (this.getArguments() != null)
            mViewPager.setCurrentItem(this.getArguments().getInt("currPos"));

    }

    /**
     * @param savedInstanceState if the fragment is being re-created from a previous saved state, this is the state.
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (activity.getSupportActionBar() != null)
            activity.getSupportActionBar().hide();
        if (Build.VERSION.SDK_INT >= 19) {
            mUIFlag ^= View.SYSTEM_UI_FLAG_IMMERSIVE;
        }
        activity.getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(activity, R.color.black));
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            activity.getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
        else
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
    }

}


text:
NS_ASSUME_NONNULL_BEGIN

@implementation NSString (DD_Char)
- (const char *)dd_getChar {
    return [self UTF8String];
}

+ (NSString *)dd_getString:(const char *)cStr {
    return [NSString stringWithCString:cStr encoding:NSUTF8StringEncoding];
}
@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>Welcome to Jekyll!</title>
  <meta name="description" content="Tech junkie • Security enthousiast • Computer Science @ VUBrussels">
  <meta name="author" content="Vincent De Schutter">
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="Vincent De Schutter">
  <meta name="twitter:description" content="Tech junkie • Security enthousiast • Computer Science @ VUBrussels">

  <meta property="og:type" content="article">
  <meta property="og:title" content="Vincent De Schutter">
  <meta property="og:description" content="Tech junkie • Security enthousiast • Computer Science @ VUBrussels">

  <link rel="apple-touch-icon" sizes="57x57" href="/images/favicons/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/images/favicons/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/images/favicons/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/images/favicons/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/images/favicons/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/images/favicons/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/images/favicons/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/images/favicons/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicons/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-194x194.png" sizes="194x194">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="/images/favicons/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="/images/favicons/manifest.json">
  <link rel="shortcut icon" href="/images/favicons/favicon.ico">
  <meta name="msapplication-TileColor" content="#ffc40d">
  <meta name="msapplication-TileImage" content="/images/favicons/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://localhost:4000//welcome-to-jekyll/">
  <link rel="alternate" type="application/rss+xml" title="Vincent De Schutter" href="/feed.xml">

Vincent De Schutter

Tech junkie • Security enthousiast • Computer Science @ VUBrussels

Blog

                  Twitter

                  Facebook

                  LinkedIn

                  GitHub

                  Email

                RSS

      <time datetime="8 Jan 2016" class="post-meta__date date">8 Jan 2016</time> • on jekyll

Welcome to Jekyll!

You'll find this post in your _posts directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run jekyll serve --watch, which launches a web server and auto-regenerates your site when a file is updated.

To add new posts, simply add a file in the _posts directory that follows the convention YYYY-MM-DD-name-of-post.ext and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.

Jekyll also offers powerful support for code snippets:

def print_hi(name)
  puts "Hi, #{name}"
end
print_hi('Tom')
#=> prints 'Hi, Tom' to STDOUT.

Check out the Jekyll docs for more info on how to get the most out of Jekyll. File all bugs/feature requests at Jekyll's GitHub repo. If you have questions, you can ask them on Jekyll's dedicated Help repository.

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus

  © 2016 Vincent De Schutter. All rights reserved.


text:
<?php

namespace Oro\Bundle\ActivityListBundle\EventListener;

use Oro\Bundle\ActivityBundle\Manager\ActivityManager;
use Oro\Bundle\ActivityListBundle\Model\MergeModes;
use Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider;
use Oro\Bundle\EntityMergeBundle\Event\EntityMetadataEvent;
use Oro\Bundle\EntityMergeBundle\Metadata\EntityMetadata;
use Oro\Bundle\EntityMergeBundle\Metadata\FieldMetadata;
use Symfony\Contracts\Translation\TranslatorInterface;

class MergeListener
{
    const TRANSLATE_KEY = 'label';

    /** @var TranslatorInterface */
    protected $translator;

    /** @var ConfigProvider */
    protected $configProvider;

    /** @var ActivityManager */
    protected $activityManager;

    /**
     * @param TranslatorInterface $translator
     * @param ConfigProvider $configProvider
     * @param ActivityManager $activityManager
     */
    public function __construct(
        TranslatorInterface $translator,
        ConfigProvider $configProvider,
        ActivityManager $activityManager
    ) {
        $this->translator = $translator;
        $this->configProvider = $configProvider;
        $this->activityManager = $activityManager;
    }

    /**
     * @param EntityMetadataEvent $event
     */
    public function onBuildMetadata(EntityMetadataEvent $event)
    {
        $entityMetadata = $event->getEntityMetadata();
        $types = $this->getAvailableActivityTypes($entityMetadata);

        foreach ($types as $type) {
            $fieldMetadataOptions = [
                'display'       => true,
                'activity'      => true,
                'type'          => $type,
                'field_name'    => $this->getFieldNameByActivityClassName($type),
                'template'      => 'OroActivityListBundle:Merge:value.html.twig',
                'is_collection' => true,
                'label'         => $this->translator->trans(
                    'oro.activity.merge.label',
                    ['%activity%' => $this->translator->trans($this->getAliasByActivityClass($type))]
                ),
                'merge_modes'   => [MergeModes::ACTIVITY_UNITE, MergeModes::ACTIVITY_REPLACE]
            ];

            $fieldMetadata = new FieldMetadata($fieldMetadataOptions);
            $entityMetadata->addFieldMetadata($fieldMetadata);
        }
    }

    /**
     * @param EntityMetadata $entityMetadata
     *
     * @return array
     */
    protected function getAvailableActivityTypes(EntityMetadata $entityMetadata)
    {
        $className = $entityMetadata->getClassName();
        $types = $this->activityManager->getActivities($className);

        return array_keys($types);
    }

    /**
     * @param string $className
     *
     * @return string
     */
    protected function getFieldNameByActivityClassName($className)
    {
        return strtolower(str_replace('\\', '_', $className));
    }

    /**
     * @param string $className
     *
     * @return string
     */
    protected function getAliasByActivityClass($className)
    {
        $config = $this->configProvider->getConfig($className);

        return $config->get(self::TRANSLATE_KEY);
    }
}


text:
Access Distinct Clusters
-------

## ServiceCenter Aggregate Architecture

In the [`Multiple Datacenters`](/docs/multidcs.md) article, we introduce
the aggregation architecture of service center. In fact, this aggregation
architecture of service center can be applied not only to the scene deployed
in multiple datacenters, but also to the scene services data aggregation in
multiple kubernetes clusters.

![architecture](/docs/kubeclusters.PNG)

The service centers deployed in distinct kubernetes clusters can communicate
with each other, sync the services data from other kubernetes clusters.
Applications can discover services from different the kubernetes cluster through
using the service center HTTP API.
**It solve the problem of isolation between kubernetes clusters**.

## Quick Start

Let's assume you want to install 2 clusters of Service-Center in different Kubernetes clusters with following details.

| Cluster | Kubernetes | namespace  | Node        |
| :-----: | :--------: | :--------: | :---------: |
| sc1     | k1         | default    | 10.12.0.1   |
| sc2     | k2         | default    | 10.12.0.2   |

To facilitate deployment, we will publish the service address of the service center in [`NodePort`] mode.

##### Deploy the Service Center

Using helm to deploy the service center to kubernetes here, the instructions for specific `values` can be referred to
[`here`](/examples/infrastructures/k8s/README.md#helm-configuration-values).

Take deployment to kubernetes cluster 1 as an example.
```bash
# login the k1 kubernetes master node to deploy sc1
git clone git@github.com:apache/servicecomb-service-center.git
cd examples/infrastructures/k8s
helm install --name k1 \
    --set sc.discovery.clusters="sc2=http://10.12.0.2:30100" \
    --set sc.discovery.aggregate="k8s\,servicecenter" \
    --set sc.registry.type="buildin" \
    --set sc.service.type=NodePort \
    service-center/
```
Notes: To deploy Service Center in kuberbetes cluster 2, you can repeat the
above steps and just change the `sc.discovery.clusters` value to
`sc1=http://10.12.0.1:30100`.

##### Confirm the service is OK

We recommend that you use [`scctl`](/scctl/README.md), and using
[`cluster command`](/scctl/pkg/plugin/README.md#cluster-options)
which makes it very convenient to verify OK.

```bash
# check the sc1 cluster api
scctl --addr http://10.12.0.3:30100 get cluster
#   CLUSTER |        ENDPOINTS
# +---------+-------------------------+
#   sc2     | http://10.12.0.2:30100

# check the sc2 cluster api
scctl --addr http://10.12.0.3:30100 get cluster
#   CLUSTER |        ENDPOINTS
# +---------+-------------------------+
#   sc1     | http://10.12.0.1:30100
```