text:
Rails.application.routes.draw do
  root 'home#index'

  # Account Devise
  devise_for :users,
    path: 'account',
    controllers: {
      registrations: "account/registrations",
      sessions: "account/sessions"
    },
    path_names: {
      sign_up: 'sign-up',
      sign_in: 'sign-in',
      sign_out: 'sign-out',
      password: 'password',
      confirmation: 'verify',
      edit: 'settings'
    }
  get '/@:username', to: 'account#show', as: 'profile'
  get '/timeline', to: 'timeline#index'
  get '/ranking', to: 'ranking#index'
  get '/FAQ', to: 'home#faq', as: 'faq'
  resources :donations
  get '/donations/:id/destroy', to: 'donations#destroy', as: 'destroy_donation'
end


text:
using System;
using System.Diagnostics;

namespace Microsoft.SPOT.Debugger
{
	//Lots of redefinitions from TinyCLR_Types.h
	public class TinyCLR_TypeSystem
	{
		public enum CLR_TABLESENUM : uint
		{
			TBL_AssemblyRef = 0x00000000,
			TBL_TypeRef = 0x00000001,
			TBL_FieldRef = 0x00000002,
			TBL_MethodRef = 0x00000003,
			TBL_TypeDef = 0x00000004,
			TBL_FieldDef = 0x00000005,
			TBL_MethodDef = 0x00000006,
			TBL_Attributes = 0x00000007,
			TBL_TypeSpec = 0x00000008,
			TBL_Resources = 0x00000009,
			TBL_ResourcesData = 0x0000000A,
			TBL_Strings = 0x0000000B,
			TBL_Signatures = 0x0000000C,
			TBL_ByteCode = 0x0000000D,
			TBL_EndOfAssembly = 0x0000000E,
			TBL_Max = 0x0000000F,
		};

		public enum CorTokenType : uint
		{
			mdtModule = 0x00000000,
			mdtTypeRef = 0x01000000,
			mdtTypeDef = 0x02000000,
			mdtFieldDef = 0x04000000,
			mdtMethodDef = 0x06000000,
			mdtParamDef = 0x08000000,
			mdtInterfaceImpl = 0x09000000,
			mdtMemberRef = 0x0a000000,
			mdtCustomAttribute = 0x0c000000,
			mdtPermission = 0x0e000000,
			mdtSignature = 0x11000000,
			mdtEvent = 0x14000000,
			mdtProperty = 0x17000000,
			mdtModuleRef = 0x1a000000,
			mdtTypeSpec = 0x1b000000,
			mdtAssembly = 0x20000000,
			mdtAssemblyRef = 0x23000000,
			mdtFile = 0x26000000,
			mdtExportedType = 0x27000000,
			mdtManifestResource = 0x28000000,
			mdtString = 0x70000000,
			mdtName = 0x71000000,
			mdtBaseType = 0x72000000,
			// Leave this on the high end value. This does not correspond to metadata table
		};

		public static uint IdxAssemblyFromIndex (uint idx)
		{
			return idx >> 16;
		}

		public static uint IdxFromIndex (uint idx)
		{
			return idx & 0xffff;
		}

		public static uint IndexFromIdxAssemblyIdx (uint idxAssm, uint idx)
		{
			return idxAssm << 16 | idx;
		}

		public static uint IndexFromIdxAssemblyIdx (uint idxAssm)
		{
			return idxAssm << 16;
		}

		public static CLR_TABLESENUM CLR_TypeFromTk (uint tk)
		{
			return (CLR_TABLESENUM)(tk >> 24);
		}

		public static uint CLR_DataFromTk (uint tk)
		{
			return  tk & 0x00FFFFFF;
		}

		public static uint CLR_TkFromType (CLR_TABLESENUM tbl, uint data)
		{
			return ((((uint)tbl) << 24) & 0xFF000000) | (data & 0x00FFFFFF);
		}

		public static CorDebugAssembly AssemblyFromIndex (CorDebugAppDomain appDomain, uint index)
		{
			return appDomain.AssemblyFromIdx (TinyCLR_TypeSystem.IdxAssemblyFromIndex (index));
		}

		public static CorDebugClass CorDebugClassFromTypeIndex (uint typeIndex, CorDebugAppDomain appDomain)
		{
			CorDebugClass cls = null;

			CorDebugAssembly assembly = appDomain.AssemblyFromIdx (TinyCLR_TypeSystem.IdxAssemblyFromIndex (typeIndex));
			if (assembly != null) {
				uint typedef = TinyCLR_TypeSystem.CLR_TkFromType (TinyCLR_TypeSystem.CLR_TABLESENUM.TBL_TypeDef, TinyCLR_TypeSystem.IdxFromIndex (typeIndex));
				cls = assembly.GetClassFromTokenTinyCLR (typedef);
			}

			return cls;
		}

		public static CorDebugFunction CorDebugFunctionFromMethodIndex (uint methodIndex, CorDebugAppDomain appDomain)
		{
			CorDebugFunction function = null;
			CorDebugAssembly assembly = appDomain.AssemblyFromIdx (TinyCLR_TypeSystem.IdxAssemblyFromIndex (methodIndex));

			if (assembly != null) {
				uint tk = TinyCLR_TypeSystem.TinyCLRTokenFromMethodIndex (methodIndex);
				function = assembly.GetFunctionFromTokenTinyCLR (tk);
			}

			return function;
		}

		public static uint ClassMemberIndexFromCLRToken (uint token, CorDebugAssembly assembly)
		{
			Pdbx.ClassMember cm = assembly.GetPdbxClassMemberFromTokenCLR (token);

			return ClassMemberIndexFromTinyCLRToken (cm.Token.TinyCLR, assembly);
		}

		public static uint ClassMemberIndexFromTinyCLRToken (uint token, CorDebugAssembly assembly)
		{
			uint idx = TinyCLR_TypeSystem.CLR_DataFromTk (token);
			return TinyCLR_TypeSystem.IndexFromIdxAssemblyIdx (assembly.Idx, idx);
		}

		private static uint TinyCLRTokenFromIndex (TinyCLR_TypeSystem.CLR_TABLESENUM tbl, uint index)
		{
			uint idxAssembly = TinyCLR_TypeSystem.IdxAssemblyFromIndex (index);
			uint idxMethod = TinyCLR_TypeSystem.IdxFromIndex (index);

			return TinyCLR_TypeSystem.CLR_TkFromType (tbl, idxMethod);
		}

		public static uint TinyCLRTokenFromMethodIndex (uint index)
		{
			return TinyCLRTokenFromIndex (TinyCLR_TypeSystem.CLR_TABLESENUM.TBL_MethodDef, index);
		}

		public static uint TinyCLRTokenFromTypeIndex (uint index)
		{
			return TinyCLRTokenFromIndex (TinyCLR_TypeSystem.CLR_TABLESENUM.TBL_TypeDef, index);
		}

		public class SymbollessSupport
		{
			public static uint MethodDefTokenFromTinyCLRToken (uint token)
			{
				Debug.Assert (CLR_TypeFromTk (token) == CLR_TABLESENUM.TBL_MethodDef);
				return (uint)CorTokenType.mdtMethodDef | CLR_DataFromTk (token);
			}

			public static uint TinyCLRTokenFromMethodDefToken (uint token)
			{
				Debug.Assert ((token & (uint)CorTokenType.mdtMethodDef) != 0);
				return TinyCLR_TypeSystem.CLR_TkFromType (CLR_TABLESENUM.TBL_MethodDef, token & 0x00ffffff);
			}

			public static uint TypeDefTokenFromTinyCLRToken (uint token)
			{
				Debug.Assert (CLR_TypeFromTk (token) == CLR_TABLESENUM.TBL_TypeDef);
				return (uint)CorTokenType.mdtTypeDef | CLR_DataFromTk (token);
			}

			public static uint TinyCLRTokenFromTypeDefToken (uint token)
			{
				Debug.Assert ((token & (uint)CorTokenType.mdtTypeDef) != 0);
				return TinyCLR_TypeSystem.CLR_TkFromType (CLR_TABLESENUM.TBL_TypeDef, token & 0x00ffffff);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
 angularjs infinite paging  ,scroll  loading content , html5 change url

 Welcome to the ng-infinite-paging wiki!

A few weeks ago , i add infinite loading posts in a single page for http://no.pingwest.com . I try to wrap it to a module .

The example : http://no.pingwest.com/n/6060.html


text:
package i5.las2peer.services.ocd.algorithms;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.la4j.matrix.Matrix;

import i5.las2peer.services.ocd.algorithms.utils.OcdAlgorithmException;
import i5.las2peer.services.ocd.algorithms.utils.Termmatrix;
import i5.las2peer.services.ocd.graphs.Cover;
import i5.las2peer.services.ocd.graphs.CoverCreationType;
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.graphs.GraphType;
import i5.las2peer.services.ocd.metrics.ExecutionTime;
import i5.las2peer.services.ocd.algorithms.utils.Similarities;
import i5.las2peer.services.ocd.algorithms.utils.Point;
import y.base.Node;
import i5.las2peer.services.ocd.algorithms.utils.Cluster;
import i5.las2peer.services.ocd.algorithms.utils.CostFunction;
import i5.las2peer.services.ocd.algorithms.utils.Clustering;

/**
 * Implements one of the algorithms by Sabrina Haefele conceived in the thesis:
 * Overlapping Community Detection Based on Content and Authority
 * Some of these algorithms are included in the paper by Shahriari, Mohsen and Haefele, Sabrina and Klamma, Ralf:
 * Contextualized versus structural overlapping communities in social media
 */
public class CostFunctionOptimizationClusteringAlgorithm implements OcdAlgorithm{

	/////////////////
	////Variables////
	/////////////////

	/**
	 * The upper bound for the number of clusters possible. Computing Clusterings between
	 * 1 and the bound, to find the number of clusters with the smallest costs. Default value 50.
	 */
	private int maximumK = 50;

	/**
	 * The threshold to determine whether a node is assigned to another community,
	 * because its distance to that community centroid is smaller that the given threshold.
	 * Default value 0.5.
	 */
	private double beta = 0.7;

	/**
	 * Boolean variable if the svd version of the algorithm should be used.
	 */

	private boolean svd = false;

	////////////////////////
	//// Parameter Names////
	////////////////////////

	public static final String MAXIMUM_K_NAME = "maximumK";
	public static final String OVERLAPPING_THRESHOLD_NAME = "overlappingThreshold";
	public static final String SVD_NAME = "svd";

	////////////////////
	//// Constructor////
	////////////////////

	public CostFunctionOptimizationClusteringAlgorithm(){

	}

	@Override
	public Set<GraphType> compatibleGraphTypes() {
		Set<GraphType> compatibilities = new HashSet<GraphType>();
		compatibilities.add(GraphType.CONTENT_UNLINKED);
		return compatibilities;
	}

	@Override
	public CoverCreationType getAlgorithmType() {
		return CoverCreationType.COST_FUNC_OPT_CLUSTERING_ALGORITHM;
	}

	@Override
	public Map<String, String> getParameters() {
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put(MAXIMUM_K_NAME, Integer.toString(maximumK));
		parameters.put(OVERLAPPING_THRESHOLD_NAME, Double.toString(beta));
		parameters.put(SVD_NAME, Boolean.toString(svd));
		return parameters;
	}

	@Override
	public void setParameters(Map<String, String> parameters) throws IllegalArgumentException {
		if(parameters.containsKey(MAXIMUM_K_NAME)){
			maximumK = Integer.parseInt(parameters.get(MAXIMUM_K_NAME));
			if(maximumK <= 0) {
				throw new IllegalArgumentException();
			}
			parameters.remove(MAXIMUM_K_NAME);
		}
		if(parameters.containsKey(OVERLAPPING_THRESHOLD_NAME)){
			beta = Double.parseDouble(parameters.get(OVERLAPPING_THRESHOLD_NAME));
			if(beta < 0 || beta > 1 ){
				throw new IllegalArgumentException();
			}
			parameters.remove(OVERLAPPING_THRESHOLD_NAME);
		}
		if(parameters.containsKey(SVD_NAME)){
			svd = Boolean.parseBoolean(parameters.get(SVD_NAME));
			parameters.remove(SVD_NAME);
		}
		if(parameters.size() > 0) {
			throw new IllegalArgumentException();
		}
	}

	@Override
	public Cover detectOverlappingCommunities(CustomGraph graph) throws OcdAlgorithmException,InterruptedException {
		Termmatrix termMat = new Termmatrix(graph);
		graph.setTermMatrix(termMat);
		ExecutionTime time = new ExecutionTime();
		time.start();

		if(svd){
			double min = 0;
			Array2DRowRealMatrix m = new  Array2DRowRealMatrix(termMat.SVD().getData());
			for(int ind = 0; ind < m.getRowDimension(); ind++){
				double temp = m.getRowVector(ind).getMinValue();
				if(temp < min){
					min = temp;
				}
			}
			for(int j = 0; j < m.getRowDimension(); j++){
				m.setRowVector(j,m.getRowVector(j).mapAdd(min));
				m.setRowVector(j,m.getRowVector(j).mapMultiply(1000));
			}
			termMat.setMatrix(m);
		}
		Clustering opt = new Clustering();
		Clustering temp = new Clustering();
		if(maximumK > termMat.getNodeIdList().size()){
			return null;
		}
		opt = gradDescClustering(termMat, 2);
		for(int i = 3; i <= maximumK; i++){
			temp = gradDescClustering(termMat, i);
			if(opt.getCosts() > temp.getCosts() && !temp.containsEmpty()){
				opt = temp;
			}
		}
		opt = overlappCommunities(opt, termMat.getNodeIdList());
		Matrix membershipMatrix = opt.createMembershipMatrix(graph);
		Cover res = new Cover(graph,membershipMatrix);
		res.setSimCosts(opt.getCosts());
		time.stop();
		time.setCoverExecutionTime(res);
		return res;
	}

	protected Clustering gradDescClustering(Termmatrix termMat, int k){
		Clustering clustering = new Clustering();
		//Clustering temp = new Clustering();
		CostFunction costFunc = new CostFunction();
		Random randGen = new Random();
		int vectorLength = termMat.getMatrix().getColumnDimension();
		boolean change = true;
		double costs = 0;

		//initialize clusters with centroids randomly generated
		for(int i = 0; i < k; i++){
			Cluster c = new Cluster();
			ArrayRealVector cent = new ArrayRealVector(vectorLength);
			int index = randGen.nextInt(termMat.getNodeIdList().size()-1);
			cent = (ArrayRealVector) termMat.getMatrix().getRowVector(index);
			c.setCentroid(cent);
			clustering.addCluster(c);
		}

		//assign nodes and update centroids
		//clustering.setClustering(assignCluster(clustering.getClustering(),termMat.getMatrix(), termMat.getNodeIdList()));
		//clustering.setCosts(costFunc.valueNode(clustering.getClustering(), termMat.getNodeIdList().size()));

		//assign nodes and update centroids until centroids don't change anymore
		while(change){
		//while(true){
			//temp.setClustering(updateCentroids(clustering.getClustering()));
			//temp.clearCluster();
			//temp.setClustering(assignCluster(temp.getClustering(),termMat.getMatrix(), termMat.getNodeIdList()));
			//temp.setCosts(costFunc.valueNode(temp.getClustering(), termMat.getNodeIdList().size()));
			clustering.setClustering(assignCluster(clustering.getClustering(),termMat.getMatrix(), termMat.getNodeIdList()));
			LinkedList<ArrayRealVector> centroids = getCentroids(clustering.getClustering());
			clustering.setClustering(updateCentroids(clustering.getClustering()));
			change = different(centroids,getCentroids(clustering.getClustering()));

			/*if(clustering.getCosts() == temp.getCosts()){
				break;
			}
			if(clustering.getCosts() > temp.getCosts()){
				clustering.setClustering(temp.getClustering());
				clustering.setCosts(temp.getCosts());
			}*/
		}

		//k++;
		costs = costFunc.value(clustering.getClustering(), termMat.getNodeIdList().size());
		clustering.setCosts(costs);

		return clustering;
	}

	private LinkedList<Cluster> assignCluster(LinkedList<Cluster> clustering, Array2DRowRealMatrix matrix, LinkedList<Node> nodeList){
		double dist = 0;
		double tempDist = 0;
		int index;
		Cluster match;

		for(int i = 0; i < matrix.getRowDimension(); i++){

			ArrayRealVector vector = (ArrayRealVector) matrix.getRowVector(i);
			Point point = new Point(nodeList.get(i),vector);
			Iterator<Cluster> it = clustering.iterator();
			match = it.next();
			dist = distanceCosSim(match.getCentroid(), vector);
			index = clustering.indexOf(match);

			while(it.hasNext()){
				Cluster curr = it.next();
				tempDist = distanceCosSim(curr.getCentroid(), vector);
				if(tempDist <= dist){
					match = curr;
					dist = tempDist;
					index = clustering.indexOf(match);
				}
			}
			match.assignPoint(point);
			clustering.set(index, match);
		}

		return clustering;
	}

	private LinkedList<Cluster> updateCentroids(LinkedList<Cluster> clust){
		CostFunction costFunc = new CostFunction();
		for(Iterator<Cluster> it = clust.iterator(); it.hasNext();){
			Cluster curr = it.next();
			ArrayRealVector cent = curr.getCentroid();
			cent = cent.subtract(costFunc.derivativeValue(curr));
			//cent = cent.add(costFunc.derivativeValue(curr));
			curr.setCentroid(cent);
		}

		return clust;
	}

	private LinkedList<ArrayRealVector> getCentroids(LinkedList<Cluster> clust){
		LinkedList<ArrayRealVector> res = new LinkedList<ArrayRealVector>();
		for(Iterator<Cluster> it = clust.iterator(); it.hasNext();){
			res.add(it.next().getCentroid());
		}
		return res;
	}

	private boolean different(LinkedList<ArrayRealVector> a, LinkedList<ArrayRealVector> b){
		for(int i = 0; i < a.size(); i++){
			ArrayRealVector vectorA = a.get(i);
			ArrayRealVector vectorB = b.get(i);
			double dif = vectorA.subtract(vectorB).getNorm();
			dif = Math.abs(dif);
			if(dif >= 0.0002){
				return true;
			}
		}

		return false;
	}

	private double distanceCosSim(ArrayRealVector v, ArrayRealVector u){
		double dist = 0;
		Similarities sim = new Similarities();

		dist = 1 - sim.cosineSim(v, u);

		return dist;
	}

	private Clustering overlappCommunities(Clustering c, LinkedList<Node> nodes) {
		//Clustering opt = c;
		LinkedList<Point> points = new LinkedList<Point>();
		LinkedList<Cluster> clusters = c.getClustering();
		//LinkedList<Cluster> optC = opt.getClustering();
		CostFunction f = new CostFunction();
		double dist = 2;

		for(Iterator<Cluster> it = clusters.iterator(); it.hasNext();){
			Cluster curr = it.next();
			points.addAll(curr.getPoints());
		}

		for(Iterator<Point> it1 = points.iterator(); it1.hasNext(); ){
				Point p = it1.next();
				for(Iterator<Cluster> it2 = clusters.iterator(); it2.hasNext();){
					Cluster clust = it2.next();
					if(!clust.getPoints().contains(p)){
						dist = distanceCosSim(clust.getCentroid(),p.getCoordinates());
						if(dist <= beta){
							clust.assignPoint(p);

						}
						dist = 2;
					}
				}
			}
		c.setCosts(f.value(c.getClustering(), nodes.size()));

		return c;
	}

}


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.store.access.sort;

import java.util.Properties;

// For JavaDoc references (i.e. @see)

import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.reference.SQLState;
import com.pivotal.gemfirexd.internal.iapi.services.i18n.MessageService;
import com.pivotal.gemfirexd.internal.iapi.services.io.FormatableBitSet;
import com.pivotal.gemfirexd.internal.iapi.sql.Activation;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.iapi.store.access.BackingStoreHashtable;
import com.pivotal.gemfirexd.internal.iapi.store.access.Qualifier;
import com.pivotal.gemfirexd.internal.iapi.store.access.ScanController;
import com.pivotal.gemfirexd.internal.iapi.store.access.ScanInfo;
import com.pivotal.gemfirexd.internal.iapi.store.access.conglomerate.Conglomerate;
import com.pivotal.gemfirexd.internal.iapi.store.access.conglomerate.ScanManager;
import com.pivotal.gemfirexd.internal.iapi.store.raw.Page;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.iapi.types.RowLocation;

/**

	Abstract base class for all sort classes which return rows from the
	sort.  Subclasses must implement fetch, next, and close.

**/

public abstract class Scan implements ScanManager, ScanInfo
{
	/*
	 * Methods of ScanController
	 */

    /**
     * A call to allow client to indicate that current row does not qualify.
     *

     * Indicates to the ScanController that the current row does not
     * qualify for the scan.  If the isolation level of the scan allows,
     * this may result in the scan releasing the lock on this row.
     *

     * Note that some scan implimentations may not support releasing locks on
     * non-qualifying rows, or may delay releasing the lock until sometime
     * later in the scan (ie. it may be necessary to keep the lock until
     * either the scan is repositioned on the next row or page).
     *

     * This call should only be made while the scan is positioned on a current
     * valid row.
     *

     * This call does not make sense for sort scans.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public void didNotQualify()
        throws StandardException
    {
    }

    /**
     * Fetch the next N rows from the table.
     *

     * Currently unimplemented for sorts.
     *

     **/
    public int fetchNextGroup(
    DataValueDescriptor[][]     row_array,
    RowLocation[]               rowloc_array)
        throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

    public int fetchNextGroup(
    DataValueDescriptor[][]     row_array,
    RowLocation[]               old_rowloc_array,
    RowLocation[]               new_rowloc_array)
        throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

// GemStone changes BEGIN
  public int fetchNextGroup(ExecRow[] row_array, RowLocation[] rowloc_array,
      Object[] indexKeys, int[] nodeVersions, int[] scanKeyGroupID,
      LocalRegion[] dataRegions) throws StandardException {
    throw new AssertionError("should not be called");
  }

  public boolean fetchNext(ExecRow destRow) throws StandardException {
    return fetchNext(destRow.getRowArray());
  }

  public void fetch(ExecRow destRow) throws StandardException {
    fetch(destRow.getRowArray());
  }

  @Override
  public ExecRow fetchRow(ExecRow destRow) throws StandardException {
    fetch(destRow);
    return destRow;
  }

  public void fetchWithoutQualify(ExecRow destRow) throws StandardException {
    fetchWithoutQualify(destRow.getRowArray());
  }

  public int getType() {
    return -1;
  }

  public boolean isScanClosed() {
    return false;
  }

// GemStone changes END
    /**
     * Insert all rows that qualify for the current scan into the input
     * Hash table.
     *

     * Currently unimplemented for sorts.
     *

     **/
    public void fetchSet(
    long                    max_rowcnt,
    int[]                   key_column_numbers,
    BackingStoreHashtable   hash_table)
        throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

    /**
    Returns true if the current position of the scan still qualifies
    under the set of qualifiers passed to the openScan().
	@see ScanController#doesCurrentPositionQualify
    **/
    public boolean doesCurrentPositionQualify()
		throws StandardException
    {
		return true;
    }

// GemStone change BEGIN
	/**
	Fetch the location of the current position in the scan.
	@see ScanController#fetchLocation
	**/
	public RowLocation fetchLocation(RowLocation templateLocation)
		throws StandardException {
	  throw StandardException.newException(
	      SQLState.SORT_IMPROPER_SCAN_METHOD);
	}

	public RowLocation getCurrentRowLocation() throws StandardException {
	  throw StandardException.newException(
	      SQLState.BTREE_UNIMPLEMENTED_FEATURE);
	}

	public void upgradeCurrentRowLocationLockToWrite()
	    throws StandardException {
	  throw StandardException.newException(
	      SQLState.BTREE_UNIMPLEMENTED_FEATURE);
	}

	public void releaseCurrentRowLocationReadLock()
	    throws StandardException {
	  throw StandardException.newException(
	      SQLState.BTREE_UNIMPLEMENTED_FEATURE);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int  getScanKeyGroupID() {
	  throw new UnsupportedOperationException("not expected to be invoked");
	}

// GemStone change END
    /**
     * Return ScanInfo object which describes performance of scan.
     *

     * Return ScanInfo object which contains information about the current
     * scan.
     *

     * Currently the ScanInfo does not have any performance data.
     *
     * @see ScanInfo
     *
	 * @return The ScanInfo object which contains info about current scan.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public ScanInfo getScanInfo()
		throws StandardException
    {
        return(this);
    }

    /**
     * Get the total estimated number of rows in the container.
     *

     * The number is a rough estimate and may be grossly off.  In general
     * the server will cache the row count and then occasionally write
     * the count unlogged to a backing store.  If the system happens to
     * shutdown before the store gets a chance to update the row count it
     * may wander from reality.
     *

     * This call is currently only supported on Heap conglomerates, it
     * will throw an exception if called on btree conglomerates.
     *
	 * @return The total estimated number of rows in the conglomerate.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public long getEstimatedRowCount()
		throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

    /**
     * Set the total estimated number of rows in the container.
     *

     * Often, after a scan, the client of RawStore has a much better estimate
     * of the number of rows in the container than what store has.  For
     * instance if we implement some sort of update statistics command, or
     * just after a create index a complete scan will have been done of the
     * table.  In this case this interface allows the client to set the
     * estimated row count for the container, and store will use that number
     * for all future references.
     *

     * This call is currently only supported on Heap conglomerates, it
     * will throw an exception if called on btree conglomerates.
     *
     * @param count the estimated number of rows in the container.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public void setEstimatedRowCount(long count)
		throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

    /**
    Returns true if the current position of the scan is at a
    deleted row.
	@see ScanController#isCurrentPositionDeleted
    **/
    public boolean isCurrentPositionDeleted()
		throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

    /**
     * Return whether this is a keyed conglomerate.
     *

     *
	 * @return whether this is a keyed conglomerate.
     **/
	public boolean isKeyed()
    {
        return(false);
    }

    /**
     * Return whether this scan is table locked.
     *
	 * @return whether this is table locked.
     **/
    public boolean isTableLocked()
    {
        return(true);
    }

    /**
    Delete the row at the current position of the scan.
	@see ScanController#delete
    **/
    public boolean delete()
		throws StandardException
	{
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
	}

    /**
    Reposition the current scan.
	@see ScanController#reopenScan
    **/
	public void reopenScan(
    DataValueDescriptor[]   startKeyValue,
    int                     startSearchOperator,
    Qualifier               qualifier[][],
    DataValueDescriptor[]   stopKeyValue,
    int                     stopSearchOperator,
    // GemStone changes BEGIN
    Activation activation)
    // GemStone changes END
        throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

    /**
    Reposition the current scan.  This call is semantically the same as if
    the current scan had been closed and a openScan() had been called instead.
    The scan is reopened against the same conglomerate, and the scan
    is reopened with the same "scan column list", "hold" and "forUpdate"
    parameters passed in the original openScan.

	@exception StandardException Standard exception policy.
    **/
	public void reopenScanByRowLocation(
    RowLocation startRowLocation,
    Qualifier qualifier[][])
        throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

    /**
    Replace the entire row at the current position of the scan.
	@see ScanController#replace
    **/
    public boolean replace(
    DataValueDescriptor[]   val,
    FormatableBitSet                 validColumns)
		throws StandardException
	{
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
	}

	/**
	Return a row location object of the correct type to be
	used in calls to fetchLocation.
	@see ScanController#newRowLocationTemplate
	**/
	public RowLocation newRowLocationTemplate()
		throws StandardException
 	{
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
	}

    /**
     *@see ScanController#positionAtRowLocation
     */
    public boolean positionAtRowLocation(RowLocation rl)
        throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

	/*
	** Methods of ScanManager
	*/

    /**
     * Do work necessary to maintain the current position in the scan.
     *

     * The latched page in the conglomerate "congomid" is changing, do
     * whatever is necessary to maintain the current position of the scan.
     * For some conglomerates this may be a no-op.
     *

     *
     * @param conglom   Conglomerate object of the conglomerate being changed.
     * @param page      Page in the conglomerate being changed.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public void savePosition(Conglomerate conglom, Page page)
        throws StandardException
	{
        // RESOLVE (mikem), under the current implementation all scans within
        // a transaction are called rather than just the ones with the right
        // conglomid.  For now just have sort scans ignore the call.

        return;
	}

	/*
	 * Methods of ScanInfo
	 */

    /**
     * Return all information gathered about the scan.
     *

     * This routine returns a list of properties which contains all information
     * gathered about the scan.  If a Property is passed in, then that property
     * list is appeneded to, otherwise a new property object is created and
     * returned.
     *

     * Currently sort scans doesn't track any information.
     *
     * @param prop   Property list to fill in.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public Properties getAllScanInfo(Properties prop)
		throws StandardException
    {
        if (prop == null)
            prop = new Properties();

        prop.put(
			MessageService.getTextMessage(SQLState.STORE_RTS_SCAN_TYPE),
			MessageService.getTextMessage(SQLState.STORE_RTS_SORT));

        return(prop);
    }

    /**
     * @see com.pivotal.gemfirexd.internal.iapi.store.access.ScanController#isHeldAfterCommit
     */
    public boolean isHeldAfterCommit() throws StandardException
    {
        throw StandardException.newException(
                SQLState.SORT_IMPROPER_SCAN_METHOD);
    }

}


text:
package org.uli.springdatajpa.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.uli.springdatajpa.entities.Person;

public interface PersonRepository extends JpaRepository<Person, Integer> {
    Person findByLastName(String lastName);
}


text: export { DragVertical16 as default } from "../../";


text:
#include <DepositResponse.h>

#include <GetSymbolsRequest.h>

#include <GetSymbolsResponse.h>

#include <GetQuoteRequest.h>

#include <GetQuoteResponse.h>

#include <CreateAccountRequest.h>

#include <CreateAccountResponse.h>

#include <SellRequest.h>

#include <SellResponse.h>

#include <BuyRequest.h>

#include <BuyResponse.h>

#include <GetPortfolioRequest.h>

#include <GetPortfolioResponse.h>

#include <TraderClientStub.h>

using namespace std;
using namespace org_wso2_www;
using namespace org_wso2_www_types;

bool createAccount(std::string user,
				   std::string password,
				   std::string epr,
				   std::string clientHome)
{

	ClientInfo *clientinfo = new ClientInfo();
	clientinfo->setName(user);
	clientinfo->setSsn("1111");
	CreateAccountRequest *request = new CreateAccountRequest();
	request->setClientinfo(clientinfo);
	request->setPassword(password);

	TraderClientStub *stub = new TraderClientStub(clientHome,epr);

	if(stub)
	{
		CreateAccountResponse *response = stub->createAccount(request);
		if(response)
		std::cout<<"RESULTS , Your user id is "<<response->getUserid()<<std::endl;

		delete stub;
		return true;
	}
	return false;
}

bool buy(std::string user,
		 std::string password,
		 std::string symbol,
		 std::string qty,
		 std::string epr,
		 std::string clientHome)
{
	BuyRequest *request = new BuyRequest();
	request->setUserid(user);
	request->setPassword(password);
	request->setSymbol(symbol);
	request->setQty(atoi(qty.c_str()));
	TraderClientStub *stub = new TraderClientStub(clientHome, epr);
	bool status = false;
	BuyResponse *response = stub->buy(request);
	if(response)
	{
		TradeStatus *sts = response->getTrade_status();
		if(sts)
		{
			std::cout<<"RESULTS: " << sts->getReason()<<std::endl;
			status = sts->getStatus();
		}
	}

	delete stub;
	return status;
}

bool sell(std::string user,
		  std::string password,
		  std::string symbol,
		  std::string qty,
		  std::string epr,
		  std::string clientHome)
{

	SellRequest *request = new SellRequest();
	request->setUserid(user);
	request->setPassword(password);
	request->setSymbol(symbol);
	request->setQty(atoi(qty.c_str()));

	TraderClientStub *stub = new TraderClientStub(clientHome, epr);
	SellResponse *response = stub->sell(request);
	bool status = false;
	if(response)
	{
		TradeStatus *sts = response->getTrade_status();
		if(sts)
		{
			std::cout<<"RESULTS: "<<sts->getReason()<<std::endl;
			status = sts->getStatus();
		}
	}

	delete stub;
	return status;
}

int main(int argc, char *argv[])
{

	bool status = false;
	wso2wsf::Environment::initialize("traderclient.log",AXIS2_LOG_LEVEL_TRACE);
	std::string clientHome = AXIS2_GETENV("WSFCPP_HOME");
	std::string operation ="";
	if(clientHome.empty())
	{
		std::cout<<"Please check the WSFCPP_HOME environment variable"<<std::endl;
		return 0;
	}

	std::string address = "http://localhost:9090/axis2/services/TraderClient";
	if (argc > 1)
	{
		operation = argv[1];
	}
	else
	{
		std::cout<<"Type ./trader -h for usage\n"<<std::endl;
		return 0;
	}

	if(operation.compare("-h") ==  0)
	{
		printf("Usage : %s [create-account] [username] [password] [endpoint_url]\n", argv[0]);
		printf("Usage : %s [buy] [username] [password] [symbol] [quantity] [endpoint_url]\n", argv[0]);
		printf("Usage : %s [sell] [username] [password] [symbol] [quantity] [endpoint_url]\n", argv[0]);
		printf("use -h for help\n");
		printf("NOTE: command line arguments must appear in given order, with trailing ones being optional\n");
		return 0;
	}

	std::cout<<"Using Endpoint "<<address<<std::endl;

	if(operation.compare("create-account") == 0)
	{
		if(argc < 4)
		{
			printf("Some arguments are missing\n .use -h for help\n");
			return 0;
		}
		else if(argc > 4)
		{
			address = argv[4];
		}
		status = createAccount(argv[2], argv[3], address, clientHome);
	}
	else if(operation.compare("buy") == 0)
	{
		if(argc < 6)
		{
			printf("Some arguments are missing\n .use -h for help\n");
			return 0;
		}
		else if(argc > 6)
		{
			address = argv[6];
		}
		status = buy(argv[2], argv[3], argv[4], argv[5], address, clientHome);
	}
	else if(axutil_strcmp(operation.c_str(), "sell") == 0)
	{
		if(argc < 6)
		{
			printf("Some arguments are missing\n .use -h for help\n");
			return 0;
		}
		else if(argc > 6)
		{
			address = argv[6];
		}
		status = sell(argv[2], argv[3], argv[4], argv[5], address, clientHome);
	}

	else
	{
		printf("Unknown operation \n");
	}

	if(!status)
	{
		printf("Trader-Client invoke failed\n");
	}
	else
	{
		printf("Trader-Client invoke Successful\n");
	}
}


text:
import { module, test } from 'qunit';
import { setupTest } from '<%= dasherizedPackageName %>/tests/helpers';

module('<%= friendlyTestDescription %>', function(hooks) {
  setupTest(hooks);

  // Replace this with your real tests.
  test('it exists', function(assert) {
    let adapter = this.owner.lookup('adapter:<%= dasherizedModuleName %>');
    assert.ok(adapter);
  });
});


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>ConverterTypeName Property</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

TypeConverterAttribute.ConverterTypeName Property

 The string type name of the type converter

        [Visual Basic]

Public Property ConverterTypeName As String

        [C#]

public string ConverterTypeName {get; set;}

Property Value

 The string type name of the type converter

Remarks

 The type specified must implement the IConvertFrom or the IConvertTo interfaces.

See Also

TypeConverterAttribute Class | log4net.Util.TypeConverters Namespace
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="ConverterTypeName property"></param><param name="Keyword" value="ConverterTypeName property, TypeConverterAttribute class"></param><param name="Keyword" value="TypeConverterAttribute.ConverterTypeName property"></param></object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
package org.kie.pmml.models.drools.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.dmg.pmml.CompoundPredicate;
import org.dmg.pmml.DataType;
import org.dmg.pmml.Predicate;
import org.dmg.pmml.SimplePredicate;
import org.junit.BeforeClass;
import org.junit.Test;
import org.kie.pmml.commons.exceptions.KiePMMLException;
import org.kie.pmml.commons.model.enums.BOOLEAN_OPERATOR;
import org.kie.pmml.commons.model.enums.OPERATOR;
import org.kie.pmml.models.drools.ast.KiePMMLFieldOperatorValue;
import org.kie.pmml.models.drools.tuples.KiePMMLOperatorValue;
import org.kie.pmml.models.drools.tuples.KiePMMLOriginalTypeGeneratedType;

import static java.util.stream.Collectors.groupingBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class KiePMMLASTFactoryUtilsTest {

    private static Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap;
    private static Map<String, DataType> simplePredicateNameType;
    private static List<SimplePredicate> simplePredicates;
    private static List<CompoundPredicate> compoundPredicates;

    @BeforeClass
    public static void setup() {
        fieldTypeMap = new HashMap<>();
        simplePredicateNameType = new HashMap<>();
        simplePredicateNameType.put("age", DataType.INTEGER);
        simplePredicateNameType.put("weight", DataType.DOUBLE);
        simplePredicateNameType.put("name", DataType.STRING);
        simplePredicateNameType.put("runner", DataType.BOOLEAN);
        simplePredicates = simplePredicateNameType
                .entrySet()
                .stream()
                .map(entry -> KiePMMLASTTestUtils.getSimplePredicate(entry.getKey(),
                                                                     entry.getValue(),
                                                                     getRandomValue(entry.getValue()),
                                                                     getRandomSimplePredicateOperator(),
                                                                     fieldTypeMap))
                .collect(Collectors.toList());
        compoundPredicates = IntStream.range(0, 4)
                .mapToObj(KiePMMLASTFactoryUtilsTest::getCompoundPredicate)
                .collect(Collectors.toList());
    }

    private static Object getRandomValue(DataType dataType) {
        switch (dataType) {
            case INTEGER:
                return new Random().nextInt(40);
            case DOUBLE:
                return new Random().nextDouble();
            case BOOLEAN:
                return new Random().nextBoolean();
            case STRING:
                return UUID.randomUUID().toString();
            default:
                return null;
        }
    }

    private static CompoundPredicate getCompoundPredicate(int counter) {
        CompoundPredicate toReturn = new CompoundPredicate();
        toReturn.setBooleanOperator(getRandomCompoundPredicateAndOrOperator(counter));
        toReturn.getPredicates().addAll(getRandomSimplePredicates());
        return toReturn;
    }

    private static List<SimplePredicate> getRandomSimplePredicates() {
        int firstIndex = new Random().nextInt(simplePredicates.size());
        int secondIndex = -1;
        while (secondIndex == -1 || secondIndex == firstIndex) {
            secondIndex = new Random().nextInt(simplePredicates.size());
        }
        return Arrays.asList(simplePredicates.get(firstIndex), simplePredicates.get(secondIndex));
    }

    private static CompoundPredicate.BooleanOperator getRandomCompoundPredicateAndOrOperator(int counter) {
        return counter % 2 == 0 ? CompoundPredicate.BooleanOperator.AND : CompoundPredicate.BooleanOperator.OR;
    }

    private static SimplePredicate.Operator getRandomSimplePredicateOperator() {
        final SimplePredicate.Operator[] values = SimplePredicate.Operator.values();
        int rndIndex = new Random().nextInt(values.length - 3);
        return values[rndIndex];
    }

    @Test
    public void getConstraintEntriesFromXOrCompoundPredicate() {
        CompoundPredicate compoundPredicate = new CompoundPredicate();
        compoundPredicate.setBooleanOperator(CompoundPredicate.BooleanOperator.XOR);
        List<Predicate> predicates = IntStream.range(0, 2).mapToObj(index -> simplePredicates.get(index)).collect(Collectors.toList());
        compoundPredicate.getPredicates().addAll(predicates);
        List<KiePMMLFieldOperatorValue> retrieved = KiePMMLASTFactoryUtils
                .getConstraintEntriesFromXOrCompoundPredicate(compoundPredicate, fieldTypeMap);
        assertNotNull(retrieved);
        assertEquals(predicates.size(), retrieved.size());
        commonVerifyKiePMMLFieldOperatorValueList(retrieved, null);
    }

    @Test(expected = KiePMMLException.class)
    public void getConstraintEntriesFromXOrCompoundPredicateWrongSize() {
        CompoundPredicate compoundPredicate = new CompoundPredicate();
        compoundPredicate.setBooleanOperator(CompoundPredicate.BooleanOperator.XOR);
        compoundPredicate.getPredicates().addAll(simplePredicates);
        KiePMMLASTFactoryUtils.getConstraintEntriesFromXOrCompoundPredicate(compoundPredicate, fieldTypeMap);
    }

    @Test(expected = KiePMMLException.class)
    public void getConstraintEntriesFromXOrCompoundPredicateWrongOperator() {
        CompoundPredicate compoundPredicate = new CompoundPredicate();
        compoundPredicate.setBooleanOperator(CompoundPredicate.BooleanOperator.AND);
        KiePMMLASTFactoryUtils.getConstraintEntriesFromXOrCompoundPredicate(compoundPredicate, fieldTypeMap);
    }

    @Test
    public void getConstraintEntryFromSimplePredicates() {
        final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = new HashMap<>();
        String fieldName = "FIELD_NAME";
        List<SimplePredicate> simplePredicates = IntStream.range(0, 2)
                .mapToObj(index -> KiePMMLASTTestUtils
                        .getSimplePredicate(fieldName, DataType.STRING, "VALUE-" + index, SimplePredicate.Operator.LESS_THAN, fieldTypeMap)).collect(Collectors.toList());
        final KiePMMLFieldOperatorValue retrieved = KiePMMLASTFactoryUtils
                .getConstraintEntryFromSimplePredicates(fieldName, BOOLEAN_OPERATOR.OR, simplePredicates, fieldTypeMap);
        assertEquals(fieldName, retrieved.getName());
        assertNotNull(retrieved.getConstraintsAsString());
        String expected = "value < \"VALUE-0\" || value < \"VALUE-1\"";
        assertEquals(expected, retrieved.getConstraintsAsString());
    }

    @Test
    public void getXORConstraintEntryFromSimplePredicates() {
        List<Predicate> predicates = new ArrayList<>(simplePredicates);
        List<KiePMMLFieldOperatorValue> retrieved = KiePMMLASTFactoryUtils
                .getXORConstraintEntryFromSimplePredicates(predicates, fieldTypeMap);
        assertNotNull(retrieved);
        assertEquals(simplePredicates.size(), retrieved.size());
        commonVerifyKiePMMLFieldOperatorValueList(retrieved, null);
    }

    @Test
    public void getCorrectlyFormattedObject() {
        simplePredicates.forEach(simplePredicate -> {
            Object retrieved = KiePMMLASTFactoryUtils.getCorrectlyFormattedObject(simplePredicate, fieldTypeMap);
            Object expected = simplePredicate.getValue();
            if (expected instanceof String) {
                expected = String.format("\"%s\"", expected);
            }
            assertEquals(expected, retrieved);
        });
    }

    @Test
    public void populateKiePMMLFieldOperatorValueListWithSimplePredicatesWithAnd() {
        commonPopulateKiePMMLFieldOperatorValueListWithSimplePredicates(CompoundPredicate.BooleanOperator.AND, BOOLEAN_OPERATOR.AND);
    }

    @Test
    public void populateKiePMMLFieldOperatorValueListWithSimplePredicatesWithOr() {
        commonPopulateKiePMMLFieldOperatorValueListWithSimplePredicates(CompoundPredicate.BooleanOperator.OR, BOOLEAN_OPERATOR.OR);
    }

    @Test
    public void populateKiePMMLFieldOperatorValueListWithCompoundPredicates() {
        final List<KiePMMLFieldOperatorValue> toPopulate = new ArrayList<>();
        KiePMMLASTFactoryUtils.populateKiePMMLFieldOperatorValueListWithCompoundPredicates(toPopulate, compoundPredicates, fieldTypeMap);
        assertFalse(toPopulate.isEmpty());
        assertEquals(2, toPopulate.size()); // one entry is for "AND" compounds and the other is for "OR" ones
        final Map<CompoundPredicate.BooleanOperator, List<CompoundPredicate>> partitionedCompoundPredicates = compoundPredicates.stream()
                .collect(Collectors.groupingBy(CompoundPredicate::getBooleanOperator));
        partitionedCompoundPredicates.forEach((booleanOperator, compoundPredicates) -> {
            final KiePMMLFieldOperatorValue operatorValue = toPopulate.stream()
                    .filter(kiePMMLFieldOperatorValue -> kiePMMLFieldOperatorValue.getOperator().equals(BOOLEAN_OPERATOR.byName(booleanOperator.value())))
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("Failed toRetrieve KiePMMLFieldOperatorValue for BooleanOperator " + booleanOperator));
            final List<KiePMMLFieldOperatorValue> nestedKiePMMLFieldOperatorValues = operatorValue.getNestedKiePMMLFieldOperatorValues();
            final List<Predicate> nestedPredicates = compoundPredicates.stream().flatMap(compoundPredicate -> compoundPredicate.getPredicates().stream()).collect(Collectors.toList());
            assertEquals(nestedPredicates.size(), nestedKiePMMLFieldOperatorValues.size());
            nestedKiePMMLFieldOperatorValues.forEach(new Consumer<KiePMMLFieldOperatorValue>() {
                @Override
                public void accept(KiePMMLFieldOperatorValue kiePMMLFieldOperatorValue) {
                    assertEquals(1, kiePMMLFieldOperatorValue.getKiePMMLOperatorValues().size());
                    final KiePMMLOperatorValue kiePMMLOperatorValue = kiePMMLFieldOperatorValue.getKiePMMLOperatorValues().get(0);
                    SimplePredicate simplePredicate = nestedPredicates.stream()
                            .map(predicate -> (SimplePredicate) predicate)
                            .filter(predicate -> predicate.getField().getValue().equals(getOriginalPredicateName(kiePMMLFieldOperatorValue.getName())))
                            .findFirst()
                            .orElseThrow(() -> new RuntimeException("Failed to find SimplePredicate for " + kiePMMLFieldOperatorValue.getName()));
                    commonVerifyKiePMMLOperatorValue(kiePMMLOperatorValue, simplePredicate);
                    nestedPredicates.remove(simplePredicate);
                }
            });
            assertTrue(nestedPredicates.isEmpty());
        });
    }

    private void commonPopulateKiePMMLFieldOperatorValueListWithSimplePredicates(CompoundPredicate.BooleanOperator compoundBooleanOperator, BOOLEAN_OPERATOR booleanOperator) {
        final Map<String, List<SimplePredicate>> predicatesByField = simplePredicates.stream()
                .collect(groupingBy(child -> fieldTypeMap.get(child.getField().getValue()).getGeneratedType()));
        final List<KiePMMLFieldOperatorValue> toPopulate = new ArrayList<>();
        KiePMMLASTFactoryUtils.populateKiePMMLFieldOperatorValueListWithSimplePredicates(toPopulate, compoundBooleanOperator, predicatesByField, fieldTypeMap);
        assertEquals(simplePredicates.size(), toPopulate.size());
        commonVerifyKiePMMLFieldOperatorValueList(toPopulate, booleanOperator);
    }

    private void commonVerifyKiePMMLFieldOperatorValueList(List<KiePMMLFieldOperatorValue> toVerify, BOOLEAN_OPERATOR booleanOperator) {
        toVerify.forEach(kiePMMLFieldOperatorValue -> {
            assertEquals(booleanOperator, kiePMMLFieldOperatorValue.getOperator());
            commonVerifyKiePMMLFieldOperatorValue(kiePMMLFieldOperatorValue);
        });
    }

    private void commonVerifyKiePMMLFieldOperatorValue(final KiePMMLFieldOperatorValue toVerify) {
        final SimplePredicate simplePredicate = getSimplePredicate(toVerify.getName());
        commonVerifyKiePMMLFieldOperatorValue(toVerify, simplePredicate);
    }

    private void commonVerifyKiePMMLFieldOperatorValue(final KiePMMLFieldOperatorValue toVerify, final SimplePredicate simplePredicate) {
        assertEquals(1, toVerify.getKiePMMLOperatorValues().size());
        final KiePMMLOperatorValue kiePMMLOperatorValue = toVerify.getKiePMMLOperatorValues().get(0);
        commonVerifyKiePMMLOperatorValue(kiePMMLOperatorValue, simplePredicate);
        Object expectedValue = simplePredicate.getValue();
        if (expectedValue instanceof String) {
            expectedValue = String.format("\"%s\"", expectedValue);
        }
        String expectedOperator = OPERATOR.byName(simplePredicate.getOperator().value()).getOperator();
        String expected = String.format("value %s %s", expectedOperator, expectedValue);
        assertEquals(expected, toVerify.getConstraintsAsString());
    }

    private void commonVerifyKiePMMLOperatorValue(final KiePMMLOperatorValue toVerify, final SimplePredicate simplePredicate) {
        assertNotNull(toVerify.getOperator());
        Object expectedValue = simplePredicate.getValue();
        if (expectedValue instanceof String) {
            expectedValue = String.format("\"%s\"", expectedValue);
        }
        assertEquals(expectedValue, toVerify.getValue());
    }

    private SimplePredicate getSimplePredicate(String generatedType) {
        String predicateName = getOriginalPredicateName(generatedType);
        return simplePredicates.stream()
                .filter(simplePredicate -> simplePredicate.getField().getValue().equals(predicateName))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("Failed to find SimplePredicate for " + predicateName));
    }

    private String getOriginalPredicateName(String generatedType) {
        return fieldTypeMap.entrySet().stream()
                .filter(entry -> entry.getValue().getGeneratedType().equals(generatedType))
                .findFirst()
                .map(Map.Entry::getKey)
                .orElseThrow(() -> new RuntimeException("Failed to find original type for " + generatedType));
    }
}


text:
<?php

namespace Madewithlove\ServiceProviders\Templating;

use Interop\Container\ServiceProviderInterface;
use Madewithlove\ServiceProviders\Utilities\Alias;
use Psr\Container\ContainerInterface;
use Twig_Environment;
use Twig_Extension;
use Twig_Loader_Array;
use Twig_Loader_Filesystem;
use Twig_LoaderInterface;

class TwigServiceProvider implements ServiceProviderInterface
{
    /**
     * Path to the views or a list of views.
     *
     * @var string|string[]
     */
    protected $views;

    /**
     * @var array
     */
    protected $options = [];

    /**
     * @var Twig_Extension[]
     */
    protected $extensions = [];

    /**
     * @param string|string[]  $views
     * @param array            $options
     * @param Twig_Extension[] $extensions
     */
    public function __construct($views = [], array $options = [], array $extensions = [])
    {
        $this->views = $views;
        $this->options = $options;
        $this->extensions = $extensions;
    }

    /**
     * {@inheritdoc}
     */
    public function getServices()
    {
        return [
            Twig_LoaderInterface::class => [$this, 'getLoader'],
            Twig_Environment::class => [$this, 'getEnvironment'],
            'twig' => new Alias(Twig_Environment::class),
        ];
    }

    /**
     * @return Twig_LoaderInterface
     */
    public function getLoader()
    {
        if (is_string($this->views) && !is_dir($this->views)) {
            $this->views = [$this->views];
        }

        $isViewsFolder = is_string($this->views) && is_dir($this->views);
        $loader = $isViewsFolder ? Twig_Loader_Filesystem::class : Twig_Loader_Array::class;

        return new $loader($this->views ?: []);
    }

    /**
     * @param ContainerInterface $container
     *
     * @return Twig_Environment
     */
    public function getEnvironment(ContainerInterface $container)
    {
        $twig = new Twig_Environment($container->get(Twig_LoaderInterface::class), $this->options);
        foreach ($this->extensions as $extension) {
            $twig->addExtension(is_string($extension) ? $container->get($extension) : $extension);
        }

        return $twig;
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <arpa/inet.h>

#define MAGIC 0x4a544147

struct header {
    unsigned int magic;
    unsigned int len;
    unsigned int be_crc32;  // CRC32 in big endian (network) format
};

int main(int argc, char **argv)
{
    int fd;
    void * map_base;
    unsigned char * payload;
	off_t start;
	unsigned int len;
    struct header header;
    int has_header = 0;

	if(argc != 3) {
		fprintf(stderr,
            "Summary: Dump bytes from /dev/mem to stdout\n"
            "\n"
            "Usage:\n"
            "    %s <start_addr> <num_bytes>\n"
            "    %s -H <start_addr>\n"
            "\n"
            "Arguments:\n"
            "    start_addr: Start address to dump.  Decimal or hex.  Must be page aligned.\n"
            "    num_bytes: Number of bytes to dump.  Decimal or hex. \n"
            "\n"
            "Returns: Zero on success.\n"
            "\n"
            "Notes:\n"
            "   If -H is specified, then the start_addr begins with a 3 32-bit word header\n"
            "   with the following fields:\n"
            "     - MAGIC: Magic number header identifier\n"
            "     - LEN: Number of bytes that follow this header\n"
            "     - CRC32: CRC32 of LEN bytes following header\n"
            "   In this case, the number of bytes to dump will be determined from the header\n"
            "   and the CRC32 will be verified.\n"
            "\n"
            "   The start_address must be a region outside of Linux addressable memory, but\n"
            "   still within physical RAM.  Generally, only useful if the Linux addressable\n"
            "   memory was artifically limited with the mem=NNN kernel command line option.\n"
            "   Using an address outside of physical RAM will crash Linux.\n"
            "\n",
			argv[0],
			argv[0]);
		exit(1);
	}

    if (strcmp("-H", argv[1]) == 0) {
        start = strtoul(argv[2], NULL, 0);

        if ((fd = open("/dev/mem", O_RDONLY)) == 1) return 1;

        map_base = mmap(NULL, sizeof(struct header), PROT_READ, MAP_SHARED, fd, start);
        if (map_base == MAP_FAILED) return 2;

        memcpy((void *) &header, map_base, sizeof(struct header));

        close(fd);

        if (header.magic != MAGIC) return 3;
        len = header.len;
        has_header = 1;

    } else {
        start = strtoul(argv[1], NULL, 0);
        len = strtoul(argv[2], NULL, 0);
    }

    if ((fd = open("/dev/mem", O_RDONLY)) == 1) return 4;

    unsigned int map_len = has_header ? len + sizeof(struct header) : len;
    map_base = mmap(NULL, map_len, PROT_READ, MAP_SHARED, fd, start);
    if (map_base == MAP_FAILED) return 5;

    payload = (unsigned char *) map_base;
    if (has_header) {
        payload += sizeof(struct header);
        unsigned int computed_crc32 = crc32(0, payload, len);
        if (computed_crc32 != ntohl(header.be_crc32)) return 6;
    }

    for (unsigned int i = 0; i < len; i++) {
        putchar(payload[i]);
    }

	if (munmap(map_base, len) == -1) return 7;
    close(fd);

    return 0;
}


text:
title: Plugin Development - Storing Custom Entities
book: plugin_dev
chapter: 6
---

## Introduction

While not all plugins need it, your plugin might need to store more than
its configuration in the database. In that case, Kong provides you with
an abstraction on top of its primary datastores which allows you to store
custom entities.

As explained in the [previous chapter]({{page.book.previous}}), Kong interacts
with the model layer through classes we refer to as "DAOs", and available on a
singleton often referred to as the "DAO Factory". This chapter will explain how
to to provide an abstraction for your own entities.

## Modules

```
kong.plugins.<plugin_name>.daos
kong.plugins.<plugin_name>.migrations.init
kong.plugins.<plugin_name>.migrations.000_base_<plugin_name>
kong.plugins.<plugin_name>.migrations.001_<from-version>_to_<to_version>
kong.plugins.<plugin_name>.migrations.002_<from-version>_to_<to_version>
```

## Create the migrations folder

Once you have defined your model, you must create your migration modules which
will be executed by Kong to create the table in which your records of your
entity will be stored.

If your plugin is intended to support both Cassandra and Postgres, then both
migrations must be written.

If your plugin doesn't have it already, you should add a `<plugin_name>/migrations`
folder to it. If there is no `init.lua` file inside already, you should create one.
This is where all the migrations for your plugin will be referenced.

The initial version of your `migrations/init.lua` file will point to a single migration.

In this case we have called it `000_base_my_plugin`.

``` lua
-- `migrations/init.lua`
return {
  "000_base_my_plugin",
}
```

This means that there will be a file in `<plugin_name>/migrations/000_base_my_plugin.lua`
containing the initial migrations. We'll see how this is done in a minute.

## Adding a new migration to an existing plugin

Sometimes it is necessary to introduce changes after a version of a plugin has already been
released. A new functionality might be needed. A database table row might need changing.

When this happens, *you must* create a new migrations file. You *must not* of modify the
existing migration files once they are published (you can still make them more robust and
bulletproof if you want, e.g. always try to write the migrations reentrant).

While there is no strict rule for naming your migration files, there is a convention that the
initial one is prefixed by `000`, the next one by `001`, and so on.

Following with our previous example, if we wanted to release a new version of the plugin with
changes in the database (for example, a table was needed called `foo`) we would insert it by
adding a file called `<plugin_name>/migrations/001_100_to_110.lua`, and referencing it on the
migrations init file like so (where `100` is the previous version of the plugin `1.0.0` and
`110` is the version to which plugin is migrated to `1.1.0`:

``` lua
-- `<plugin_name>/migrations/init.lua`
return {
  "000_base_my_plugin",
  "001_100_to_110",
}
```

## Migration File syntax

While Kong's core migrations support both Postgres and Cassandra, custom plugins
can choose to support either both of them or just one.

A migration file is a Lua file which returns a table with the following structure:

``` lua
-- `<plugin_name>/migrations/000_base_my_plugin.lua`
return {
  postgresql = {
    up = [[
      CREATE TABLE IF NOT EXISTS "my_plugin_table" (
        "id"           UUID                         PRIMARY KEY,
        "created_at"   TIMESTAMP WITHOUT TIME ZONE,
        "col1"         TEXT
      );

      DO $$
      BEGIN
        CREATE INDEX IF NOT EXISTS "my_plugin_table_col1"
                                ON "my_plugin_table" ("col1");
      EXCEPTION WHEN UNDEFINED_COLUMN THEN
        -- Do nothing, accept existing state
      END$$;
    ]],
  },

  cassandra = {
    up = [[
      CREATE TABLE IF NOT EXISTS my_plugin_table (
        id          uuid PRIMARY KEY,
        created_at  timestamp,
        col1        text
      );

      CREATE INDEX IF NOT EXISTS ON my_plugin_table (col1);
    ]],
  }
}

-- `<plugin_name>/migrations/001_100_to_110.lua`
return {
  postgresql = {
    up = [[
      DO $$
      BEGIN
        ALTER TABLE IF EXISTS ONLY "my_plugin_table" ADD "cache_key" TEXT UNIQUE;
      EXCEPTION WHEN DUPLICATE_COLUMN THEN
        -- Do nothing, accept existing state
      END;
    $$;
    ]],
    teardown = function(connector, helpers)
      assert(connector:connect_migrations())
      assert(connector:query([[
        DO $$
        BEGIN
          ALTER TABLE IF EXISTS ONLY "my_plugin_table" DROP "col1";
        EXCEPTION WHEN UNDEFINED_COLUMN THEN
          -- Do nothing, accept existing state
        END$$;
      ]])
    end,
  },

  cassandra = {
    up = [[
      ALTER TABLE my_plugin_table ADD cache_key text;
      CREATE INDEX IF NOT EXISTS ON my_plugin_table (cache_key);
    ]],
    teardown = function(connector, helpers)
      assert(connector:connect_migrations())
      assert(connector:query("ALTER TABLE my_plugin_table DROP col1"))
    end,
  }
}
```

If a plugin only supports Postgres or Cassandra, only the section for one strategy is
needed. Each strategy section has two parts, `up` and `teardown`.

* `up` is an optional string of raw SQL/CQL statements. Those statements will be executed
  when `kong migrations up` is executed.
* `teardown` is an optional Lua function, which takes a `connector` parameter. Such connector
  can invoke the `query` method to execute SQL/CQL queries. Teardown is triggered by
  `kong migrations finish`

It is recommended that all the non-destructive operations, such as creation of new tables and
addition of new records is done on the `up` sections, while destructive operations (such as
removal of data, changing row types, insertion of new data) is done on the `teardown` sections.

In both cases, it is recommended that all the SQL/CQL statements are written so that they are
as reentrant as possible. `DROP TABLE IF EXISTS` instead of `DROP TABLE`,
`CREATE INDEX IF NOT EXIST` instead of `CREATE INDEX`, etc. If a migration fails for some
reason, it is expected that the first attempt at fixing the problem will be simply
re-running the migrations.

While Postgres does, Cassandra does not support constraints such as "NOT
NULL", "UNIQUE" or "FOREIGN KEY", but Kong provides you with such features when
you define your model's schema. Bear in mind that this schema will be the same
for both Postgres and Cassandra, hence, you might trade-off a pure SQL schema
for one that works with Cassandra too.

**IMPORTANT**: if your `schema` uses a `unique` constraint, then Kong will
enforce it for Cassandra, but for Postgres you must set this constraint in
the migrations.

To see a real-life example, give a look at the [Key-Auth plugin migrations](https://github.com/Kong/kong/tree/{{page.kong_version}}/kong/plugins/key-auth/migrations).

---

## Defining a Schema

The first step to using custom entities in a custom plugin is defining one
or more *schemas*.

A schema is a Lua table which describes entities. There's structural information
like how are the different fields of the entity named and what are their types,
which is similar to the fields describing your [plugin
configuration]({{page.book.chapters.plugin-configuration}})).
Compared to plugin configuration schemas, custom entity schemas require
additional metadata (e.g. which field, or fields, constitute the entities'
primary key).

Schemas are to be defined in a module named:

```
kong.plugins.<plugin_name>.daos
```

Meaning that there should be a file called `<plugin_name>/daos.lua` inside your
plugin folder. The `daos.lua` file should return a table containing one or more
schemas. For example:

```lua
-- daos.lua
local typedefs = require "kong.db.schema.typedefs"

return {
  -- this plugin only results in one custom DAO, named `keyauth_credentials`:
  keyauth_credentials = {
    name               = "keyauth_credentials", -- the actual table in the database
    endpoint_key       = "key",
    primary_key        = { "id" },
    cache_key          = { "key" },
    generate_admin_api = true,
    fields = {
      {
        -- a value to be inserted by the DAO itself
        -- (think of serial id and the uniqueness of such required here)
        id = typedefs.uuid,
      },
      {
        -- also interted by the DAO itself
        created_at = typedefs.auto_timestamp_s,
      },
      {
        -- a foreign key to a consumer's id
        consumer = {
          type      = "foreign",
          reference = "consumers",
          default   = ngx.null,
          on_delete = "cascade",
        },
      },
      {
        -- a unique API key
        key = {
          type      = "string",
          required  = false,
          unique    = true,
          auto      = true,
        },
      },
    },
  },
}
```

This example `daos.lua` file introduces a single schema called `keyauth_credentials`.

Here is a description of some top-level properties:

Name	Type	Description

  name
  string (required)
  It will be used to determine the DAO name (kong.db.[name]).

  primary_key
  table (required)

    Field names forming the entity's primary key.
    Schemas support composite keys, even if most Kong core entities currently use an UUID named
    id. If you are using Cassandra and need a composite key, it should have the same
    fields as the partition key.

endpoint_key
  string (optional)

    The name of the field used as an alternative identifier on the Admin API.
    On the example above, key is the endpoint_key. This means that a credential with
    id = 123 and key = "foo" could be referenced as both
    /keyauth_credentials/123 and /keyauth_credentials/foo.

  cache_key
  table (optional)

    Contains the name of the fields used for generating the cache_key, a string which must
    unequivocally identify the entity inside Kong's cache. A unique field, like key in your example,
    is usually good candidate. In other cases a combination of several fields is preferable.

  fields
  table

    Each field definition is a table with a single key, which is the field's name. The table value is
    a subtable containing the field's attributes, some of which will be explained below.

Many field attributes encode *validation rules*. When attempting to insert or update entities using
the DAO, these validations will be checked, and an error returned if the provided input doesn't conform
to them.

The `typedefs` variable (obtained by requiring `kong.db.schema.typedefs`) is a table containing
a lot of useful type definitions and aliases, including `typedefs.uuid`, the most usual type for the primary key,
and `typedefs.auto_timestamp_s`, for `created_at` fields. It is used extensively when defining fields.

Here's a non-exhaustive explanation of some of the field attributes available:

Attribute name	type	Description

  type
  string

    Schemas support the following scalar types: "string", "integer", "number" and
    "boolean". Compound types like "array", "record", or "set" are
    also supported.

    In additon to these values, the type attribute can also take the special "foreign" value,
    which denotes a foreign relationship.

    Each field will need to be backed by database fields of appropriately similar types, created via migrations.

    type is the only required attribute for all field definitions.

  default
  any (matching with type attribute)

    Specifies the value the field will have when attempting to insert it, if no value was provided.
    Default values are always set via Lua, never by the underlying database. It is thus not recommended to set
    any default values on fields in migrations.

  required
  boolean

    When set to true on a field, an error will be thrown when attempting to insert an entity lacking a value
    for said field (unless the field in question has a default value).

  unique
  boolean

When set to true on a field, an error will be thrown when attempting to insert an entity on the database,
    but another entity already has the given value on said field.

This attribute must be backed up by declaring fields as UNIQUE in migrations when using
    PostgreSQL. The Cassandra strategy does a check in Lua before attempting inserts, so it doesn't require any special treatment.

  auto
  boolean

  When attempting to insert an entity without providing a value for this a field where auto is set to true,

If type == "uuid", the field will take a random UUID as value.

If type == "string", the field will take a random string.

If the field name is created_at or updated_at, the field will take the current time when
    inserting / updating, as appropriate.

  reference
  string
  Required for fields of type foreign. The given string must be the name of an existing schema,
    to which the foreign key will "point to". This means that if a schema B has a foreign key pointing to schema A,
    then A needs to be loaded before B.

  on_delete
  string

    Optional and exclusive for fields of type foreign. It dictates what must happen
    with entities linked by a foreign key when the entity being referenced is deleted. It can have three possible
    values:

"cascade": When the linked entity is deleted, all the dependent entities must also be deleted.

"null": When the linked entity is deleted, all the dependent entities will have their foreign key
      field set to null.

"restrict": Attempting to delete an entity with linked entities will result in an error.

    In Cassandra this is handled with pure Lua code, but in PostgreSQL it will be necessary to declare the references
    as ON DELETE CASCADE/NULL/RESTRICT in a migration.

To learn more about schemas, see:

* The source code of [typedefs.lua](https://github.com/Kong/kong/blob/{{page.kong_version | replace: "x", "0"}}/kong/db/schema/typedefs.lua)
  to get an idea of what's provided there by default.
* [The Core Schemas](https://github.com/Kong/kong/tree/{{page.kong_version | replace: "x", "0"}}/kong/db/schema/entities)
  to see examples of some other field attributes not discussed here.
* [All the `daos.lua` files for embedded plugins](https://github.com/search?utf8=%E2%9C%93&q=repo%3Akong%2Fkong+path%3A%2Fkong%2Fplugins+filename%3Adaos.lua),
  especially [the key-auth one](https://github.com/Kong/kong/blob/{{page.kong_version | replace: "x", "0"}}/kong/plugins/key-auth/daos.lua),
  which was used for this guide as an example.

---

## The custom DAO

The schemas are not used directly to interact with the database. Instead, a DAO
is built for each valid schema. A DAO takes the name of the schema it wraps, and is
accessible through the `kong.db` interface.

For the example schema above, the DAO generated would be available for plugins
via `kong.db.keyauth_credentials`.

### Selecting an entity

``` lua
local entity, err, err_t = kong.db.<name>:select(primary_key)
```

Attempts to find an entity in the database and return it. Three things can happen:

* The entity was found. In this case, it is returned as a regular Lua table.
* An error occurred - for example the connection with the database was lost. In that
  case the first returned value will be `nil`, the second one will be a string
  describing the error, and the last one will be the same error in table form.
* An error does not occur but the entity is not found. Then the function will
  just return `nil`, with no error.

Example of usage:

``` lua
local entity, err = kong.db.keyauth_credentials:select({
  id = "c77c50d2-5947-4904-9f37-fa36182a71a9"
})

if err then
  kong.log.err("Error when inserting keyauth credential: " .. err)
  return nil
end

if not entity then
  kong.log.err("Could not find credential.")
  return nil
end
```

### Iterating over all the entities

``` lua
for entity, err on kong.db.<name>:each(entities_per_page) do
  if err then
    ...
  end
  ...
end
```

This method efficiently iterates over all the entities in the database by making paginated
requests. The `entities_per_page` parameter, which defaults to `100`, controls how many
entities per page are returned.

On each iteration, a new `entity` will be returned or, if there is any error, the `err`
variable will be filled up with an error. The recommended way to iterate is checking `err` first,
and otherwise assume that `entity` is present.

Example of usage:

``` lua
for credential, err on kong.db.keyauth_credentials:each(1000) do
  if err then
    kong.log.err("Error when iterating over keyauth credentials: " .. err)
    return nil
  end

  kong.log("id: " .. credential.id)
end
```

This example iterates over the credentials in pages of 1000 items, logging their ids unless
an error happens.

### Inserting an entity

``` lua
local entity, err, err_t = kong.db.<name>:insert(<values>)
```

Inserts an entity in the database, and returns a copy of the inserted entity, or
`nil`, an error message (a string) and a table describing the error in table form.

When the insert is successful, the returned entity contains the extra values produced by
`default` and `auto`.

The following example uses the `keyauth_credentials` DAO to insert a credential for a given
Consumer, setting its `key` to `"secret"`. Notice the syntax for referencing foreign keys.

``` lua
local entity, err = kong.db.keyauth_credentials:insert({
  consumer = { id = "c77c50d2-5947-4904-9f37-fa36182a71a9" },
  key = "secret",
})

if not entity then
  kong.log.err("Error when inserting keyauth credential: " .. err)
  return nil
end
```

The returned entity, assuming no error happened will have `auto`-filled fields, like `id` and `created_at`.

### Updating an entity

``` lua
local entity, err, err_t = kong.db.<name>:update(primary_key, <values>)
```

Updates an existing entity, provided it can be found using the provided primary key and a set of values.

The returned entity will be the entity after the update takes place, or `nil` + an error message + an error table.

The following example modifies the `key` field of an existing credential given the credential's id:

``` lua
local entity, err = kong.db.keyauth_credentials:update({
  { id = "2b6a2022-770a-49df-874d-11e2bf2634f5" },
  { key = "updated_secret" },
})

if not entity then
  kong.log.err("Error when updating keyauth credential: " .. err)
  return nil
end
```

Notice how the syntax for specifying a primary key is similar to the one used to specify a foreign key.

### Upserting an entity

``` lua
local entity, err, err_t = kong.db.<name>:upsert(primary_key, <values>)
```

`upsert` is a mixture of `insert` and `update`:

* When the provided `primary_key` identifies an existing entity, it works like `update`.
* When the provided `primary_key` does not identify an existing entity, it works like `insert`

Given this code:

``` lua
local entity, err = kong.db.keyauth_credentials:upsert({
  { id = "2b6a2022-770a-49df-874d-11e2bf2634f5" },
  { consumer = { id = "a96145fb-d71e-4c88-8a5a-2c8b1947534c" } },
})

if not entity then
  kong.log.err("Error when upserting keyauth credential: " .. err)
  return nil
end
```

Two things can happen:

* If a credential with id `2b6a2022-770a-49df-874d-11e2bf2634f5` exists,
  then this code will attempt to set its Consumer to the provided one.
* If the credential does not exist, then this code is attempting to create
  a new credential, with the given id and Consumer.

### Deleting an entity

``` lua
local ok, err, err_t = kong.db.<name>:delete(primary_key)
```

Attempts to delete the entity identified by `primary_key`. It returns `true`
if the entity *doesn't exist* after calling this method, or `nil` + error +
error table if an error is detected.

Notice that calling `delete` will succeed if the entity didn't exist *before
calling it*. This is for performance reasons - we want to avoid doing a
read-before-delete if we can avoid it. If you want to do this check, you
must do it manually, by checking with `select` before invoking `delete`.

Example:

``` lua
local ok, err = kong.db.keyauth_credentials:delete({
  { id = "2b6a2022-770a-49df-874d-11e2bf2634f5" }
})

if not ok then
  kong.log.err("Error when deleting keyauth credential: " .. err)
  return nil
end
```

---

## Caching custom entities

Sometimes custom entities are required on every request/response, which in turn
triggers a query on the datastore every time. This is very inefficient because
querying the datastore adds latency and slows the request/response down, and
the resulting increased load on the datastore could affect the datastore
performance itself and, in turn, other Kong nodes.

When a custom entity is required on every request/response it is good practice
to cache it in-memory by leveraging the in-memory cache API provided by Kong.

The next chapter will focus on caching custom entities, and invalidating them
when they change in the datastore: [Caching custom entities]({{page.book.next}}).

---

Next: [Caching custom entities ›]({{page.book.next}})

[Admin API]: /enterprise/{{page.kong_version}}/admin-api/
[Plugin Development Kit]: /enterprise/{{page.kong_version}}/pdk


text:
<?php

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\YamlFileDumper;

class YamlFileDumperTest extends \PHPUnit_Framework_TestCase {

    public function testDump() {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'));

        $tempDir = sys_get_temp_dir();
        $dumper = new YamlFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__ . '/../fixtures/resources.yml'), file_get_contents($tempDir . '/messages.en.yml'));

        unlink($tempDir . '/messages.en.yml');
    }

}


text:
Although Apache ActiveMQ Artemis provides a JMS agnostic messaging API, many
users will be more comfortable using JMS.

JMS is a very popular API standard for messaging, and most messaging systems
provide a JMS API. If you are completely new to JMS we suggest you follow the
[Oracle JMS
tutorial](https://docs.oracle.com/javaee/7/tutorial/partmessaging.htm) - a full
JMS tutorial is out of scope for this guide.

Apache ActiveMQ Artemis also ships with a wide range of examples, many of which
demonstrate JMS API usage. A good place to start would be to play around with
the simple JMS Queue and Topic example, but we also provide examples for many
other parts of the JMS API. A full description of the examples is available in
[Examples](examples.md).

In this section we'll go through the main steps in configuring the server for
JMS and creating a simple JMS program. We'll also show how to configure and use
JNDI, and also how to use JMS with Apache ActiveMQ Artemis without using any
JNDI.

## A simple ordering system

For this chapter we're going to use a very simple ordering system as our
example. It is a somewhat contrived example because of its extreme simplicity,
but it serves to demonstrate the very basics of setting up and using JMS.

We will have a single JMS Queue called `OrderQueue`, and we will have a single
`MessageProducer` sending an order message to the queue and a single
`MessageConsumer` consuming the order message from the queue.

The queue will be a `durable` queue, i.e. it will survive a server restart or
crash. We also want to pre-deploy the queue, i.e. specify the queue in the
server configuration so it is created automatically without us having to
explicitly create it from the client.

## JNDI

The JMS specification establishes the convention that *administered objects*
(i.e. JMS queue, topic and connection factory instances) are made available via
the JNDI API. Brokers are free to implement JNDI as they see fit assuming the
implementation fits the API. Apache ActiveMQ Artemis does not have a JNDI
server. Rather, it uses a client-side JNDI implementation that relies on
special properties set in the environment to construct the appropriate JMS
objects. In other words, no objects are stored in JNDI on the Apache ActiveMQ
Artemis server, instead they are simply instantiated on the client based on the
provided configuration. Let's look at the different kinds of administered
objects and how to configure them.

> **Note:**
>
> The following configuration properties *are strictly required when Apache
> ActiveMQ Artemis is running in stand-alone mode*. When Apache ActiveMQ
> Artemis is integrated to an application server (e.g. Wildfly) the application
> server itself will almost certainly provide a JNDI client with its own
> properties.

### ConnectionFactory JNDI

A JMS connection factory is used by the client to make connections to the
server. It knows the location of the server it is connecting to, as well as
many other configuration parameters.

Here's a simple example of the JNDI context environment for a client looking up
a connection factory to access an *embedded* instance of Apache ActiveMQ
Artemis:

```properties
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory
connectionFactory.invmConnectionFactory=vm://0
```

In this instance we have created a connection factory that is bound to
`invmConnectionFactory`, any entry with prefix `connectionFactory.` will create
a connection factory.

In certain situations there could be multiple server instances running within a
particular JVM. In that situation each server would typically have an InVM
acceptor with a unique server-ID. A client using JMS and JNDI can account for
this by specifying a connction factory for each server, like so:

```properties
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory
connectionFactory.invmConnectionFactory0=vm://0
connectionFactory.invmConnectionFactory1=vm://1
connectionFactory.invmConnectionFactory2=vm://2
```

Here is a list of all the supported URL schemes:

- `vm`
- `tcp`
- `udp`
- `jgroups`

Most clients won't be connecting to an embedded broker. Clients will most
commonly connect across a network a remote broker. Here's a simple example of a
client configuring a connection factory to connect to a remote broker running
on myhost:5445:

```properties
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory
connectionFactory.ConnectionFactory=tcp://myhost:5445
```

In the example above the client is using the `tcp` scheme for the provider URL.
A client may also specify multiple comma-delimited host:port combinations in
the URL (e.g.  `(tcp://remote-host1:5445,remote-host2:5445)`). Whether there is
one or many host:port combinations in the URL they are treated as the *initial
connector(s)* for the underlying connection.

The `udp` scheme is also supported which should use a host:port combination
that matches the `group-address` and `group-port` from the corresponding
`broadcast-group` configured on the ActiveMQ Artemis server(s).

Each scheme has a specific set of properties which can be set using the
traditional URL query string format (e.g.
`scheme://host:port?key1=value1&key2=value2`) to customize the underlying
transport mechanism. For example, if a client wanted to connect to a remote
server using TCP and SSL it would create a connection factory like so,
`tcp://remote-host:5445?ssl-enabled=true`.

All the properties available for the `tcp` scheme are described in [the
documentation regarding the Netty
transport](configuring-transports.md#configuring-the-netty-transport).

Note if you are using the `tcp` scheme and multiple addresses then a query can
be applied to all the url's or just to an individual connector, so where you
have

- `(tcp://remote-host1:5445?httpEnabled=true,remote-host2:5445?httpEnabled=true)?clientID=1234`

then the `httpEnabled` property is only set on the individual connectors where
as the `clientId` is set on the actual connection factory. Any connector
specific properties set on the whole URI will be applied to all the connectors.

The `udp` scheme supports 4 properties:

- `localAddress` - If you are running with multiple network
  interfaces on the same machine, you may want to specify that the
  discovery group listens only only a specific interface. To do this
  you can specify the interface address with this parameter.

- `localPort` - If you want to specify a local port to which the
  datagram socket is bound you can specify it here. Normally you would
  just use the default value of -1 which signifies that an anonymous
  port should be used. This parameter is always specified in
  conjunction with `localAddress`.

- `refreshTimeout` - This is the period the discovery group waits after
  receiving the last broadcast from a particular server before removing that
  servers connector pair entry from its list. You would normally set this to a
  value significantly higher than the broadcast-period on the broadcast group
  otherwise servers might intermittently disappear from the list even though they
  are still broadcasting due to slight differences in timing. This parameter is
  optional, the default value is 10000 milliseconds (10 seconds).

- `discoveryInitialWaitTimeout` - If the connection factory is used immediately
  after creation then it may not have had enough time to received broadcasts
  from all the nodes in the cluster. On first usage, the connection factory will
  make sure it waits this long since creation before creating the first
  connection. The default value for this parameter is 10000 milliseconds.

Lastly, the `jgroups` scheme is supported which provides an alternative to the
`udp` scheme for server discovery. The URL pattern is either
`jgroups://channelName?file=jgroups-xml-conf-filename`
where`jgroups-xml-conf-filename` refers to an XML file on the classpath that
contains the JGroups configuration or it can be
`jgroups://channelName?properties=some-jgroups-properties`. In both instance
the `channelName` is the name given to the jgroups channel created.

The `refreshTimeout` and `discoveryInitialWaitTimeout` properties are supported
just like with `udp`.

The default type for the default connection factory is of type
`javax.jms.ConnectionFactory`.  This can be changed by setting the type like so

```properties
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory
java.naming.provider.url=tcp://localhost:5445?type=CF
```

In this example it is still set to the default, below shows a list of types
that can be set.

#### Configuration for Connection Factory Types

type | interface
--- |---
CF (default) | javax.jms.ConnectionFactory
XA_CF | javax.jms.XAConnectionFactory
QUEUE_CF | javax.jms.QueueConnectionFactory
QUEUE_XA_CF | javax.jms.XAQueueConnectionFactory
TOPIC_CF | javax.jms.TopicConnectionFactory
TOPIC_XA_CF | javax.jms.XATopicConnectionFactory

### Destination JNDI

JMS destinations are also typically looked up via JNDI. As with connection
factories, destinations can be configured using special properties in the JNDI
context environment. The property *name* should follow the pattern:
`queue.<jndi-binding>` or `topic.<jndi-binding>`.  The property *value* should
be the name of the queue hosted by the Apache ActiveMQ Artemis server. For
example, if the server had a JMS queue configured like so:

```xml
<address name="OrderQueue">
   <queue name="OrderQueue"/>
</address>
```

And if the client wanted to bind this queue to "queues/OrderQueue" then the
JNDI properties would be configured like so:

```properties
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory
java.naming.provider.url=tcp://myhost:5445
queue.queues/OrderQueue=OrderQueue
```

It is also possible to look-up JMS destinations which haven't been configured
explicitly in the JNDI context environment. This is possible using
`dynamicQueues/` or `dynamicTopics/` in the look-up string. For example, if the
client wanted to look-up the aforementioned "OrderQueue" it could do so simply
by using the string "dynamicQueues/OrderQueue".  Note, the text that follows
`dynamicQueues/` or `dynamicTopics/` must correspond *exactly* to the name of
the destination on the server.

### The code

Here's the code for the example:

First we'll create a JNDI initial context from which to lookup our JMS objects.
If the above properties are set in `jndi.properties` and it is on the classpath
then any new, empty `InitialContext` will be initialized using those
properties:

```java
InitialContext ic = new InitialContext();

//Now we'll look up the connection factory from which we can create
//connections to myhost:5445:

ConnectionFactory cf = (ConnectionFactory)ic.lookup("ConnectionFactory");

//And look up the Queue:

Queue orderQueue = (Queue)ic.lookup("queues/OrderQueue");

//Next we create a JMS connection using the connection factory:

Connection connection = cf.createConnection();

//And we create a non transacted JMS Session, with AUTO\_ACKNOWLEDGE
//acknowledge mode:

Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

//We create a MessageProducer that will send orders to the queue:

MessageProducer producer = session.createProducer(orderQueue);

//And we create a MessageConsumer which will consume orders from the
//queue:

MessageConsumer consumer = session.createConsumer(orderQueue);

//We make sure we start the connection, or delivery won't occur on it:

connection.start();

//We create a simple TextMessage and send it:

TextMessage message = session.createTextMessage("This is an order");
producer.send(message);

//And we consume the message:

TextMessage receivedMessage = (TextMessage)consumer.receive();
System.out.println("Got order: " + receivedMessage.getText());
```

It is as simple as that. For a wide range of working JMS examples please
see the examples directory in the distribution.

> **Warning**
>
> Please note that JMS connections, sessions, producers and consumers are
> *designed to be re-used*.
>
> It is an anti-pattern to create new connections, sessions, producers and
> consumers for each message you produce or consume. If you do this, your
> application will perform very poorly. This is discussed further in the
> section on performance tuning [Performance Tuning](perf-tuning.md).

## Directly instantiating JMS Resources without using JNDI

Although it is a very common JMS usage pattern to lookup JMS *Administered
Objects* (that's JMS Queue, Topic and ConnectionFactory instances) from JNDI,
in some cases you just think "Why do I need JNDI?  Why can't I just instantiate
these objects directly?"

With Apache ActiveMQ Artemis you can do exactly that. Apache ActiveMQ Artemis
supports the direct instantiation of JMS Queue, Topic and ConnectionFactory
instances, so you don't have to use JNDI at all.

> For a full working example of direct instantiation please look at the
> [Instantiate JMS Objects
> Directly](examples.md#instantiate-jms-objects-directly) example under the JMS
> section of the examples.

Here's our simple example, rewritten to not use JNDI at all:

We create the JMS ConnectionFactory object via the ActiveMQJMSClient Utility
class, note we need to provide connection parameters and specify which
transport we are using, for more information on connectors please see
[Configuring the Transport](configuring-transports.md).

```java
TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName());

ConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF,transportConfiguration);

//We also create the JMS Queue object via the ActiveMQJMSClient Utility
//class:

Queue orderQueue = ActiveMQJMSClient.createQueue("OrderQueue");

//Next we create a JMS connection using the connection factory:

Connection connection = cf.createConnection();

//And we create a non transacted JMS Session, with AUTO\_ACKNOWLEDGE
//acknowledge mode:

Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

//We create a MessageProducer that will send orders to the queue:

MessageProducer producer = session.createProducer(orderQueue);

//And we create a MessageConsumer which will consume orders from the
//queue:

MessageConsumer consumer = session.createConsumer(orderQueue);

//We make sure we start the connection, or delivery won't occur on it:

connection.start();

//We create a simple TextMessage and send it:

TextMessage message = session.createTextMessage("This is an order");
producer.send(message);

//And we consume the message:

TextMessage receivedMessage = (TextMessage)consumer.receive();
System.out.println("Got order: " + receivedMessage.getText());
```

## Setting The Client ID

This represents the client id for a JMS client and is needed for creating
durable subscriptions. It is possible to configure this on the connection
factory and can be set via the `clientId` element. Any connection created by
this connection factory will have this set as its client id.

## Setting The Batch Size for DUPS_OK

When the JMS acknowledge mode is set to `DUPS_OK` it is possible to configure
the consumer so that it sends acknowledgements in batches rather that one at a
time, saving valuable bandwidth. This can be configured via the connection
factory via the `dupsOkBatchSize` element and is set in bytes. The default is
1024 \* 1024 bytes = 1 MiB.

## Setting The Transaction Batch Size

When receiving messages in a transaction it is possible to configure the
consumer to send acknowledgements in batches rather than individually saving
valuable bandwidth. This can be configured on the connection factory via the
`transactionBatchSize` element and is set in bytes.  The default is 1024 \*
1024.

## Setting The Destination Cache

Many frameworks such as Spring resolve the destination by name on every
operation, this can cause a performance issue and extra calls to the broker, in
a scenario where destinations (addresses) are permanent broker side, such as
they are managed by a platform or operations team.  using `cacheDestinations`
element, you can toggle on the destination cache to improve the performance and
reduce the calls to the broker.  This should not be used if destinations
(addresses) are not permanent broker side, as in dynamic creation/deletion.