text:
package org.jgroups.protocols.jzookeeper;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.View;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.ManagedOperation;
import org.jgroups.stack.Protocol;
import org.jgroups.util.MessageBatch;
/*
 * Zab_0 is the same implemetation as Zab_0, but the follower will ack locally
 * but the leader still sends commit message to follower, but it is ignored by follower
 *
 */
public class Zab2PhasesWithCommit extends Protocol {

	private final AtomicLong                  zxid=new AtomicLong(0);
    private ExecutorService                     executor;
    private Address                           local_addr;
    private volatile Address                  leader;
    private int QUEUE_CAPACITY = 500;
    private volatile View                     view;
    private volatile boolean                  is_leader=false;
    private List<Address>                       zabMembers = Collections.synchronizedList(new ArrayList<Address>());
	private long                                lastZxidProposed=0, lastZxidCommitted=0;
    private final Set<MessageId>                requestQueue =Collections.synchronizedSet(new HashSet<MessageId>());
	private Map<Long, ZabHeader> queuedCommitMessage = new HashMap<Long, ZabHeader>();
	private List<Integer> latencies = new ArrayList<Integer>();
	private List<Integer> avgLatencies = new ArrayList<Integer>();
	private List<String> avgLatenciesTimer = new ArrayList<String>();

    private final Map<Long, ZabHeader> queuedProposalMessage = Collections.synchronizedMap(new HashMap<Long, ZabHeader>());
    private final LinkedBlockingQueue<ZabHeader> queuedMessages =
	        new LinkedBlockingQueue<ZabHeader>();
	private ConcurrentMap<Long, Proposal> outstandingProposals = new ConcurrentHashMap<Long, Proposal>();
    private final Map<MessageId, Message> messageStore = Collections.synchronizedMap(new HashMap<MessageId, Message>());
    private Calendar cal = Calendar.getInstance();
    private int index=-1;
    private volatile boolean                  running=true;
    private long startThroughputTime = 0;
    private long endThroughputTime = 0;
    private volatile boolean startThroughput = false;
    private static PrintWriter outFile;
    private final static String outDir="/home/pg/p13/a6915654/ZAB/";
	private  AtomicInteger                  numReqDeviverd=new AtomicInteger(0);
	private  AtomicInteger                  numRequest=new AtomicInteger(0);
	private long rateInterval = 10000;
	private long rateCount = 0;
	private long currentCpuTime = 0, rateCountTime = 0, lastTimer = 0, lastCpuTime = 0;
	private int lastArrayIndex = 0, lastArrayIndexUsingTime = 0 ;
	private long timeInterval = 500;
	private int lastFinished = 0;
	private Timer timer;
	private AtomicLong countMessageLeader = new AtomicLong(0);
	private long countMessageFollower = 0;
	private long countTotalMessagesFollowers = 0;
	private AtomicLong warmUpRequest = new AtomicLong(0);
	private static long warmUp = 10000;
    private int largeLatCount = 0;
    private List<String> largeLatencies = new ArrayList<String>();
    private List<String> largeLatenciesNano = new ArrayList<String>();
    private boolean is_warmUp=true;

    public Zab2PhasesWithCommit(){

    }

    @ManagedAttribute
    public boolean isleaderinator() {return is_leader;}
    public Address getleaderinator() {return leader;}
    public Address getLocalAddress() {return local_addr;}

    @ManagedOperation
    public String printStats() {
        return dumpStats().toString();
    }

    @Override
    public void start() throws Exception {
        super.start();
        running=true;
	    executor = Executors.newSingleThreadExecutor();
	    executor.execute(new FollowerMessageHandler(this.id));
	    log.setLevel("trace");
	    this.outFile = new PrintWriter(new BufferedWriter(new FileWriter
				(outDir+InetAddress.getLocalHost().getHostName()+"Zab.log",true)));

    }

    public void reset(Address client) {
    	zxid.set(0); lastZxidProposed=0;
    	lastZxidCommitted=0; requestQueue.clear();
    	queuedCommitMessage.clear(); queuedProposalMessage.clear();
        queuedMessages.clear(); outstandingProposals.clear();
        messageStore.clear(); latencies.clear();
        avgLatencies.clear(); avgLatenciesTimer.clear();
        numReqDeviverd= new AtomicInteger(0); numRequest= new AtomicInteger(0);
        startThroughputTime = 0; endThroughputTime = 0;
        startThroughput = false; currentCpuTime = 0;
        rateCountTime = 0; lastTimer = 0;
        lastCpuTime = 0; lastArrayIndex = 0;
    	lastArrayIndexUsingTime = 0 ; lastFinished = 0;
    	countMessageLeader = new AtomicLong(0);//	 timer.cancel();
    	largeLatCount=0; countMessageFollower=0;
    	countTotalMessagesFollowers=0; rateCount=0;
    	is_warmUp = false;
    	try {
			this.outFile = new PrintWriter(new BufferedWriter(new FileWriter
					(outDir+InetAddress.getLocalHost().getHostName()+"Zab.log",true)));
    	}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	log.info("Reset done");
    	MessageId messageId = new MessageId(local_addr,
				-10, System.currentTimeMillis());
    	ZabHeader startTest = new ZabHeader(ZabHeader.STARTREALTEST, messageId);
        Message confirmClient=new Message(client).putHeader(this.id, startTest);
		down_prot.down(new Event(Event.MSG, confirmClient));

    }
    @Override
    public void stop() {
        running=false;
        executor.shutdown();
        super.stop();
    }

    public Object down(Event evt) {
        switch(evt.getType()) {
            case Event.MSG:
            	Message m = (Message) evt.getArg();
                handleClientRequest(m);
                return null; // don't pass down
            case Event.SET_LOCAL_ADDRESS:
                local_addr=(Address)evt.getArg();
                break;
        }
        return down_prot.down(evt);
    }

    public Object up(Event evt) {
        Message msg = null;
        ZabHeader hdr;

        switch(evt.getType()) {
            case Event.MSG:
                msg=(Message)evt.getArg();
                hdr=(ZabHeader)msg.getHeader(this.id);
                if(hdr == null){
                    break; // pass up
                }
                switch(hdr.getType()) {
                   case ZabHeader.START_SENDING:
                	   if(!zabMembers.contains(local_addr))
                		   return up_prot.up(new Event(Event.MSG, msg));
                	   break;
                	case ZabHeader.REQUEST:
  //              		if (!is_leader && !startThroughput){
//                			startThroughput = true;
//                			startThroughputTime = System.currentTimeMillis();
//                		      timer = new Timer();
//                			  timer.schedule(new ResubmitTimer(), timeInterval, timeInterval);
	                	    //numRequest.incrementAndGet();
                    		//queuedMessages.add(hdr);
                		//}
	                		forwardToLeader(msg);
                		break;
                	case ZabHeader.RESET:
                		 reset(msg.getSrc());
  	                	break;
                    case ZabHeader.FORWARD:
//                    	if (warmUpRequest.get() <= warmUp){
//                    		warmUpRequest.incrementAndGet();
//                    		queuedMessages.add(hdr);
//                		}
                		// if (warmUpRequest.get() > warmUp && !startThroughput){
//                    	`startThroughputTime = System.currentTimeMillis();
//                		   // timer = new Timer();
//                			//timer.schedule(new ResubmitTimer(), timeInterval, timeInterval);
	                	    //numRequest.incrementAndGet();
                    		//queuedMessages.add(hdr);
                		//}
                		//else if (startThroughput){
	              	    //numRequest.incrementAndGet();
                   		queuedMessages.add(hdr);

                		//}
//                    	if(!is_leader) {
//                			if(log.isErrorEnabled())
//                				//log.error("[" + local_addr + "] "+ ": non-Leader; dropping FORWARD request from " + msg.getSrc());
//                			break;
//                		 }

                	    //hdr.getMessageId().setStartTime(System.currentTimeMillis());
                		//queuedMessages.add(hdr);
                		break;
                    case ZabHeader.PROPOSAL:
                    	if (!is_leader){
	                   		if (!is_warmUp && !startThroughput){
	                			startThroughput = true;
	                			startThroughputTime = System.currentTimeMillis();
	                		    //timer = new Timer();
	                			//timer.schedule(new ResubmitTimer(), timeInterval, timeInterval);

	                		}
	                   		//hdr.getMessageId().setStartTime(System.currentTimeMillis());
	            			sendACK(msg, hdr);
	            		}
	                   	break;
                    case ZabHeader.ACK:
                		if (is_leader){
                			processACK(msg, msg.getSrc());
                		}
                		break;
                    case ZabHeader.COMMIT:
                    		//deliver(hdr.getZxid());
                		 break;
                    case ZabHeader.STATS:
                    	//if(is_leader)
                    		printMZabStats();
                    	break;
                    case ZabHeader.COUNTMESSAGE:
                    		sendTotalABMwssages(hdr);
                    		log.info("Yes, I recieved count request");
                    	break;
                    case ZabHeader.STARTREALTEST:
                    	if(!zabMembers.contains(local_addr))
                			return up_prot.up(new Event(Event.MSG, msg));
                    case ZabHeader.RESPONSE:
                    	handleOrderingResponse(hdr);

            }
                return null;
              case Event.VIEW_CHANGE:
              handleViewChange((View)evt.getArg());
              break;

        }

        return up_prot.up(evt);
    }

    public void up(MessageBatch batch) {
        for(Message msg: batch) {
            if(msg.isFlagSet(Message.Flag.NO_TOTAL_ORDER) || msg.isFlagSet(Message.Flag.OOB) || msg.getHeader(id) == null)
                continue;
            batch.remove(msg);

            try {
                up(new Event(Event.MSG, msg));
            }
            catch(Throwable t) {
                log.error("failed passing up message", t);
            }
        }

        if(!batch.isEmpty())
            up_prot.up(batch);
    }

    /* --------------------------------- Private Methods ----------------------------------- */

	private void handleClientRequest(Message message) {
		ZabHeader clientHeader = ((ZabHeader) message.getHeader(this.id));

		if (clientHeader != null
				&& clientHeader.getType() == ZabHeader.START_SENDING) {
			for (Address client : view.getMembers()) {
				if (log.isDebugEnabled())
					log.info("Address to check " + client);
				if (!zabMembers.contains(client)) {
					if (log.isDebugEnabled())
						log.info("Address to check is not zab Members, will send start request to"
								+ client + " " + getCurrentTimeStamp());
					message.setDest(client);
					down_prot.down(new Event(Event.MSG, message));
				}
			}
		}

		else if (clientHeader != null
				&& clientHeader.getType() == ZabHeader.RESET) {

			for (Address server : zabMembers) {
				// message.setDest(server);
				Message resetMessage = new Message(server).putHeader(this.id,
						clientHeader);
				resetMessage.setSrc(local_addr);
				down_prot.down(new Event(Event.MSG, resetMessage));
			}
		}

		else if (clientHeader != null
				&& clientHeader.getType() == ZabHeader.STATS) {

			for (Address server : zabMembers) {
				// message.setDest(server);
				Message statsMessage = new Message(server).putHeader(this.id,
						clientHeader);
				down_prot.down(new Event(Event.MSG, statsMessage));
			}
		}

		else if (clientHeader != null
				&& clientHeader.getType() == ZabHeader.COUNTMESSAGE) {
			for (Address server : zabMembers) {
				if(!server.equals(zabMembers.get(0))){
					Message countMessages = new Message(server).putHeader(this.id,
							clientHeader);
					down_prot.down(new Event(Event.MSG, countMessages));
				}
			}

		}

		else if (!clientHeader.getMessageId().equals(null)
				&& clientHeader.getType() == ZabHeader.REQUEST) {
			Address destination = null;
			messageStore.put(clientHeader.getMessageId(), message);
			ZabHeader hdrReq = new ZabHeader(ZabHeader.REQUEST,
					clientHeader.getMessageId());
			++index;
			if (index > 2)
				index = 0;
			destination = zabMembers.get(index);
			Message requestMessage = new Message(destination).putHeader(
					this.id, hdrReq);
			down_prot.down(new Event(Event.MSG, requestMessage));
		}

	}

    private void handleViewChange(View v) {
        List<Address> mbrs=v.getMembers();
        leader=mbrs.get(0);
        if (leader.equals(local_addr)){
        	is_leader = true;
        }
        if (mbrs.size() == 3){
        	zabMembers.addAll(v.getMembers());
        }
        if (mbrs.size() > 3 && zabMembers.isEmpty()){
        	for (int i = 0; i < 3; i++) {
        		zabMembers.add(mbrs.get(i));
			}

        }
        if(mbrs.isEmpty()) return;

        if(view == null || view.compareTo(v) < 0)
            view=v;
        else
            return;
    }

    private long getNewZxid(){
    	return zxid.incrementAndGet();
    }

    private void forwardToLeader(Message msg) {
    	ZabHeader hdrReq = (ZabHeader) msg.getHeader(this.id);
 	   requestQueue.add(hdrReq.getMessageId());
    	if (!is_warmUp && is_leader && !startThroughput){
			startThroughput = true;
			startThroughputTime = System.currentTimeMillis();
		      //timer = new Timer();
			  //timer.schedule(new ResubmitTimer(), timeInterval, timeInterval);
		}

	   if (is_leader){
		   hdrReq.getMessageId().setStartTime(System.nanoTime());
		   queuedMessages.add((ZabHeader)msg.getHeader(this.id));
       }
	   else{
		   hdrReq.getMessageId().setStartTime(System.nanoTime());
		   forward(msg);
	   }

   }

    private void forward(Message msg) {
        Address target=leader;
 	    ZabHeader hdrReq = (ZabHeader) msg.getHeader(this.id);
        if(target == null)
            return;

	    try {
	        ZabHeader hdr=new ZabHeader(ZabHeader.FORWARD, hdrReq.getMessageId());
	        Message forward_msg=new Message(target).putHeader(this.id,hdr);
	        down_prot.down(new Event(Event.MSG, forward_msg));
	     }
	    catch(Exception ex) {
	      log.error("failed forwarding message to " + msg, ex);
	    }

    }

    private void sendACK(Message msg, ZabHeader hdrAck){
   		numRequest.incrementAndGet();
    	if (msg == null )
    		return;

    	//ZABHeader hdr = (ZABHeader) msg.getHeader(this.id);
    	if (hdrAck == null)
    		return;

    	//if (hdr.getZxid() != lastZxidProposed + 1){
//            log.info("Got zxid 0x"
//                    + Long.toHexString(hdr.getZxid())
//                    + " expected 0x"
//                    + Long.toHexString(lastZxidProposed + 1));
        //}

    	lastZxidProposed = hdrAck.getZxid();
    	queuedProposalMessage.put(hdrAck.getZxid(), hdrAck);
		ZabHeader hdrACK = new ZabHeader(ZabHeader.ACK, hdrAck.getZxid(), hdrAck.getMessageId());
		Message ACKMessage = new Message(leader).putHeader(this.id, hdrACK);
		if(!is_warmUp)
			countMessageFollower++;
		try{
    		down_prot.down(new Event(Event.MSG, ACKMessage));
         }catch(Exception ex) {
    		log.error("failed sending ACK message to Leader");
    	}
		deliver(hdrAck.getZxid());

    }

    private synchronized void processACK(Message msgACK, Address sender){

    	ZabHeader hdr = (ZabHeader) msgACK.getHeader(this.id);
    	long ackZxid = hdr.getZxid();
		if (lastZxidCommitted >= ackZxid) {
            return;
        }
        Proposal p = outstandingProposals.get(ackZxid);
        if (p == null) {
            return;
        }
		p.AckCount++;
		//if (log.isDebugEnabled()) {
//            log.debug("Count for zxid: " +
//                    Long.toHexString(ackZxid)+" = "+ p.getAckCount());
        //}

		if(isQuorum(p.getAckCount())){
 		   // log.info("Commiting processACK >>>>>>>>>>>>>"+ ackZxid);
            outstandingProposals.remove(ackZxid);
            commit(ackZxid);
		}

		}

    private void commit(long zxidd){
	    ZabHeader hdrOrg = queuedProposalMessage.get(zxidd);
   	    //log.info("Czxid = "+ hdrOrg.getZxid() + " " + getCurrentTimeStamp());
	    synchronized(this){
 	       lastZxidCommitted = zxidd;
 	   }

		   if (hdrOrg == null){
			   log.info("??????????????????????????? Header is null (commit)"+ hdrOrg + " for zxid "+zxidd);
			   return;
		   }

	       ZabHeader hdrCommit = new ZabHeader(ZabHeader.COMMIT, zxidd);
	       Message commitMessage = new Message().putHeader(this.id, hdrCommit);
           for (Address address : zabMembers) {
        	   //if(!address.equals(leader) && startThroughput)
        	   if(!address.equals(leader))
             	  	countMessageLeader.incrementAndGet();
	              Message cpy = commitMessage.copy();
	              cpy.setDest(address);
	   		      //log.info("[" + local_addr + "] "+ "YYYYYYYY sending comit message zxid to = "+zxidd+":"+address);
	              down_prot.down(new Event(Event.MSG, cpy));

           }
           deliver(zxidd);
		   // log.info("Commiting commit >>>>>>>>>>>>>"+ zxidd);

	    }

    private void deliver(long dZxid){
		//ZABHeader hdrOrginal = null;
		//ZABHeader hdr = (ZABHeader) toDeliver.getHeader(this.id);
		//long zxid = hdr.getZxid();

//		log.info("[" + local_addr + "] "
//				+ " recieved commit message (deliver) for zxid="
//				+ hdr.getZxid() + " " + getCurrentTimeStamp());
		//log.info("Dzxid = "+ hdr.getZxid() + " " + getCurrentTimeStamp());
		ZabHeader hdrOrginal = queuedProposalMessage.remove(dZxid);
		if (hdrOrginal == null) {
			 if (log.isInfoEnabled())
				 log.info("$$$$$$$$$$$$$$$$$$$$$ Header is null (deliver)"
					+ hdrOrginal + " for zxid " + dZxid);
			return;
		}
//		log.info("!!!!!!!!!!!! check if (requestQueue.contains(hdrOrginal.getMessageId() (deliver)"
//				+ requestQueue.contains(hdrOrginal.getMessageId()));
		//numReqDeviverd.incrementAndGet();

		queuedCommitMessage.put(dZxid, hdrOrginal);
		//synchronized(latencies){
			if(!is_warmUp){
				numReqDeviverd.incrementAndGet();
				endThroughputTime = System.currentTimeMillis();

				//endThroughputTime = System.currentTimeMillis();
				//long startTime  = hdrOrginal.getMessageId().getStartTime();
				//latencies.add((int)(System.currentTimeMillis() - startTime));
//				rateCount++;
//			if (rateCount == rateInterval){
//				new StatsThread().start();;
//				rateCount=0;
//			}
				//if (numReqDeviverd.get()>=1000000){
				//	timer.cancel();
				//}
			}
	//	}

		if (log.isInfoEnabled())
			log.info("queuedCommitMessage size = " + queuedCommitMessage.size() + " zxid "+dZxid);
		if (requestQueue.contains(hdrOrginal.getMessageId())) {
			//if(!is_warmUp){
			long startTime  = hdrOrginal.getMessageId().getStartTime();
			latencies.add((int)(System.nanoTime() - startTime));
			//log.info("chckkkkkkkkkkkkk "+(endThroughputTime - startTime));

			//}
			//log.info("I am the zab request receiver, "+ hdr.getZxid());
					//+ hdrOrginal.getMessageId().getAddress());
			ZabHeader hdrResponse = new ZabHeader(ZabHeader.RESPONSE, dZxid,
					hdrOrginal.getMessageId());
			Message msgResponse = new Message(hdrOrginal.getMessageId()
					.getOriginator()).putHeader(this.id, hdrResponse);
			down_prot.down(new Event(Event.MSG, msgResponse));

		}

	}

    private void handleOrderingResponse(ZabHeader hdrResponse) {
	        Message message = messageStore.get(hdrResponse.getMessageId());
	        message.putHeader(this.id, hdrResponse);
	        up_prot.up(new Event(Event.MSG, message));

	    }

		private boolean isQuorum(int majority){
	    	return majority >= ((zabMembers.size()/2) + 1)? true : false;
	    }

		private String getCurrentTimeStamp(){
			long timestamp = new Date().getTime();
			cal.setTimeInMillis(timestamp);
			String timeString =
				   new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());

			return timeString;
		}

		private void sendTotalABMwssages(ZabHeader CarryCountMessageLeader){
			if(!is_leader){
			    ZabHeader followerMsgCount = new ZabHeader(ZabHeader.COUNTMESSAGE, countMessageFollower);
		   	    Message requestMessage = new Message(leader).putHeader(this.id, followerMsgCount);
		        down_prot.down(new Event(Event.MSG, requestMessage));
			}
			else{
				long followerMsg = CarryCountMessageLeader.getZxid();
				countTotalMessagesFollowers += followerMsg;
			}

		}

		private void printMZabStats(){
			// print Min, Avg, and Max latency
			List<Long> latAvg = new ArrayList<Long>();
			int count =0;
			long avgTemp =0;
			long min = Long.MAX_VALUE, avg =0, max = Long.MIN_VALUE;
			for (long lat : latencies){
				if (lat < min){
					min = lat;
				}
				if (lat > max){
					max = lat;
				}
				avg+=lat;
				avgTemp+=lat;
				count++;
				if(count>10000){
					latAvg.add(avgTemp/count);
					count=0;
					avgTemp=0;
				}

			}

			outFile.println("Number of Request Recieved = "+(numRequest));
			outFile.println("Number of Request Deliever = " + numReqDeviverd);
			outFile.println("Total ZAB Messages = " + (countMessageLeader.get() + countTotalMessagesFollowers));
			outFile.println("Throughput = " + (numReqDeviverd.get()/(TimeUnit.MILLISECONDS.toSeconds(endThroughputTime-startThroughputTime))));
			outFile.println("Large Latencies count " + largeLatCount);
			outFile.println("Large Latencies " + largeLatencies);
			outFile.println("Latency /Min= " + min + " /Avg= "+ (avg/latencies.size())+
			        " /Max= " +max);
			outFile.println("Latency size= " + latencies.size());
			outFile.println("Latency average rate with interval 100000 = " +
			        avgLatencies);
			outFile.println("Latency average rate with interval 200 MillSec = " +
			        avgLatenciesTimer);
			outFile.println("Latency average rate with No intervel = " +
					latAvg + " numbers avg = " + latAvg.size());

			Collections.sort(latencies);

			int x50=0, x100=0, x150=0, x200=0, x250=0, x300=0, x350=0,x400=0, x450=0, x500=0,
					x550=0, x600=0, x650=0, x700=0, xLager700=0, x10=0, x20=0,x30=0,x40=0,x55=0;

			for (Integer l:latencies){
				if (l<11)
					x10++;
				else if(l>10 && l<21)
					x20++;
				else if(l>20 && l<31)
					x30++;
				else if(l>30 && l<41)
					x40++;
				else if(l>40 && l<51)
					x50++;
				else if(l>50 && l<101)
					x100++;
				else if(l>100 && l<151)
					x150++;
				else if(l>150 && l<201)
					x200++;
				else if(l>200 && l<251)
					x250++;
				else if(l>250 && l<301)
					x300++;
				else if(l>300 && l<351)
					x350++;
				else if(l>350 && l<401)
					x400++;
				else if(l>400 && l<451)
					x450++;
				else if(l>450 && l<501)
					x500++;
				else if(l>500 && l<551)
					x550++;
				else if(l>560 && l<601)
					x600++;
				else if(l>600 && l<651)
					x650++;
				else if(l>650 && l<701)
					x700++;
				else
					xLager700++;
			}
				//outFile.println("Distribution contains latencies form (0-50) " + x50);
				outFile.println("Distribution contains latencies form (0-10) " + x10);
				outFile.println("Distribution contains latencies form (11-20) " + x20);
				outFile.println("Distribution contains latencies form (21-30) " + x30);
				outFile.println("Distribution contains latencies form (31-40) " + x40);
				outFile.println("Distribution contains latencies form (41-50) " + x55);
			    outFile.println("Distribution contains latencies form (51-100) " + x100);
			    outFile.println("Distribution contains latencies form (101-150) " + x150);
			    outFile.println("Distribution contains latencies form (151-200) " + x200);
			    outFile.println("Distribution contains latencies form (201-250) " + x250);
			    outFile.println("Distribution contains latencies form (251-300) " + x300);
			    outFile.println("Distribution contains latencies form (301-350) " + x350);
			    outFile.println("Distribution contains latencies form (351-400) " + x400);
			    outFile.println("Distribution contains latencies form (401-450) " + x450);
			    outFile.println("Distribution contains latencies form (451-500) " + x500);
			    outFile.println("Distribution contains latencies form (501-550) " + x550);
			    outFile.println("Distribution contains latencies form (551-600) " + x600);
			    outFile.println("Distribution contains latencies form (601-650) " + x650);
			    outFile.println("Distribution contains latencies form (651-700) " + x700);
			    outFile.println("Distribution contains latencies form (  > 700) " + xLager700);

//			final int groupRange = 50;
//
//			ListMultimap<Integer, Integer> map = Multimaps.index(latencies, new Function<Integer, Integer>() {
//			    public Integer apply(Integer i) {
//			        //work out which group the value belongs in
//			        return (i / groupRange) + (i % groupRange == 0 ? 0 : 1);
//			    }
//			});
//			for (Integer key : map.keySet()) {
//			    List<Integer> value = map.get(key);
//			    outFile.println("Distribution contains " + value.size() + " items from " + value.get(0) + " to " + value.get(value.size() - 1));
//			}

			    outFile.println("Test Generated at "+ new Date() + " /Lasted for = "
					 	+ TimeUnit.MILLISECONDS.toSeconds((endThroughputTime-startThroughputTime)));
			 outFile.println();

			outFile.close();

		}

/* ----------------------------- End of Private Methods -------------------------------- */

 final class FollowerMessageHandler implements Runnable {

    	private short id;
    	public FollowerMessageHandler(short id){
    		this.id = id;
    	}

    	/**
         * create a proposal and send it out to all the members
         *
         * @param message
         */
    	@Override
        public void run() {
                handleRequests();
        }

        public void handleRequests() {
        	ZabHeader hdrReq = null;
            while (running) {

                	 try {
                		 hdrReq = queuedMessages.take();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

            	long new_zxid = getNewZxid();
          	    numRequest.incrementAndGet();

            	ZabHeader hdrProposal = new ZabHeader(ZabHeader.PROPOSAL, new_zxid, hdrReq.getMessageId());
                Message ProposalMessage=new Message().putHeader(this.id, hdrProposal);

                ProposalMessage.setSrc(local_addr);
            	Proposal p = new Proposal();
            	p.setMessageId(hdrReq.getMessageId());
            	p.AckCount++;
            	outstandingProposals.put(new_zxid, p);
            	//hdrProposal.getMessageId().setStartTime(System.currentTimeMillis());
            	queuedProposalMessage.put(new_zxid, hdrProposal);

            	try{

                 	for (Address address : zabMembers) {
                        if(address.equals(leader))
                        	continue;
                        //if(startThroughput)
                		countMessageLeader.incrementAndGet();
                        Message cpy = ProposalMessage.copy();
                        cpy.setDest(address);
                		down_prot.down(new Event(Event.MSG, cpy));
                    }
                 }catch(Exception ex) {
            		log.error("failed proposing message to members");
            	}

            }

        }

    }

	 public class StatsThread extends Thread{
		 public void run(){
			 int avg = 0, elementCount = 0;
			 for (int i =  lastArrayIndex; i < latencies.size(); i++){
				 avg+=latencies.get(i);
				 elementCount++;
			 }

			 lastArrayIndex = latencies.size() - 1;
			 avg= avg/elementCount;
			 avgLatencies.add(avg);
		 }
	 }

	 class ResubmitTimer extends TimerTask{

		@Override
		public void run() {
			int finished = numReqDeviverd.get();
			currentCpuTime = System.currentTimeMillis();

			//Find average latency
			 int avg = 0, elementCount = 0;

			 //List<Integer> latCopy = new ArrayList<Integer>(latencies);
			 for (int i =  lastArrayIndexUsingTime; i < latencies.size(); i++){
				 if (latencies.get(i)>50){
					 largeLatCount++;
					 largeLatencies.add((currentCpuTime - startThroughputTime) + "/" + latencies.get(i));
				 }
				 avg+=latencies.get(i);
				 elementCount++;
			 }

			 lastArrayIndexUsingTime = latencies.size()-1;
			 avg= avg/elementCount;

			String mgsLat = (currentCpuTime - startThroughputTime) + "/" +
			                ((finished - lastFinished) + "/" + avg);// (TimeUnit.MILLISECONDS.toSeconds(currentCpuTime - lastCpuTime)));
			avgLatenciesTimer.add(mgsLat);
			lastFinished = finished;
			lastCpuTime = currentCpuTime;
		}

	 }
}


text:
@implementation NSLayoutConstraint (JRConstraintMake)

NSArray <NSLayoutConstraint *> *JRConstraintsMakeScaleToFill(id item,
                                                             id toItem) {

    NSMutableArray <NSLayoutConstraint *> *constraints = [[NSMutableArray alloc] init];

    [constraints addObject:JRConstraintMake(item, NSLayoutAttributeTop, NSLayoutRelationEqual, toItem, NSLayoutAttributeTop, 1, 0)];
    [constraints addObject:JRConstraintMake(item, NSLayoutAttributeLeft, NSLayoutRelationEqual, toItem, NSLayoutAttributeLeft, 1, 0)];
    [constraints addObject:JRConstraintMake(item, NSLayoutAttributeBottom, NSLayoutRelationEqual, toItem, NSLayoutAttributeBottom, 1, 0)];
    [constraints addObject:JRConstraintMake(item, NSLayoutAttributeRight, NSLayoutRelationEqual, toItem, NSLayoutAttributeRight, 1, 0)];

    return [constraints copy];
}

NSArray <NSLayoutConstraint *> *JRConstraintsMakeEqualSize(id item,
                                                           id toItem) {

    NSMutableArray <NSLayoutConstraint *> *constraints = [[NSMutableArray alloc] init];

    [constraints addObject:JRConstraintMake(item, NSLayoutAttributeWidth, NSLayoutRelationEqual, toItem, NSLayoutAttributeWidth, 1, 0)];
    [constraints addObject:JRConstraintMake(item, NSLayoutAttributeHeight, NSLayoutRelationEqual, toItem, NSLayoutAttributeHeight, 1, 0)];

    return [constraints copy];
}

NSLayoutConstraint *JRConstraintMake(id item,
                                     NSLayoutAttribute attribute,
                                     NSLayoutRelation relation,
                                     id toItem,
                                     NSLayoutAttribute secondAttribute,
                                     CGFloat multiplier,
                                     CGFloat constant) {

    NSLayoutConstraint *constaint = [NSLayoutConstraint constraintWithItem:item
                                        attribute:attribute
                                        relatedBy:relation
                                           toItem:toItem
                                        attribute:secondAttribute
                                       multiplier:multiplier
                                         constant:constant];
    return constaint;
}

@end

redpajama_set_name: RedPajamaGithub


text:
#ifndef __itkParticleEntropyGradientFunction_h
#define __itkParticleEntropyGradientFunction_h

#include "itkParticleVectorFunction.h"
#include "itkParticleContainerArrayAttribute.h"
#include "itkParticleImageDomainWithGradients.h"
#include <vector>

namespace itk
{

/**
 * \class ParticleEntropyGradientFunction
 *
 * \brief This function returns an estimate of the gradient of the entropy of a
 * particle distribution with respect to change in position of a specific
 * particle in that distribution.

 *
 * The following description is an excerpt from
 *
 *J Cates, P T Fletcher, M Styner, M Shenton, R Whitaker. Shape Modeling and
 * Analysis with Entropy-Based Particle Systems.  Information Processing in
 * Medical Imaging IPMI 2007, LNCS 4584, pp. 333–345, 2007.
 *
 *
 * We treat a surface as a subset of \f$\Re^d\f$, where \f$d=2\f$ or \f$d=3\f$
 * depending whether we are processing curves in the plane or surfaces in a
 * volume, refspectively.  The method we describe here deals with smooth,
 * closed manifolds of codimension one, and we will refer to such manifolds as
 * {\em surfaces}.  We sample a surface \f${\cal S} \subset \Re^d\f$ using a
 * discrete set of \f$N\f$ points that are considered random variables \f$Z =
 * (X_1, X_2, \ldots, X_N)\f$ drawn from a probability density function (PDF),
 * \f$p(X)\f$.  We denote a realization of this PDF with lower case, and thus
 * we have \f$z = (x_1, x_2,\ldots, x_N)\f$, where \f$z \in {\cal S}^N\f$.  The
 * probability of a realization \f$x\f$ is \f$p(X = x)\f$, which we denote
 * simply as \f$p(x)\f$.
 *
 * The amount of information contained in such a random sampling is, in the
 * limit, the differential entropy of the PDF, which is \f$H[X] = -\int_S p(x)
 * \log p(x) dx = -E\{\log p(X)\}\f$, where \f$E\{ \cdot \}\f$ is the
 * expectation. When we have a sufficient number of points sampled from
 * \f$p\f$, we can approximate the expectation by the sample mean, which gives
 * \f$H[X] \approx - (1/N)\sum_{i} \log p(x_i)\f$.  We must also estimate
 * \f$p(x_i)\f$.  Density functions on surfaces can be quite complex, and so we
 * use a nonparametric, Parzen windowing estimation of this density using the
 * particles themselves.  Thus we have
 *\f[
 * p(x_i) \approx \frac{1}{N(N-1)} \sum^N_{j=1, j \neq i} G(x_i - x_j,
 * \sigma_i),
 * \f]
 * where \f$G(x_i - x_j,
 * \sigma_i)\f$ is a \f$d\f$-dimensional, isotropic Gaussian with standard
 * deviation \f$\sigma_i\f$.  The cost function \f$C\f$, is therefore an
 * approximation of (negative) entropy:
 * \f[
 * -H[X] \approx C(x_1, \dots, x_N) =
 * \sum_{i} \log \frac{1}{N(N-1)} \sum_{j \neq i} G(x_i - x_j, \sigma_i).
 * \f]
 *
 */
template <class TGradientNumericType, unsigned int VDimension>
class ParticleEntropyGradientFunction : public ParticleVectorFunction<VDimension>
{
public:
 /** Standard class typedefs. */
  typedef ParticleEntropyGradientFunction Self;
  typedef SmartPointer<Self>  Pointer;
  typedef SmartPointer<const Self>  ConstPointer;
  typedef ParticleVectorFunction<VDimension> Superclass;
  itkTypeMacro( ParticleEntropyGradientFunction, ParticleVectorFunction);

  /** Data type representing individual gradient components. */
  typedef TGradientNumericType GradientNumericType;

  /** Type of particle system. */
  typedef typename Superclass::ParticleSystemType ParticleSystemType;

  /** Cache type for the sigma values. */
  typedef ParticleContainerArrayAttribute<double, VDimension> SigmaCacheType;

  /** Vector & Point types. */
  typedef typename Superclass::VectorType VectorType;
  typedef typename ParticleSystemType::PointType PointType;
  typedef  vnl_vector_fixed<TGradientNumericType, VDimension> GradientVectorType;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Dimensionality of the domain of the particle system. */
  itkStaticConstMacro(Dimension, unsigned int, VDimension);

  /** The first argument is a pointer to the particle system.  The second
      argument is the index of the domain within that particle system.  The
      third argument is the index of the particle location within the given
      domain. */
  virtual VectorType Evaluate(unsigned int, unsigned int, const ParticleSystemType *,
                              double &) const;

  virtual VectorType Evaluate(unsigned int, unsigned int, const ParticleSystemType *,
                              double &, double &) const
  {
    itkExceptionMacro("This method not implemented");
    return VectorType();
  }
  virtual double Energy(unsigned int, unsigned int, const ParticleSystemType *) const
  {
    itkExceptionMacro("This method not implemented");
    return 0.0;
  }

  virtual void ResetBuffers()
  {
    m_SpatialSigmaCache->ZeroAllValues();
  }

  /** Estimate the best sigma for Parzen windowing in a given neighborhood.
      The best sigma is the sigma that maximizes probability at the given point  */
  virtual double EstimateSigma(unsigned int, const typename ParticleSystemType::PointVectorType &,
                                const std::vector<double> &,
                                    const PointType &, double,  double,  int &err) const;

  /** Returns a weighting coefficient based on the angle between two
     vectors. Weights smoothly approach zero as the angle between two
     normals approaches 90 degrees. */
  TGradientNumericType AngleCoefficient(const GradientVectorType&,
                                        const GradientVectorType&) const;

  /** Minimum radius of the neighborhood of points that are considered in the
      calculation. The neighborhood is a spherical radius in 3D space. The
      actual radius used in a calculation may exceed this value, but will not
      exceed the MaximumNeighborhoodRadius. */
  void SetMinimumNeighborhoodRadius( double s)
  { m_MinimumNeighborhoodRadius = s; }
  double GetMinimumNeighborhoodRadius() const
  { return m_MinimumNeighborhoodRadius; }

  /** Maximum radius of the neighborhood of points that are considered in the
      calculation. The neighborhood is a spherical radius in 3D space. */
  void SetMaximumNeighborhoodRadius( double s)
  { m_MaximumNeighborhoodRadius = s; }
  double GetMaximumNeighborhoodRadius() const
  { return m_MaximumNeighborhoodRadius; }

  /** Numerical parameters*/
  void SetFlatCutoff(double s)
  { m_FlatCutoff = s; }
  double GetFlatCutoff() const
  { return m_FlatCutoff; }
  void SetNeighborhoodToSigmaRatio(double s)
  { m_NeighborhoodToSigmaRatio = s; }
  double GetNeighborhoodToSigmaRatio() const
  { return m_NeighborhoodToSigmaRatio; }

  /**Access the cache of sigma values for each particle position.  This cache
     is populated by registering this object as an observer of the correct
     particle system (see SetParticleSystem).*/
  void SetSpatialSigmaCache( SigmaCacheType *s)
  {    m_SpatialSigmaCache = s;  }
  SigmaCacheType *GetSpatialSigmaCache()
  {   return  m_SpatialSigmaCache.GetPointer();  }
  const SigmaCacheType *GetSpatialSigmaCache() const
  {   return  m_SpatialSigmaCache.GetPointer();  }

  /** Compute a set of weights based on the difference in the normals of a
      central point and each of its neighbors.  Difference of > 90 degrees
      results in a weight of 0. */
  void ComputeAngularWeights(const PointType &,
                             const typename ParticleSystemType::PointVectorType &,
                             const ParticleImageDomainWithGradients<TGradientNumericType, VDimension> *,
                             std::vector<double> &) const;

  //  void ComputeNeighborho0d();

protected:

  ParticleEntropyGradientFunction() : m_FlatCutoff(0.05), m_NeighborhoodToSigmaRatio(3.0) {}
  virtual ~ParticleEntropyGradientFunction() {}
  void operator=(const ParticleEntropyGradientFunction &);
  ParticleEntropyGradientFunction(const ParticleEntropyGradientFunction &);

  double m_MinimumNeighborhoodRadius;
  double m_MaximumNeighborhoodRadius;
  double m_FlatCutoff;
  double m_NeighborhoodToSigmaRatio;
  typename SigmaCacheType::Pointer m_SpatialSigmaCache;
};

} //end namespace

#if ITK_TEMPLATE_EXPLICIT
# include "Templates/itkParticleEntropyGradientFunction+-.h"
#endif

#if ITK_TEMPLATE_TXX
# include "itkParticleEntropyGradientFunction.txx"
#endif

#endif


text:
using System.Runtime.CompilerServices;

namespace TripShare.Client.Console
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using TripShare.Data;
    using TripShare.Models;

    public class ConsoleClient
    {
        static void Main()
        {
            var data = new TripShareData();

            var cities = data.Cities
                .All()
                .Select(c => c.Name)
                .ToList();

            foreach (var city in cities)
            {
                Console.WriteLine(city);
            }

            var trip = data.Trips.Find(1);

            Console.WriteLine("Ot" + " " + trip.DepartureCity.Name + " do " + trip.ArrivalCity.Name + " na {0:dd/MM}",
                trip.DepartureDate);
        }
    }
}


text:
package com.gamefreezer.galaga.tests;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import com.gamefreezer.galaga.AbstractGraphics;
import com.gamefreezer.galaga.Animation;
import com.gamefreezer.galaga.AnimationPool;
import com.gamefreezer.galaga.HitRenderer;
import com.gamefreezer.galaga.Location;

public class HitRendererTest {

    HitRenderer hitRenderer;
    Animation hitAnim;
    AnimationPool pool;
    AbstractGraphics graphics;
    int rendererSize = 10;
    int poolSize = 10;
    Location origin;
    int maxFrames = 5;

    @Before
    public void setUp() throws Exception {
	hitRenderer = new HitRenderer(rendererSize);
	hitAnim = Helper.buildAnimation(true);
	pool = new AnimationPool("hits", Helper.buildSpriteCache(), maxFrames,
		Helper.buildAnimationSource(), poolSize, true);
	graphics = new MockGraphics();
	origin = new Location();
    }

    @Test
    public void canAddNewHit() {
	assertThat(hitRenderer.currentRenders(), is(0));
	hitRenderer.registerHit(hitAnim, new Location(), origin);
	assertThat(hitRenderer.currentRenders(), is(1));
    }

    @Test
    public void extraHitsIgnoredSafely() {
	for (int idx = 0; idx < rendererSize; idx++) {
	    hitRenderer
		    .registerHit(Helper.buildAnimation(true), origin, origin);
	}
	assertThat("pre", hitRenderer.currentRenders(), is(rendererSize));
	hitRenderer.registerHit(Helper.buildAnimation(true), origin, origin);
	assertThat("post", hitRenderer.currentRenders(), is(rendererSize));
    }

    @Test
    public void hitsNulledAfterPlaying() {
	hitRenderer.registerHit(hitAnim, origin, origin);
	hitRenderer.draw(graphics, origin);
	hitRenderer.draw(graphics, origin);
	assertThat(hitRenderer.currentRenders(), is(0));
    }

    @Test
    public void hitsReturnedToPoolAfterPlaying() {
	hitRenderer.registerHit(pool.get(), origin, origin);
	assertThat(pool.remaining(), is(poolSize - 1));
	hitRenderer.draw(graphics, origin);
	hitRenderer.draw(graphics, origin);
	assertThat(pool.remaining(), is(poolSize));
    }
}


text:
//
//  OCHamcrest - HCInvocationMatcher.h
//  Copyright 2009 www.hamcrest.org. See LICENSE.txt
//
//  Created by: Jon Reid
//

    // Inherited
#import <OCHamcrest/HCBaseMatcher.h>

/**
    Supporting class for matching a feature of an object.

    Tests whether the result of passing a given invocation to the value satisfies a given matcher.
*/
@interface HCInvocationMatcher : HCBaseMatcher
{
    NSInvocation* invocation;
    id<HCMatcher> subMatcher;
}

/**
    Helper method for creating an invocation.

    A class is specified only so we can determine the method signature.
*/
+ (NSInvocation*) createInvocationForSelector:(SEL)selector onClass:(Class)aClass;

- (id) initWithInvocation:(NSInvocation*)anInvocation matching:(id<HCMatcher>)aMatcher;

/**
    Returns string representation of the invocation's selector.
*/
- (NSString*) stringFromSelector;

@end


text:
(function() {
  'use strict';
  function getItemsFromService(itemService){
    return itemService.getItems();
  }
  getItemsFromService.$inject=['itemService'];

  function selectRoute($stateProvider){
    $stateProvider.state('select',{
      url:'/select',
      templateUrl:'views/select.tpl.html',
      controller:'SelectCtrl as sc'
    });
  }
  selectRoute.$inject=['$stateProvider'];
  angular.module('app.select')
  .config(selectRoute);
}());


text:
#ifndef HEADER_CURL_MULTIIF_H
#define HEADER_CURL_MULTIIF_H

/*
 * Prototypes for library-wide functions provided by multi.c
 */

CURLcode Curl_updatesocket(struct Curl_easy *data);
void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id);
void Curl_expire_clear(struct Curl_easy *data);
void Curl_expire_done(struct Curl_easy *data, expire_id id);
CURLMcode Curl_update_timer(struct Curl_multi *multi) WARN_UNUSED_RESULT;
void Curl_attach_connection(struct Curl_easy *data,
                             struct connectdata *conn);
void Curl_detach_connection(struct Curl_easy *data);
bool Curl_multiplex_wanted(const struct Curl_multi *multi);
void Curl_set_in_callback(struct Curl_easy *data, bool value);
bool Curl_is_in_callback(struct Curl_easy *easy);
CURLcode Curl_preconnect(struct Curl_easy *data);

/* Internal version of curl_multi_init() accepts size parameters for the
   socket, connection and dns hashes */
struct Curl_multi *Curl_multi_handle(int hashsize, int chashsize,
                                     int dnssize);

/* the write bits start at bit 16 for the *getsock() bitmap */
#define GETSOCK_WRITEBITSTART 16

#define GETSOCK_BLANK 0 /* no bits set */

/* set the bit for the given sock number to make the bitmap for writable */
#define GETSOCK_WRITESOCK(x) (1 << (GETSOCK_WRITEBITSTART + (x)))

/* set the bit for the given sock number to make the bitmap for readable */
#define GETSOCK_READSOCK(x) (1 << (x))

#ifdef DEBUGBUILD
 /*
  * Curl_multi_dump is not a stable public function, this is only meant to
  * allow easier tracking of the internal handle's state and what sockets
  * they use. Only for research and development DEBUGBUILD enabled builds.
  */
void Curl_multi_dump(struct Curl_multi *multi);
#endif

/* Return the value of the CURLMOPT_MAX_HOST_CONNECTIONS option */
size_t Curl_multi_max_host_connections(struct Curl_multi *multi);

/* Return the value of the CURLMOPT_MAX_TOTAL_CONNECTIONS option */
size_t Curl_multi_max_total_connections(struct Curl_multi *multi);

void Curl_multiuse_state(struct Curl_easy *data,
                         int bundlestate); /* use BUNDLE_* defines */

/*
 * Curl_multi_closed()
 *
 * Used by the connect code to tell the multi_socket code that one of the
 * sockets we were using is about to be closed.  This function will then
 * remove it from the sockethash for this handle to make the multi_socket API
 * behave properly, especially for the case when libcurl will create another
 * socket again and it gets the same file descriptor number.
 */

void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s);

/*
 * Add a handle and move it into PERFORM state at once. For pushed streams.
 */
CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
                                 struct Curl_easy *data,
                                 struct connectdata *conn);

/* Return the value of the CURLMOPT_MAX_CONCURRENT_STREAMS option */
unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi);

#endif /* HEADER_CURL_MULTIIF_H */


text:
from datetime import date
from functools import wraps
from unittest import mock

from django import forms
from django.contrib.auth.models import AnonymousUser
from django.core import checks
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
from django.test import RequestFactory, TestCase, override_settings

from wagtail.admin.edit_handlers import (
    FieldPanel, FieldRowPanel, InlinePanel, ObjectList, PageChooserPanel,
    RichTextFieldPanel, TabbedInterface, extract_panel_definitions_from_model_class,
    get_form_for_model)
from wagtail.admin.forms import WagtailAdminModelForm, WagtailAdminPageForm
from wagtail.admin.rich_text import DraftailRichTextArea
from wagtail.admin.widgets import AdminAutoHeightTextInput, AdminDateInput, AdminPageChooser
from wagtail.core.models import Page, Site
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.tests.testapp.forms import ValidatedPageForm
from wagtail.tests.testapp.models import (
    EventPage, EventPageChooserModel, EventPageSpeaker, PageChooserModel,
    RestaurantPage, SimplePage, ValidatedPage)
from wagtail.tests.utils import WagtailTestUtils

class TestGetFormForModel(TestCase):
    def test_get_form_without_model(self):
        edit_handler = ObjectList()
        with self.assertRaisesMessage(
                AttributeError,
                'ObjectList is not bound to a model yet. '
                'Use `.bind_to(model=model)` before using this method.'):
            edit_handler.get_form_class()

    def test_get_form_for_model(self):
        EventPageForm = get_form_for_model(EventPage, form_class=WagtailAdminPageForm)
        form = EventPageForm()

        # form should be a subclass of WagtailAdminModelForm
        self.assertTrue(issubclass(EventPageForm, WagtailAdminModelForm))
        # form should contain a title field (from the base Page)
        self.assertEqual(type(form.fields['title']), forms.CharField)
        # and 'date_from' from EventPage
        self.assertEqual(type(form.fields['date_from']), forms.DateField)
        # the widget should be overridden with AdminDateInput as per FORM_FIELD_OVERRIDES
        self.assertEqual(type(form.fields['date_from'].widget), AdminDateInput)

        # treebeard's 'path' field should be excluded
        self.assertNotIn('path', form.fields)

        # all child relations become formsets by default
        self.assertIn('speakers', form.formsets)
        self.assertIn('related_links', form.formsets)

    def test_direct_form_field_overrides(self):
        # Test that field overrides defined through DIRECT_FORM_FIELD_OVERRIDES
        # are applied

        SimplePageForm = get_form_for_model(SimplePage, form_class=WagtailAdminPageForm)
        simple_form = SimplePageForm()
        # plain TextFields should use AdminAutoHeightTextInput as the widget
        self.assertEqual(type(simple_form.fields['content'].widget), AdminAutoHeightTextInput)

        # This override should NOT be applied to subclasses of TextField such as
        # RichTextField - they should retain their default widgets
        EventPageForm = get_form_for_model(EventPage, form_class=WagtailAdminPageForm)
        event_form = EventPageForm()
        self.assertEqual(type(event_form.fields['body'].widget), DraftailRichTextArea)

    def test_get_form_for_model_with_specific_fields(self):
        EventPageForm = get_form_for_model(
            EventPage, form_class=WagtailAdminPageForm, fields=['date_from'],
            formsets=['speakers'])
        form = EventPageForm()

        # form should contain date_from but not title
        self.assertEqual(type(form.fields['date_from']), forms.DateField)
        self.assertEqual(type(form.fields['date_from'].widget), AdminDateInput)
        self.assertNotIn('title', form.fields)

        # formsets should include speakers but not related_links
        self.assertIn('speakers', form.formsets)
        self.assertNotIn('related_links', form.formsets)

    def test_get_form_for_model_with_excluded_fields(self):
        EventPageForm = get_form_for_model(
            EventPage, form_class=WagtailAdminPageForm,
            exclude=['title'], exclude_formsets=['related_links'])
        form = EventPageForm()

        # form should contain date_from but not title
        self.assertEqual(type(form.fields['date_from']), forms.DateField)
        self.assertEqual(type(form.fields['date_from'].widget), AdminDateInput)
        self.assertNotIn('title', form.fields)

        # 'path' is not excluded any more, as the excluded fields were overridden
        self.assertIn('path', form.fields)

        # formsets should include speakers but not related_links
        self.assertIn('speakers', form.formsets)
        self.assertNotIn('related_links', form.formsets)

    def test_get_form_for_model_with_widget_overides_by_class(self):
        EventPageForm = get_form_for_model(
            EventPage, form_class=WagtailAdminPageForm,
            widgets={'date_from': forms.PasswordInput})
        form = EventPageForm()

        self.assertEqual(type(form.fields['date_from']), forms.DateField)
        self.assertEqual(type(form.fields['date_from'].widget), forms.PasswordInput)

    def test_get_form_for_model_with_widget_overides_by_instance(self):
        EventPageForm = get_form_for_model(
            EventPage, form_class=WagtailAdminPageForm,
            widgets={'date_from': forms.PasswordInput()})
        form = EventPageForm()

        self.assertEqual(type(form.fields['date_from']), forms.DateField)
        self.assertEqual(type(form.fields['date_from'].widget), forms.PasswordInput)

    def test_tag_widget_is_passed_tag_model(self):
        RestaurantPageForm = get_form_for_model(
            RestaurantPage, form_class=WagtailAdminPageForm
        )
        form_html = RestaurantPageForm().as_p()
        self.assertIn('/admin/tag\\u002Dautocomplete/tests/restauranttag/', form_html)

def clear_edit_handler(page_cls):
    def decorator(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            # Clear any old EditHandlers generated
            page_cls.get_edit_handler.cache_clear()
            try:
                fn(*args, **kwargs)
            finally:
                # Clear the bad EditHandler generated just now
                page_cls.get_edit_handler.cache_clear()
        return decorated
    return decorator

class TestPageEditHandlers(TestCase):

    @clear_edit_handler(EventPage)
    def test_get_edit_handler(self):
        """
        Forms for pages should have a base class of WagtailAdminPageForm.
        """
        edit_handler = EventPage.get_edit_handler()
        EventPageForm = edit_handler.get_form_class()

        # The generated form should inherit from WagtailAdminPageForm
        self.assertTrue(issubclass(EventPageForm, WagtailAdminPageForm))

    @clear_edit_handler(ValidatedPage)
    def test_get_form_for_page_with_custom_base(self):
        """
        ValidatedPage sets a custom base_form_class. This should be used as the
        base class when constructing a form for ValidatedPages
        """
        edit_handler = ValidatedPage.get_edit_handler()
        GeneratedValidatedPageForm = edit_handler.get_form_class()

        # The generated form should inherit from ValidatedPageForm, because
        # ValidatedPage.base_form_class == ValidatedPageForm
        self.assertTrue(issubclass(GeneratedValidatedPageForm, ValidatedPageForm))

    @clear_edit_handler(ValidatedPage)
    def test_check_invalid_base_form_class(self):
        class BadFormClass:
            pass

        invalid_base_form = checks.Error(
            "ValidatedPage.base_form_class does not extend WagtailAdminPageForm",
            hint="Ensure that wagtail.admin.tests.test_edit_handlers.BadFormClass extends WagtailAdminPageForm",
            obj=ValidatedPage,
            id='wagtailadmin.E001')

        invalid_edit_handler = checks.Error(
            "ValidatedPage.get_edit_handler().get_form_class() does not extend WagtailAdminPageForm",
            hint="Ensure that the EditHandler for ValidatedPage creates a subclass of WagtailAdminPageForm",
            obj=ValidatedPage,
            id='wagtailadmin.E002')

        with mock.patch.object(ValidatedPage, 'base_form_class', new=BadFormClass):
            errors = checks.run_checks()

            # ignore CSS loading errors (to avoid spurious failures on CI servers that
            # don't build the CSS)
            errors = [e for e in errors if e.id != 'wagtailadmin.W001']

            # Errors may appear out of order, so sort them by id
            errors.sort(key=lambda e: e.id)

            self.assertEqual(errors, [invalid_base_form, invalid_edit_handler])

    @clear_edit_handler(ValidatedPage)
    def test_custom_edit_handler_form_class(self):
        """
        Set a custom edit handler on a Page class, but dont customise
        ValidatedPage.base_form_class, or provide a custom form class for the
        edit handler. Check the generated form class is of the correct type.
        """
        ValidatedPage.edit_handler = TabbedInterface()
        with mock.patch.object(ValidatedPage, 'edit_handler', new=TabbedInterface(), create=True):
            form_class = ValidatedPage.get_edit_handler().get_form_class()
            self.assertTrue(issubclass(form_class, WagtailAdminPageForm))
            errors = ValidatedPage.check()
            self.assertEqual(errors, [])

    @clear_edit_handler(ValidatedPage)
    def test_repr(self):
        edit_handler = ValidatedPage.get_edit_handler()

        handler_handler_repr = repr(edit_handler)

        self.assertIn("model=<class 'wagtail.tests.testapp.models.ValidatedPage'>", handler_handler_repr)
        self.assertIn('instance=None', handler_handler_repr)
        self.assertIn("request=None", handler_handler_repr)
        self.assertIn('form=None', handler_handler_repr)

class TestExtractPanelDefinitionsFromModelClass(TestCase):
    def test_can_extract_panel_property(self):
        # A class with a 'panels' property defined should return that list
        result = extract_panel_definitions_from_model_class(EventPageSpeaker)
        self.assertEqual(len(result), 5)
        self.assertTrue(any([isinstance(panel, ImageChooserPanel) for panel in result]))

    def test_exclude(self):
        panels = extract_panel_definitions_from_model_class(Site, exclude=['hostname'])
        for panel in panels:
            self.assertNotEqual(panel.field_name, 'hostname')

    def test_can_build_panel_list(self):
        # EventPage has no 'panels' definition, so one should be derived from the field list
        panels = extract_panel_definitions_from_model_class(EventPage)

        self.assertTrue(any([
            isinstance(panel, FieldPanel) and panel.field_name == 'date_from'
            for panel in panels
        ]))

        # returned panel types should respect modelfield.get_panel() - used on RichTextField
        self.assertTrue(any([
            isinstance(panel, RichTextFieldPanel) and panel.field_name == 'body'
            for panel in panels
        ]))

class TestTabbedInterface(TestCase):
    def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user

        # a custom tabbed interface for EventPage
        self.event_page_tabbed_interface = TabbedInterface([
            ObjectList([
                FieldPanel('title', widget=forms.Textarea),
                FieldPanel('date_from'),
                FieldPanel('date_to'),
            ], heading='Event details', classname="shiny"),
            ObjectList([
                InlinePanel('speakers', label="Speakers"),
            ], heading='Speakers'),
        ]).bind_to(model=EventPage, request=self.request)

    def test_get_form_class(self):
        EventPageForm = self.event_page_tabbed_interface.get_form_class()
        form = EventPageForm()

        # form must include the 'speakers' formset required by the speakers InlinePanel
        self.assertIn('speakers', form.formsets)

        # form must respect any overridden widgets
        self.assertEqual(type(form.fields['title'].widget), forms.Textarea)

    def test_render(self):
        EventPageForm = self.event_page_tabbed_interface.get_form_class()
        event = EventPage(title='Abergavenny sheepdog trials')
        form = EventPageForm(instance=event)

        tabbed_interface = self.event_page_tabbed_interface.bind_to(
            instance=event,
            form=form,
        )

        result = tabbed_interface.render()

        # result should contain tab buttons
        self.assertIn('Event details', result)
        self.assertIn('Speakers', result)

        # result should contain tab panels
        self.assertIn('
', result)
        self.assertIn('
', result)
        self.assertIn('
', result)

        # result should contain rendered content from descendants
        self.assertIn('Abergavenny sheepdog trials</textarea>', result)

        # this result should not include fields that are not covered by the panel definition
        self.assertNotIn('signup_link', result)

    def test_required_fields(self):
        # required_fields should report the set of form fields to be rendered recursively by children of TabbedInterface
        result = set(self.event_page_tabbed_interface.required_fields())
        self.assertEqual(result, set(['title', 'date_from', 'date_to']))

    def test_render_form_content(self):
        EventPageForm = self.event_page_tabbed_interface.get_form_class()
        event = EventPage(title='Abergavenny sheepdog trials')
        form = EventPageForm(instance=event)

        tabbed_interface = self.event_page_tabbed_interface.bind_to(
            instance=event,
            form=form,
        )

        result = tabbed_interface.render_form_content()
        # rendered output should contain field content as above
        self.assertIn('Abergavenny sheepdog trials</textarea>', result)
        # rendered output should NOT include fields that are in the model but not represented
        # in the panel definition
        self.assertNotIn('signup_link', result)

class TestObjectList(TestCase):
    def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user
        # a custom ObjectList for EventPage
        self.event_page_object_list = ObjectList([
            FieldPanel('title', widget=forms.Textarea),
            FieldPanel('date_from'),
            FieldPanel('date_to'),
            InlinePanel('speakers', label="Speakers"),
        ], heading='Event details', classname="shiny").bind_to(
            model=EventPage, request=self.request)

    def test_get_form_class(self):
        EventPageForm = self.event_page_object_list.get_form_class()
        form = EventPageForm()

        # form must include the 'speakers' formset required by the speakers InlinePanel
        self.assertIn('speakers', form.formsets)

        # form must respect any overridden widgets
        self.assertEqual(type(form.fields['title'].widget), forms.Textarea)

    def test_render(self):
        EventPageForm = self.event_page_object_list.get_form_class()
        event = EventPage(title='Abergavenny sheepdog trials')
        form = EventPageForm(instance=event)

        object_list = self.event_page_object_list.bind_to(
            instance=event,
            form=form,
        )

        result = object_list.render()

        # result should contain ObjectList furniture
        self.assertIn('
', result)

        # result should contain labels for children
        self.assertInHTML('Start date', result)

        # result should include help text for children
        self.assertIn('
Not required if event is on a single day
', result)

        # result should contain rendered content from descendants
        self.assertIn('Abergavenny sheepdog trials</textarea>', result)

        # this result should not include fields that are not covered by the panel definition
        self.assertNotIn('signup_link', result)

class TestFieldPanel(TestCase):
    def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user

        self.EventPageForm = get_form_for_model(
            EventPage, form_class=WagtailAdminPageForm, formsets=[])
        self.event = EventPage(title='Abergavenny sheepdog trials',
                               date_from=date(2014, 7, 20), date_to=date(2014, 7, 21))

        self.end_date_panel = (FieldPanel('date_to', classname='full-width')
                               .bind_to(model=EventPage, request=self.request))

    def test_non_model_field(self):
        # defining a FieldPanel for a field which isn't part of a model is OK,
        # because it might be defined on the form instead
        field_panel = FieldPanel('barbecue').bind_to(model=Page)

        # however, accessing db_field will fail
        with self.assertRaises(FieldDoesNotExist):
            field_panel.db_field

    def test_render_as_object(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-22'},
            instance=self.event)

        form.is_valid()

        field_panel = self.end_date_panel.bind_to(
            instance=self.event,
            form=form,
        )
        result = field_panel.render_as_object()

        # check that label appears as a legend in the 'object' wrapper,
        # but not as a field label (that would be provided by ObjectList instead)
        self.assertIn('<legend>End date</legend>', result)
        self.assertNotIn('End date:', result)

        # check that help text is not included (it's provided by ObjectList instead)
        self.assertNotIn('Not required if event is on a single day', result)

        # check that the populated form field is included
        self.assertIn('value="2014-07-22"', result)

        # there should be no errors on this field
        self.assertNotIn('
', result)

    def test_render_as_field(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-22'},
            instance=self.event)

        form.is_valid()

        field_panel = self.end_date_panel.bind_to(
            instance=self.event,
            form=form,
        )
        result = field_panel.render_as_field()

        # check that label is output in the 'field' style
        self.assertIn('End date:', result)
        self.assertNotIn('<legend>End date</legend>', result)

        # check that help text is included
        self.assertIn('Not required if event is on a single day', result)

        # check that the populated form field is included
        self.assertIn('value="2014-07-22"', result)

        # there should be no errors on this field
        self.assertNotIn('
', result)

    def test_required_fields(self):
        result = self.end_date_panel.required_fields()
        self.assertEqual(result, ['date_to'])

    def test_error_message_is_rendered(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-33'},
            instance=self.event)

        form.is_valid()

        field_panel = self.end_date_panel.bind_to(
            instance=self.event,
            form=form,
        )
        result = field_panel.render_as_field()

        self.assertIn('
', result)
        self.assertIn('Enter a valid date.', result)

    def test_repr(self):
        form = self.EventPageForm()
        field_panel = self.end_date_panel.bind_to(
            form=form,
        )

        field_panel_repr = repr(field_panel)

        self.assertIn("model=<class 'wagtail.tests.testapp.models.EventPage'>", field_panel_repr)
        self.assertIn('instance=None', field_panel_repr)
        self.assertIn("request=<WSGIRequest: GET '/'>", field_panel_repr)
        self.assertIn('form=EventPageForm', field_panel_repr)

class TestFieldRowPanel(TestCase):
    def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user

        self.EventPageForm = get_form_for_model(
            EventPage, form_class=WagtailAdminPageForm, formsets=[])
        self.event = EventPage(title='Abergavenny sheepdog trials',
                               date_from=date(2014, 7, 20), date_to=date(2014, 7, 21))

        self.dates_panel = FieldRowPanel([
            FieldPanel('date_from', classname='col4'),
            FieldPanel('date_to', classname='coltwo'),
        ]).bind_to(model=EventPage, request=self.request)

    def test_render_as_object(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-22'},
            instance=self.event)

        form.is_valid()

        field_panel = self.dates_panel.bind_to(
            instance=self.event,
            form=form,
        )
        result = field_panel.render_as_object()

        # check that the populated form field is included
        self.assertIn('value="2014-07-22"', result)

        # there should be no errors on this field
        self.assertNotIn('
', result)

    def test_render_as_field(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-22'},
            instance=self.event)

        form.is_valid()

        field_panel = self.dates_panel.bind_to(
            instance=self.event,
            form=form,
        )
        result = field_panel.render_as_field()

        # check that label is output in the 'field' style
        self.assertIn('End date:', result)
        self.assertNotIn('<legend>End date</legend>', result)

        # check that help text is included
        self.assertIn('Not required if event is on a single day', result)

        # check that the populated form field is included
        self.assertIn('value="2014-07-22"', result)

        # there should be no errors on this field
        self.assertNotIn('
', result)

    def test_error_message_is_rendered(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-33'},
            instance=self.event)

        form.is_valid()

        field_panel = self.dates_panel.bind_to(
            instance=self.event,
            form=form,
        )
        result = field_panel.render_as_field()

        self.assertIn('
', result)
        self.assertIn('Enter a valid date.', result)

    def test_add_col_when_wrong_in_panel_def(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-33'},
            instance=self.event)

        form.is_valid()

        field_panel = self.dates_panel.bind_to(
            instance=self.event,
            form=form,
        )

        result = field_panel.render_as_field()

        self.assertIn('<li class="field-col coltwo col6', result)

    def test_added_col_doesnt_change_siblings(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-33'},
            instance=self.event)

        form.is_valid()

        field_panel = self.dates_panel.bind_to(
            instance=self.event,
            form=form,
        )

        result = field_panel.render_as_field()

        self.assertIn('<li class="field-col col4', result)

class TestFieldRowPanelWithChooser(TestCase):
    def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user

        self.EventPageForm = get_form_for_model(
            EventPage, form_class=WagtailAdminPageForm, formsets=[])
        self.event = EventPage(title='Abergavenny sheepdog trials',
                               date_from=date(2014, 7, 19), date_to=date(2014, 7, 21))

        self.dates_panel = FieldRowPanel([
            FieldPanel('date_from'),
            ImageChooserPanel('feed_image'),
        ]).bind_to(model=EventPage, request=self.request)

    def test_render_as_object(self):
        form = self.EventPageForm(
            {'title': 'Pontypridd sheepdog trials', 'date_from': '2014-07-20', 'date_to': '2014-07-22'},
            instance=self.event)

        form.is_valid()

        field_panel = self.dates_panel.bind_to(
            instance=self.event,
            form=form,
        )
        result = field_panel.render_as_object()

        # check that the populated form field is included
        self.assertIn('value="2014-07-20"', result)

        # there should be no errors on this field
        self.assertNotIn('
', result)

class TestPageChooserPanel(TestCase):
    fixtures = ['test.json']

    def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user

        model = PageChooserModel  # a model with a foreign key to Page which we want to render as a page chooser

        # a PageChooserPanel class that works on PageChooserModel's 'page' field
        self.edit_handler = (ObjectList([PageChooserPanel('page')])
                             .bind_to(model=PageChooserModel,
                                      request=self.request))
        self.my_page_chooser_panel = self.edit_handler.children[0]

        # build a form class containing the fields that MyPageChooserPanel wants
        self.PageChooserForm = self.edit_handler.get_form_class()

        # a test instance of PageChooserModel, pointing to the 'christmas' page
        self.christmas_page = Page.objects.get(slug='christmas')
        self.events_index_page = Page.objects.get(slug='events')
        self.test_instance = model.objects.create(page=self.christmas_page)

        self.form = self.PageChooserForm(instance=self.test_instance)
        self.page_chooser_panel = self.my_page_chooser_panel.bind_to(
            instance=self.test_instance, form=self.form)

    def test_page_chooser_uses_correct_widget(self):
        self.assertEqual(type(self.form.fields['page'].widget), AdminPageChooser)

    def test_render_js_init(self):
        result = self.page_chooser_panel.render_as_field()
        expected_js = 'createPageChooser("{id}", ["{model}"], {parent}, false, null);'.format(
            id="id_page", model="wagtailcore.page", parent=self.events_index_page.id)

        self.assertIn(expected_js, result)

    def test_render_js_init_with_can_choose_root_true(self):
        # construct an alternative page chooser panel object, with can_choose_root=True

        my_page_object_list = ObjectList([
            PageChooserPanel('page', can_choose_root=True)
        ]).bind_to(model=PageChooserModel)
        my_page_chooser_panel = my_page_object_list.children[0]
        PageChooserForm = my_page_object_list.get_form_class()

        form = PageChooserForm(instance=self.test_instance)
        page_chooser_panel = my_page_chooser_panel.bind_to(
            instance=self.test_instance, form=form, request=self.request)
        result = page_chooser_panel.render_as_field()

        # the canChooseRoot flag on createPageChooser should now be true
        expected_js = 'createPageChooser("{id}", ["{model}"], {parent}, true, null);'.format(
            id="id_page", model="wagtailcore.page", parent=self.events_index_page.id)
        self.assertIn(expected_js, result)

    def test_get_chosen_item(self):
        result = self.page_chooser_panel.get_chosen_item()
        self.assertEqual(result, self.christmas_page)

    def test_render_as_field(self):
        result = self.page_chooser_panel.render_as_field()
        self.assertIn('
help text
', result)
        self.assertIn('Christmas', result)
        self.assertIn(
            ''
            'Edit this page' % self.christmas_page.id,
            result)

    def test_render_as_empty_field(self):
        test_instance = PageChooserModel()
        form = self.PageChooserForm(instance=test_instance)
        page_chooser_panel = self.my_page_chooser_panel.bind_to(
            instance=test_instance, form=form, request=self.request)
        result = page_chooser_panel.render_as_field()

        self.assertIn('
help text
', result)
        self.assertIn('', result)
        self.assertIn('Choose a page', result)

    def test_render_error(self):
        form = self.PageChooserForm({'page': ''}, instance=self.test_instance)
        self.assertFalse(form.is_valid())

        page_chooser_panel = self.my_page_chooser_panel.bind_to(
            instance=self.test_instance, form=form, request=self.request)
        self.assertIn('This field is required.', page_chooser_panel.render_as_field())

    def test_override_page_type(self):
        # Model has a foreign key to Page, but we specify EventPage in the PageChooserPanel
        # to restrict the chooser to that page type
        my_page_object_list = ObjectList([
            PageChooserPanel('page', 'tests.EventPage')
        ]).bind_to(model=EventPageChooserModel)
        my_page_chooser_panel = my_page_object_list.children[0]
        PageChooserForm = my_page_object_list.get_form_class()
        form = PageChooserForm(instance=self.test_instance)
        page_chooser_panel = my_page_chooser_panel.bind_to(
            instance=self.test_instance, form=form, request=self.request)

        result = page_chooser_panel.render_as_field()
        expected_js = 'createPageChooser("{id}", ["{model}"], {parent}, false, null);'.format(
            id="id_page", model="tests.eventpage", parent=self.events_index_page.id)

        self.assertIn(expected_js, result)

    def test_autodetect_page_type(self):
        # Model has a foreign key to EventPage, which we want to autodetect
        # instead of specifying the page type in PageChooserPanel
        my_page_object_list = (ObjectList([PageChooserPanel('page')])
                               .bind_to(model=EventPageChooserModel,
                                        request=self.request))
        my_page_chooser_panel = my_page_object_list.children[0]
        PageChooserForm = my_page_object_list.get_form_class()
        form = PageChooserForm(instance=self.test_instance)
        page_chooser_panel = my_page_chooser_panel.bind_to(
            instance=self.test_instance, form=form)

        result = page_chooser_panel.render_as_field()
        expected_js = 'createPageChooser("{id}", ["{model}"], {parent}, false, null);'.format(
            id="id_page", model="tests.eventpage", parent=self.events_index_page.id)

        self.assertIn(expected_js, result)

    def test_target_models(self):
        result = PageChooserPanel(
            'page',
            'wagtailcore.site'
        ).bind_to(model=PageChooserModel).target_models()
        self.assertEqual(result, [Site])

    def test_target_models_malformed_type(self):
        result = PageChooserPanel(
            'page',
            'snowman'
        ).bind_to(model=PageChooserModel)
        self.assertRaises(ImproperlyConfigured,
                          result.target_models)

    def test_target_models_nonexistent_type(self):
        result = PageChooserPanel(
            'page',
            'snowman.lorry'
        ).bind_to(model=PageChooserModel)
        self.assertRaises(ImproperlyConfigured,
                          result.target_models)

class TestInlinePanel(TestCase, WagtailTestUtils):
    fixtures = ['test.json']

    def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user

    def test_render(self):
        """
        Check that the inline panel renders the panels set on the model
        when no 'panels' parameter is passed in the InlinePanel definition
        """
        speaker_object_list = ObjectList([
            InlinePanel('speakers', label="Speakers", classname="classname-for-speakers")
        ]).bind_to(model=EventPage, request=self.request)
        EventPageForm = speaker_object_list.get_form_class()

        # SpeakerInlinePanel should instruct the form class to include a 'speakers' formset
        self.assertEqual(['speakers'], list(EventPageForm.formsets.keys()))

        event_page = EventPage.objects.get(slug='christmas')

        form = EventPageForm(instance=event_page)
        panel = speaker_object_list.bind_to(instance=event_page, form=form)

        result = panel.render_as_field()

        self.assertIn('
', result)
        self.assertIn('Name:', result)
        self.assertIn('value="Father"', result)
        self.assertIn('Surname:', result)
        self.assertIn('Image:', result)
        self.assertIn('Choose an image', result)

        # rendered panel must also contain hidden fields for id, DELETE and ORDER
        self.assertTagInHTML(
            '<input id="id_speakers-0-id" name="speakers-0-id" type="hidden">',
            result, allow_extra_attrs=True
        )
        self.assertTagInHTML(
            '<input id="id_speakers-0-DELETE" name="speakers-0-DELETE" type="hidden">',
            result, allow_extra_attrs=True
        )
        self.assertTagInHTML(
            '<input id="id_speakers-0-ORDER" name="speakers-0-ORDER" type="hidden">',
            result, allow_extra_attrs=True
        )

        # rendered panel must contain maintenance form for the formset
        self.assertTagInHTML(
            '<input id="id_speakers-TOTAL_FORMS" name="speakers-TOTAL_FORMS" type="hidden">',
            result, allow_extra_attrs=True
        )

        # rendered panel must include the JS initializer
        self.assertIn('var panel = InlinePanel({', result)

    def test_render_with_panel_overrides(self):
        """
        Check that inline panel renders the panels listed in the InlinePanel definition
        where one is specified
        """
        speaker_object_list = ObjectList([
            InlinePanel('speakers', label="Speakers", panels=[
                FieldPanel('first_name', widget=forms.Textarea),
                ImageChooserPanel('image'),
            ]),
        ]).bind_to(model=EventPage, request=self.request)
        speaker_inline_panel = speaker_object_list.children[0]
        EventPageForm = speaker_object_list.get_form_class()

        # speaker_inline_panel should instruct the form class to include a 'speakers' formset
        self.assertEqual(['speakers'], list(EventPageForm.formsets.keys()))

        event_page = EventPage.objects.get(slug='christmas')

        form = EventPageForm(instance=event_page)
        panel = speaker_inline_panel.bind_to(instance=event_page, form=form)

        result = panel.render_as_field()

        # rendered panel should contain first_name rendered as a text area, but no last_name field
        self.assertIn('Name:', result)
        self.assertIn('Father</textarea>', result)
        self.assertNotIn('Surname:', result)

        # test for #338: surname field should not be rendered as a 'stray' label-less field
        self.assertTagInHTML('<input id="id_speakers-0-last_name">', result, count=0, allow_extra_attrs=True)

        self.assertIn('Image:', result)
        self.assertIn('Choose an image', result)

        # rendered panel must also contain hidden fields for id, DELETE and ORDER
        self.assertTagInHTML(
            '<input id="id_speakers-0-id" name="speakers-0-id" type="hidden">',
            result, allow_extra_attrs=True
        )
        self.assertTagInHTML(
            '<input id="id_speakers-0-DELETE" name="speakers-0-DELETE" type="hidden">',
            result, allow_extra_attrs=True
        )
        self.assertTagInHTML(
            '<input id="id_speakers-0-ORDER" name="speakers-0-ORDER" type="hidden">',
            result, allow_extra_attrs=True
        )

        # rendered panel must contain maintenance form for the formset
        self.assertTagInHTML(
            '<input id="id_speakers-TOTAL_FORMS" name="speakers-TOTAL_FORMS" type="hidden">',
            result, allow_extra_attrs=True
        )

        # render_js_init must provide the JS initializer
        self.assertIn('var panel = InlinePanel({', panel.render_js_init())

    @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True)
    def test_no_thousand_separators_in_js(self):
        """
        Test that the USE_THOUSAND_SEPARATOR setting does not screw up the rendering of numbers
        (specifically maxForms=1000) in the JS initializer:
        https://github.com/wagtail/wagtail/pull/2699
        https://github.com/wagtail/wagtail/issues/3227
        """
        speaker_object_list = ObjectList([
            InlinePanel('speakers', label="Speakers", panels=[
                FieldPanel('first_name', widget=forms.Textarea),
                ImageChooserPanel('image'),
            ]),
        ]).bind_to(model=EventPage, request=self.request)
        speaker_inline_panel = speaker_object_list.children[0]
        EventPageForm = speaker_object_list.get_form_class()
        event_page = EventPage.objects.get(slug='christmas')
        form = EventPageForm(instance=event_page)
        panel = speaker_inline_panel.bind_to(instance=event_page, form=form)

        self.assertIn('maxForms: 1000', panel.render_js_init())

    def test_invalid_inlinepanel_declaration(self):
        with self.ignore_deprecation_warnings():
            self.assertRaises(TypeError, lambda: InlinePanel(label="Speakers"))
            self.assertRaises(TypeError, lambda: InlinePanel(EventPage, 'speakers', label="Speakers", bacon="chunky"))

class TestInlinePanelRelatedModelPanelConfigChecks(TestCase):

    def setUp(self):
        self.original_panels = EventPageSpeaker.panels
        delattr(EventPageSpeaker, 'panels')

        def get_checks_result():
            # run checks only with the 'panels' tag
            checks_result = checks.run_checks(tags=['panels'])
            return [warning for warning in checks_result if warning.obj == EventPageSpeaker]

        self.warning_id = 'wagtailadmin.W002'
        self.get_checks_result = get_checks_result

    def tearDown(self):
        EventPageSpeaker.panels = self.original_panels

    def test_page_with_inline_model_with_tabbed_panel_only(self):
        """Test that checks will warn against setting single tabbed panel on InlinePanel model"""

        EventPageSpeaker.settings_panels = [FieldPanel('first_name'), FieldPanel('last_name')]

        warning = checks.Warning(
            "EventPageSpeaker.settings_panels will have no effect on InlinePanel model editing",
            hint="""Ensure that EventPageSpeaker uses `panels` instead of `settings_panels`.
There are no tabs on non-Page model editing within InlinePanels.""",
            obj=EventPageSpeaker,
            id=self.warning_id,
        )

        checks_results = self.get_checks_result()

        self.assertIn(warning, checks_results)

        delattr(EventPageSpeaker, 'settings_panels')

    def test_page_with_inline_model_with_two_tabbed_panels(self):
        """Test that checks will warn against multiple tabbed panels on InlinePanel models"""

        EventPageSpeaker.content_panels = [FieldPanel('first_name')]
        EventPageSpeaker.promote_panels = [FieldPanel('last_name')]

        warning_1 = checks.Warning(
            "EventPageSpeaker.content_panels will have no effect on InlinePanel model editing",
            hint="""Ensure that EventPageSpeaker uses `panels` instead of `content_panels`.
There are no tabs on non-Page model editing within InlinePanels.""",
            obj=EventPageSpeaker,
            id=self.warning_id,
        )
        warning_2 = checks.Warning(
            "EventPageSpeaker.promote_panels will have no effect on InlinePanel model editing",
            hint="""Ensure that EventPageSpeaker uses `panels` instead of `promote_panels`.
There are no tabs on non-Page model editing within InlinePanels.""",
            obj=EventPageSpeaker,
            id=self.warning_id,
        )

        checks_results = self.get_checks_result()

        self.assertIn(warning_1, checks_results)
        self.assertIn(warning_2, checks_results)

        delattr(EventPageSpeaker, 'content_panels')
        delattr(EventPageSpeaker, 'promote_panels')

    def test_page_with_inline_model_with_edit_handler(self):
        """Checks should NOT warn if InlinePanel models use tabbed panels AND edit_handler"""

        EventPageSpeaker.content_panels = [FieldPanel('first_name')]
        EventPageSpeaker.edit_handler = TabbedInterface(
            ObjectList([FieldPanel('last_name')], heading='test')
        )

        # should not be any errors
        self.assertEqual(self.get_checks_result(), [])

        # clean up for future checks
        delattr(EventPageSpeaker, 'edit_handler')
        delattr(EventPageSpeaker, 'content_panels')


text:
package org.codehaus.enunciate.tests.xfire_integration;

import junit.framework.Assert;
import junit.framework.TestCase;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.cite.InfoSet;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.cite.Source;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.data.Event;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.data.Person;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.data.Relationship;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.services.*;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.services.impl.PersonServiceImpl;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.services.impl.RelationshipServiceImpl;
import org.codehaus.enunciate.samples.genealogy.jaxws_client.services.impl.SourceServiceImpl;

import javax.xml.ws.soap.MTOMFeature;
import java.net.URI;
import java.util.*;

/**
 * @author Ryan Heaton
 */
public class TestFullJBossAPIWithJAXWSClient extends TestCase {

  /**
   * Tests the full API
   */
  public void testFullSOAPAPI() throws Exception {
    int port = 8080;
    if (System.getProperty("container.port") != null) {
      port = Integer.parseInt(System.getProperty("container.port"));
    }

    String context = "full";
    if (System.getProperty("container.test.context") != null) {
      context = System.getProperty("container.test.context");
    }

    SourceServiceImpl impl = new SourceServiceImpl("http://localhost:" + port + "/" + context + "/soap-services/sources/source");
    SourceService sourceService = impl;
    Source source = sourceService.getSource("valid");
    Assert.assertEquals("valid", source.getId());
    Assert.assertEquals(URI.create("uri:some-uri"), source.getLink());
    Assert.assertEquals("some-title", source.getTitle());
    assertNull(sourceService.getSource("invalid"));

    try {
      sourceService.getSource("throw");
      fail("Should have thrown the exception.");
    }
    catch (ServiceException e) {
      Assert.assertEquals("some message", e.getMessage());
      Assert.assertEquals("another message", e.getAnotherMessage());
    }

    try {
      sourceService.getSource("unknown");
      fail("should have thrown the unknown source exception.");
    }
    catch (UnknownSourceException e) {
      UnknownSourceBean bean = e.getFaultInfo();
      Assert.assertEquals("unknown", bean.getSourceId());
      Assert.assertEquals(888, bean.getErrorCode());
    }

    Assert.assertEquals("newid", sourceService.addInfoSet("somesource", new InfoSet()));
    Assert.assertEquals("okay", sourceService.addInfoSet("othersource", new InfoSet()));
    Assert.assertEquals("resourceId", sourceService.addInfoSet("resource", new InfoSet()));
    try {
      sourceService.addInfoSet("unknown", new InfoSet());
      fail("Should have thrown the exception.");
    }
    catch (ServiceException e) {
      Assert.assertEquals("unknown source id", e.getMessage());
      Assert.assertEquals("anyhow", e.getAnotherMessage());
    }

    PersonService personService = new PersonServiceImpl("http://localhost:" + port + "/" + context + "/soap-services/PersonServiceService", new MTOMFeature());
    ArrayList<String> ids = new ArrayList<String>(Arrays.asList("id1", "id2", "id3", "id4"));
    Collection persons = personService.readPersons(ids);
    for (Object o : persons) {
      Person person = (Person) o;
      assertTrue(ids.remove(person.getId()));
      Assert.assertEquals(new Date(1L), ((Event) person.getEvents().iterator().next()).getDate());
    }

    Collection<Person> empty = personService.readPersons(null);
    assertTrue(empty == null || empty.isEmpty());

    personService.deletePerson("somebody");
    try {
      personService.deletePerson(null);
      fail("Should have thrown the exception.");
    }
    catch (ServiceException e) {
      Assert.assertEquals("a person id must be supplied", e.getMessage());
      Assert.assertEquals("no person id.", e.getAnotherMessage());
    }

    RelationshipService relationshipService = new RelationshipServiceImpl("http://localhost:" + port + "/" + context + "/soap-services/RelationshipServiceService");
    List list = relationshipService.getRelationships("someid");
    for (int i = 0; i < list.size(); i++) {
      Relationship relationship = (Relationship) list.get(i);
      Assert.assertEquals(String.valueOf(i), relationship.getId());
    }

    try {
      relationshipService.getRelationships("throw");
      fail("Should have thrown the relationship service exception, even though it wasn't annotated with @WebFault.");
    }
    catch (RelationshipException e) {
      Assert.assertEquals("hi", e.getMessage());
    }

    relationshipService.touch();

  }

}


text: The Client Secret represents hash Application Secret