text:
package org.sakaiproject.tool.assessment.ui.listener.delivery;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.LearningResourceStoreService;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Actor;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Context;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Object;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Result;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Statement;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb.SAKAI_VERB;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.samigo.util.SamigoConstants;
import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAccessControlIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade;
import org.sakaiproject.tool.assessment.services.FinFormatException;
import org.sakaiproject.tool.assessment.services.GradebookServiceException;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.services.ItemService;
import org.sakaiproject.tool.assessment.services.SaLengthException;
import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService;
import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.FinBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.ItemContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.shared.PersonBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.tool.assessment.util.SamigoLRSStatements;
import org.sakaiproject.tool.assessment.util.TextFormat;
import org.sakaiproject.user.api.Preferences;
import org.sakaiproject.user.api.PreferencesService;
import org.sakaiproject.user.api.UserDirectoryService;

/**
 *

 * Title: Samigo
 *

 *

 * Purpose: This listener is called in delivery when the user clicks on submit,
 * save, or previous, next, toc.... It calculates and saves scores in DB
 *
 * @version $Id: SubmitToGradingActionListener.java 11634 2006-07-06 17:35:54Z
 *          daisyf@stanford.edu $
 */

public class SubmitToGradingActionListener implements ActionListener {
	private static final Logger log = LoggerFactory.getLogger(SubmitToGradingActionListener.class);
    private final EventTrackingService eventTrackingService= ComponentManager.get( EventTrackingService.class );

	/**
	 * The publishedAssesmentService
	 */
	private final PublishedAssessmentService publishedAssesmentService = new PublishedAssessmentService();

	private final PreferencesService preferencesService = ComponentManager.get( PreferencesService.class );
	private final UserDirectoryService userDirectoryService = ComponentManager.get( UserDirectoryService.class );

	/**
	 * ACTION.
	 *
	 * @param ae
	 * @throws AbortProcessingException
	 */
	public void processAction(ActionEvent ae) throws AbortProcessingException, FinFormatException, SaLengthException {
		try {
			log.debug("SubmitToGradingActionListener.processAction() ");

			// get managed bean
			DeliveryBean delivery = (DeliveryBean) ContextUtil
					.lookupBean("delivery");

			if ((ContextUtil.lookupParam("showfeedbacknow") != null
					&& "true"
							.equals(ContextUtil.lookupParam("showfeedbacknow")) || delivery
					.getActionMode() == DeliveryBean.PREVIEW_ASSESSMENT))
				delivery.setForGrade(false);

			// get assessment
			PublishedAssessmentFacade publishedAssessment;
			if (delivery.getPublishedAssessment() != null)
				publishedAssessment = delivery.getPublishedAssessment();
			else {
				publishedAssessment = publishedAssesmentService
						.getPublishedAssessment(delivery.getAssessmentId());
				delivery.setPublishedAssessment(publishedAssessment);
			}

			HashMap invalidFINMap = new HashMap();
			ArrayList invalidSALengthList = new ArrayList();
			AssessmentGradingData adata = submitToGradingService(ae, publishedAssessment, delivery, invalidFINMap, invalidSALengthList);
			// set AssessmentGrading in delivery
			delivery.setAssessmentGrading(adata);
            if (adata.getForGrade()) {
                Event event = eventTrackingService.newEvent(SamigoConstants.EVENT_ASSESSMENT_AUTO_GRADED, adata.getPublishedAssessmentTitle(), null, true, NotificationService.NOTI_OPTIONAL, SamigoLRSStatements.getStatementForGradedAssessment(adata, publishedAssessment));
                eventTrackingService.post(event);
            }
			// set url & confirmation after saving the record for grade
			if (delivery.getForGrade())
			{
				setConfirmation(adata, publishedAssessment, delivery);
				setReceiptEmailSetting( delivery );
			}

			if (isForGrade(adata) && !isUnlimited(publishedAssessment)) {
				delivery.setSubmissionsRemaining(delivery
						.getSubmissionsRemaining() - 1);
			}

			if (!invalidFINMap.isEmpty()) {
				delivery.setIsAnyInvalidFinInput(true);
				throw new FinFormatException ("Not a valid FIN input");
			}

			if (!invalidSALengthList.isEmpty()) {
				delivery.setIsAnyInvalidFinInput(true);
				throw new SaLengthException ("Short Answer input is too long");
			}

			delivery.setIsAnyInvalidFinInput(false);

		} catch (GradebookServiceException ge) {
			log.warn(ge.getMessage(), ge);
			FacesContext context = FacesContext.getCurrentInstance();
			String err = (String) ContextUtil.getLocalizedString(
					"org.sakaiproject.tool.assessment.bundle.AuthorMessages",
					"gradebook_exception_error");
			context.addMessage(null, new FacesMessage(err));
		}
	}

	private boolean isForGrade(AssessmentGradingData aData) {
		if (aData != null)
			return (Boolean.TRUE).equals(aData.getForGrade());
		else
			return false;
	}

	private boolean isUnlimited(PublishedAssessmentFacade publishedAssessment) {
		return (Boolean.TRUE).equals(publishedAssessment
				.getAssessmentAccessControl().getUnlimitedSubmissions());
	}

	/**
	 * This method sets the submitting user's receipt email setting from Preferences.
	 * It will either be, 'None', 'Digest', or 'Immediate'.
	 *
	 * @param delivery
	 */
	private void setReceiptEmailSetting( DeliveryBean delivery )
	{
		int submitterEmailReceiptPref = SamigoConstants.NOTI_PREF_DEFAULT;
		Preferences submitterPrefs = preferencesService.getPreferences( userDirectoryService.getCurrentUser().getId() );
		ResourceProperties props = submitterPrefs.getProperties( NotificationService.PREFS_TYPE + SamigoConstants.NOTI_PREFS_TYPE_SAMIGO );
		try
		{
			submitterEmailReceiptPref = (int) props.getLongProperty( "2" );
		}
		catch( EntityPropertyNotDefinedException | EntityPropertyTypeException ex ) { /* User hasn't changed preference */ }

		switch( submitterEmailReceiptPref )
		{
			case NotificationService.PREF_IGNORE:
			{
				delivery.setReceiptEmailSetting( (String) ContextUtil.getLocalizedString(
						"org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "receiptEmail_none") );
				break;
			}
			case NotificationService.PREF_DIGEST:
			{
				delivery.setReceiptEmailSetting( (String) ContextUtil.getLocalizedString(
						"org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "receiptEmail_digest") );
				break;
			}
			case NotificationService.PREF_IMMEDIATE:
			{
				delivery.setReceiptEmailSetting( (String) ContextUtil.getLocalizedString(
						"org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "receiptEmail_immediate") );
				break;
			}
		}
	}

	/**
	 * This method set the url & confirmation string for submitted.jsp. The
	 * confirmation string =
	 * assessmentGradingId-publishedAssessmentId-agentId-submitteddate
	 *
	 * @param adata
	 * @param publishedAssessment
	 * @param delivery
	 */
	private void setConfirmation(AssessmentGradingData adata,
			PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
		if (publishedAssessment.getAssessmentAccessControl() != null) {
			setFinalPage(publishedAssessment, delivery);
			setSubmissionMessage(publishedAssessment, delivery);
		}
		setConfirmationId(adata, publishedAssessment, delivery);
	}

	/**
	 * Set confirmationId which is AssessmentGradingId-TimeStamp.
	 *
	 * @param adata
	 * @param publishedAssessment
	 * @param delivery
	 */
	private void setConfirmationId(AssessmentGradingData adata,
			PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
		delivery.setConfirmation(adata.getAssessmentGradingId() + "-"
				+ publishedAssessment.getPublishedAssessmentId() + "-"
				+ adata.getAgentId() + "-"
				+ adata.getSubmittedDate().toString());
	}

	/**
	 * Set the submission message.
	 *
	 * @param publishedAssessment
	 * @param delivery
	 */
	private void setSubmissionMessage(
			PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
		String submissionMessage = publishedAssessment
				.getAssessmentAccessControl().getSubmissionMessage();
		if (submissionMessage != null)
			delivery.setSubmissionMessage(submissionMessage);
	}

	/**
	 * Set finalPage url in delivery bean.
	 *
	 * @param publishedAssessment
	 * @param delivery
	 */
	private void setFinalPage(PublishedAssessmentFacade publishedAssessment,
			DeliveryBean delivery) {
		String url = publishedAssessment.getAssessmentAccessControl()
				.getFinalPageUrl();
		if (url != null)
			url = url.trim();
		delivery.setUrl(url);
	}

	/**
	 * Invoke submission and return the grading data
	 *
	 * @param publishedAssessment
	 * @param delivery
	 * @return
	 */
	private synchronized AssessmentGradingData submitToGradingService(
			ActionEvent ae, PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery, HashMap invalidFINMap, ArrayList invalidSALengthList) throws FinFormatException {
		log.debug("****1a. inside submitToGradingService ");
		String submissionId = "";
		HashSet<ItemGradingData> itemGradingHash = new HashSet<>();
		// daisyf decoding: get page contents contains SectionContentsBean, a
		// wrapper for SectionDataIfc
		Iterator<SectionContentsBean> iter = delivery.getPageContents().getPartsContents()
				.iterator();
		log.debug("****1b. inside submitToGradingService, iter= " + iter);
		HashSet<ItemGradingData> adds = new HashSet<>();
		HashSet<ItemGradingData> removes = new HashSet<>();

		// we go through all the answer collected from JSF form per each
		// publsihedItem and
		// work out which answer is an new addition and in cases like
		// MC/MCMR/Survey, we will
		// discard any existing one and just save the new one. For other
		// question type, we
		// simply modify the publishedText or publishedAnswer of the existing
		// ones.
		while (iter.hasNext()) {
			SectionContentsBean part = iter.next();
			log.debug("****1c. inside submitToGradingService, part " + part);
			Iterator<ItemContentsBean> iter2 = part.getItemContents().iterator();
			while (iter2.hasNext()) { // go through each item from form
				ItemContentsBean item = iter2.next();
				log.debug("****** before prepareItemGradingPerItem");
				prepareItemGradingPerItem(ae, delivery, item, adds, removes);
				log.debug("****** after prepareItemGradingPerItem");
			}
		}

		AssessmentGradingData adata = persistAssessmentGrading(ae, delivery,
				itemGradingHash, publishedAssessment, adds, removes, invalidFINMap, invalidSALengthList);

		StringBuilder redrawAnchorName = new StringBuilder("p");
		String tmpAnchorName = "";

		Iterator<SectionContentsBean> iterPart = delivery.getPageContents().getPartsContents().iterator();
		while (iterPart.hasNext()) {
			SectionContentsBean part = iterPart.next();
			String partSeq = part.getNumber();
			Iterator<ItemContentsBean> iterItem = part.getItemContents().iterator();
			while (iterItem.hasNext()) { // go through each item from form
				ItemContentsBean item = iterItem.next();
				String itemSeq = item.getSequence();
				Long itemId = item.getItemData().getItemId();
				if (item.getItemData().getTypeId() == 5) {
					if (invalidSALengthList.contains(itemId)) {
						item.setIsInvalidSALengthInput(true);
						redrawAnchorName.append(partSeq);
						redrawAnchorName.append("q");
						redrawAnchorName.append(itemSeq);
						if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
							tmpAnchorName = redrawAnchorName.toString();
						}
					}
					else {
						item.setIsInvalidSALengthInput(false);
					}
				}
				else if (item.getItemData().getTypeId() == 11) {
					if (invalidFINMap.containsKey(itemId)) {
						item.setIsInvalidFinInput(true);
						redrawAnchorName.append(partSeq);
						redrawAnchorName.append("q");
						redrawAnchorName.append(itemSeq);
						if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
							tmpAnchorName = redrawAnchorName.toString();
						}
						ArrayList list = (ArrayList) invalidFINMap.get(itemId);
						List<FinBean> finArray = item.getFinArray();
						Iterator<FinBean> iterFin = finArray.iterator();
						while (iterFin.hasNext()) {
							FinBean finBean = iterFin.next();
							if (finBean.getItemGradingData() != null) {
								Long itemGradingId = finBean.getItemGradingData().getItemGradingId();
								if (list.contains(itemGradingId)) {
									finBean.setIsCorrect(false);
								}
							}
						}
					}
					else {
						item.setIsInvalidFinInput(false);
					}
				}
			}
		}

		if (tmpAnchorName != null && !tmpAnchorName.equals("")) {
			delivery.setRedrawAnchorName(tmpAnchorName);
		}
		else {
			delivery.setRedrawAnchorName("");
		}

		delivery.setSubmissionId(submissionId);
		delivery.setSubmissionTicket(submissionId);// is this the same thing?
		// hmmmm
		delivery.setSubmissionDate(new Date());
		delivery.setSubmitted(true);
		return adata;
	}

	private AssessmentGradingData persistAssessmentGrading(ActionEvent ae,
			DeliveryBean delivery, HashSet<ItemGradingData> itemGradingHash,
			PublishedAssessmentFacade publishedAssessment, HashSet<ItemGradingData> adds,
			HashSet<ItemGradingData> removes, HashMap invalidFINMap, ArrayList invalidSALengthList) throws FinFormatException {
		AssessmentGradingData adata = null;
		if (delivery.getAssessmentGrading() != null) {
			adata = delivery.getAssessmentGrading();
		}

		GradingService service = new GradingService();
		log.debug("**adata=" + adata);
		if (adata == null) { // <--- this shouldn't happened 'cos it should
			// have been created by BeginDelivery
			adata = makeNewAssessmentGrading(publishedAssessment, delivery,
					itemGradingHash);
			delivery.setAssessmentGrading(adata);
		} else {
			// 1. add all the new itemgrading for MC/Survey and discard any
			// itemgrading for MC/Survey
			// 2. add any modified SAQ/TF/FIB/Matching/MCMR/FIN
			// 3. save any modified Mark for Review in FileUplaod/Audio

			HashMap<Long, ItemDataIfc> fibMap = getFIBMap(publishedAssessment);
			HashMap<Long, ItemDataIfc> finMap = getFINMap(publishedAssessment);
			HashMap<Long, ItemDataIfc> calcQuestionMap = getCalcQuestionMap(publishedAssessment); // CALCULATED_QUESTION
			HashMap<Long, ItemDataIfc> imagQuestionMap = getImagQuestionMap(publishedAssessment); // IMAGEMAP_QUESTION
			HashMap<Long, ItemDataIfc> mcmrMap = getMCMRMap(publishedAssessment);
			HashMap<Long, ItemDataIfc> emiMap = getEMIMap(publishedAssessment);
			Set<ItemGradingData> itemGradingSet = adata.getItemGradingSet();
			log.debug("*** 2a. before removal & addition " + (new Date()));
			if (itemGradingSet != null) {
				log.debug("*** 2aa. removing old itemGrading " + (new Date()));
				itemGradingSet.removeAll(removes);
				service.deleteAll(removes);
				// refresh itemGradingSet & assessmentGrading after removal
				log.debug("*** 2ab. reload itemGradingSet " + (new Date()));
				itemGradingSet = service.getItemGradingSet(adata
						.getAssessmentGradingId().toString());
				log.debug("*** 2ac. load assessmentGarding " + (new Date()));
				adata = service.load(adata.getAssessmentGradingId().toString(), false);

				Iterator<ItemGradingData> iter = adds.iterator();
				while (iter.hasNext()) {
					iter.next().setAssessmentGradingId(adata
							.getAssessmentGradingId());
				}
				// make update to old item and insert new item
				// and we will only update item that has been changed
				log
						.debug("*** 2ad. set assessmentGrading with new/updated itemGrading "
								+ (new Date()));
				log
						.debug("Submitforgrading: before calling .....................oldItemGradingSet.size = "
								+ itemGradingSet.size());
				log.debug("Submitforgrading: newItemGradingSet.size = "
						+ adds.size());

				HashSet<ItemGradingData> updateItemGradingSet = getUpdateItemGradingSet(
						itemGradingSet, adds, fibMap, finMap, calcQuestionMap,imagQuestionMap,mcmrMap, emiMap, adata);
				adata.setItemGradingSet(updateItemGradingSet);
			}
		}

		adata.setSubmitFromTimeoutPopup(delivery.getsubmitFromTimeoutPopup());
		adata.setIsLate(isLate(publishedAssessment, delivery.getsubmitFromTimeoutPopup()));
		adata.setForGrade(delivery.getForGrade());

		// If this assessment grading data has been updated (comments or adj. score) by grader and then republic and allow student to resubmit
		// when the student submit his answers, we update the status back to 0 and remove the grading entry/info.
		if (AssessmentGradingData.ASSESSMENT_UPDATED_NEED_RESUBMIT.equals(adata.getStatus()) || AssessmentGradingData.ASSESSMENT_UPDATED.equals(adata.getStatus())) {
			adata.setStatus(0);
			adata.setGradedBy(null);
			adata.setGradedDate(null);
			adata.setComments(null);
			adata.setTotalOverrideScore(0d);
		}

		log.debug("*** 2b. before storingGrades, did all the removes and adds "
				+ (new Date()));

		if (delivery.getNavigation().equals("1") && ae != null && "showFeedback".equals(ae.getComponent().getId())) {
			log.debug("Do not persist to db if it is linear access and the action is show feedback");
			// 3. let's build three HashMap with (publishedItemId, publishedItem),
			// (publishedItemTextId, publishedItem), (publishedAnswerId,
			// publishedItem) to help with storing grades to adata only, not db
			HashMap publishedItemHash = delivery.getPublishedItemHash();
			HashMap publishedItemTextHash = delivery.getPublishedItemTextHash();
			HashMap publishedAnswerHash = delivery.getPublishedAnswerHash();
			service.storeGrades(adata, publishedAssessment, publishedItemHash, publishedItemTextHash, publishedAnswerHash, false, invalidFINMap, invalidSALengthList);
		}
		else {
			log.debug("Persist to db otherwise");
			// The following line seems redundant. I cannot see a reason why we need to save the adata here
			// and then again in following service.storeGrades(). Comment it out.
			//service.saveOrUpdateAssessmentGrading(adata);
			log.debug("*** 3. before storingGrades, did all the removes and adds " + (new Date()));
			// 3. let's build three HashMap with (publishedItemId, publishedItem),
			// (publishedItemTextId, publishedItem), (publishedAnswerId,
			// publishedItem) to help with storing grades to adata and then persist to DB
			HashMap publishedItemHash = delivery.getPublishedItemHash();
			HashMap publishedItemTextHash = delivery.getPublishedItemTextHash();
			HashMap publishedAnswerHash = delivery.getPublishedAnswerHash();
			service.storeGrades(adata, publishedAssessment, publishedItemHash, publishedItemTextHash, publishedAnswerHash, invalidFINMap, invalidSALengthList);
		}
		return adata;
	}

	private HashMap<Long, ItemDataIfc> getFIBMap(PublishedAssessmentIfc publishedAssessment) {
		return publishedAssesmentService.prepareFIBItemHash(publishedAssessment);
	}

  	private HashMap<Long, ItemDataIfc> getFINMap(PublishedAssessmentIfc publishedAssessment){
	    return publishedAssesmentService.prepareFINItemHash(publishedAssessment);
	}

  	/**
  	 * CALCULATED_QUESTION
  	 * @param publishedAssessment
  	 * @return map of calc items
  	 */
  	private HashMap<Long, ItemDataIfc> getCalcQuestionMap(PublishedAssessmentIfc publishedAssessment){
	    return (HashMap<Long, ItemDataIfc>) publishedAssesmentService.prepareCalcQuestionItemHash(publishedAssessment);
	}

  	/**
  	 * IMAGEMAP_QUESTION
  	 * @param publishedAssessment
  	 * @return map of image items
  	 */
  	private HashMap<Long, ItemDataIfc> getImagQuestionMap(PublishedAssessmentIfc publishedAssessment){
	    return (HashMap<Long, ItemDataIfc>) publishedAssesmentService.prepareImagQuestionItemHash(publishedAssessment);
	}

	private HashMap<Long, ItemDataIfc> getMCMRMap(PublishedAssessmentIfc publishedAssessment) {
		return publishedAssesmentService.prepareMCMRItemHash(publishedAssessment);
	}

	private HashMap<Long, ItemDataIfc> getEMIMap(PublishedAssessmentIfc publishedAssessment) {
		PublishedAssessmentService s = new PublishedAssessmentService();
		return s.prepareEMIItemHash(publishedAssessment);
	}

	private HashSet<ItemGradingData> getUpdateItemGradingSet(Set oldItemGradingSet,
			Set<ItemGradingData> newItemGradingSet, HashMap<Long, ItemDataIfc> fibMap, HashMap<Long, ItemDataIfc> finMap, HashMap<Long, ItemDataIfc> calcQuestionMap, HashMap<Long, ItemDataIfc> imagQuestionMap,HashMap<Long, ItemDataIfc> mcmrMap,
			HashMap<Long, ItemDataIfc> emiMap, AssessmentGradingData adata) {
		log.debug("Submitforgrading: oldItemGradingSet.size = "
				+ oldItemGradingSet.size());
		log.debug("Submitforgrading: newItemGradingSet.size = "
				+ newItemGradingSet.size());
		HashSet<ItemGradingData> updateItemGradingSet = new HashSet<>();
		Iterator iter = oldItemGradingSet.iterator();
		HashMap<Long, ItemGradingData> map = new HashMap<>();
		while (iter.hasNext()) { // create a map with old itemGrading
			ItemGradingData item = (ItemGradingData) iter.next();
			map.put(item.getItemGradingId(), item);
		}

		// go through new itemGrading
		Iterator<ItemGradingData> iter1 = newItemGradingSet.iterator();
		while (iter1.hasNext()) {
			ItemGradingData newItem = iter1.next();
			ItemGradingData oldItem = map.get(newItem
					.getItemGradingId());
			if (oldItem != null) {
			    if (!oldItem.equals(newItem) ||
			    //Now Check all the maps
			            fibMap.get(oldItem.getPublishedItemId()) != null
			            || emiMap.get(oldItem.getPublishedItemId()) != null
			            || finMap.get(oldItem.getPublishedItemId())!=null
			            || calcQuestionMap.get(oldItem.getPublishedItemId())!=null
						|| imagQuestionMap.get(oldItem.getPublishedItemId())!=null
			            || mcmrMap.get(oldItem.getPublishedItemId()) != null) {
			        String newAnswerText = ContextUtil.stringWYSIWYG(newItem.getAnswerText());
			        oldItem.setReview(newItem.getReview());
			        oldItem.setPublishedAnswerId(newItem.getPublishedAnswerId());
			        String newRationale = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, newItem.getRationale());
			        oldItem.setRationale(newRationale);
			        oldItem.setAnswerText(newAnswerText);
			        oldItem.setSubmittedDate(new Date());
			        oldItem.setAutoScore(newItem.getAutoScore());
			        oldItem.setOverrideScore(newItem.getOverrideScore());
			        updateItemGradingSet.add(oldItem);
			        // log.debug("**** SubmitToGrading: need update
			        // "+oldItem.getItemGradingId());
			    }
			} else { // itemGrading from new set doesn't exist, add to set in
				// this case
				// log.debug("**** SubmitToGrading: need add new item");
				//a new item should always have the grading ID set to null
				newItem.setItemGradingId(null);
				newItem.setAgentId(adata.getAgentId());
				updateItemGradingSet.add(newItem);
			}
		}
		return updateItemGradingSet;
	}

	/**
	 * Make a new AssessmentGradingData object for delivery
	 *
	 * @param publishedAssessment
	 *            the PublishedAssessmentFacade
	 * @param delivery
	 *            the DeliveryBean
	 * @param itemGradingHash
	 *            the item data
	 * @return
	 */
	private AssessmentGradingData makeNewAssessmentGrading(
			PublishedAssessmentFacade publishedAssessment,
			DeliveryBean delivery, HashSet<ItemGradingData> itemGradingHash) {
		PersonBean person = (PersonBean) ContextUtil.lookupBean("person");
		AssessmentGradingData adata = new AssessmentGradingData();
		adata.setAgentId(person.getId());
		adata.setPublishedAssessmentId(publishedAssessment
				.getPublishedAssessmentId());
		adata.setForGrade(delivery.getForGrade());
		adata.setItemGradingSet(itemGradingHash);
		adata.setAttemptDate(new Date());
		adata.setIsLate(Boolean.FALSE);
		adata.setStatus(0);
		adata.setTotalOverrideScore(Double.valueOf(0));
		adata.setTimeElapsed(Integer.valueOf("0"));
		return adata;
	}

	/**
	 * This is specific to JSF - question for each type is layout differently in
	 * JSF and the answers submitted are being collected differently too. e.g.
	 * for each MC/Survey/MCMR, an itemgrading is associated with each choice.
	 * whereas there is only one itemgrading per each question for SAQ/TF/Audio,
	 * and one for each blank in FIB. To understand the logic in this method, it
	 * is best to study jsf/delivery/item/deliver*.jsp
	 */
	private void prepareItemGradingPerItem(ActionEvent ae, DeliveryBean delivery,
			ItemContentsBean item, HashSet<ItemGradingData> adds, HashSet<ItemGradingData> removes) {
		List<ItemGradingData> grading = item.getItemGradingDataArray();
		int typeId = item.getItemData().getTypeId().intValue();

		//no matter what kinds of type questions, if it marks as review, add it in.
		for (int m = 0; m < grading.size(); m++) {
			ItemGradingData itemgrading = grading.get(m);
			if (itemgrading.getItemGradingId() == null && (itemgrading.getReview() != null && itemgrading.getReview())  == true) {
				adds.add(itemgrading);
			}
		}

		// 1. add all the new itemgrading for MC/Survey and discard any
		// itemgrading for MC/Survey
		// 2. add any modified SAQ/TF/FIB/Matching/MCMR/Audio/FIN
		switch (typeId) {
		case 1: // MC
		case 12: // MC Single Selection
		case 3: // Survey
			boolean answerModified = false;
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);

				if (itemgrading.getItemGradingId() == null
						|| itemgrading.getItemGradingId().intValue() <= 0) { // =>
					// new answer
					if (itemgrading.getPublishedAnswerId() != null || (itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
						answerModified = true;
						break;
					}
				}
			}

			// Click the Reset Selection link
			if(item.getUnanswered()) {
				answerModified = true;
			}

			if (answerModified) {
				for (int m = 0; m < grading.size(); m++) {
					ItemGradingData itemgrading = grading
					.get(m);
					if (itemgrading.getItemGradingId() != null
							&& itemgrading.getItemGradingId().intValue() > 0) {
						// remove all old answer for MC & Surevy
						removes.add(itemgrading);
					} else {
						// add new answer
						if (itemgrading.getPublishedAnswerId() != null
							|| itemgrading.getAnswerText() != null
							|| (itemgrading.getRationale() != null
								&& !itemgrading.getRationale().trim().equals(""))) {
							// null=> skipping this question
							itemgrading.setAgentId(AgentFacade.getAgentString());
							itemgrading.setSubmittedDate(new Date());
							if (itemgrading.getRationale() != null && itemgrading.getRationale().length() > 0) {
								itemgrading.setRationale(TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, itemgrading.getRationale()));
							}
							// the rest of the info is collected by
							// ItemContentsBean via JSF form
							adds.add(itemgrading);
						}
					}
				}
			}
			else{
				handleMarkForReview(grading, adds);
			}
			break;
		case 4: // T/F
		case 9: // Matching
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);
				itemgrading.setAgentId(AgentFacade.getAgentString());
				itemgrading.setSubmittedDate(new Date());
			}
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);
				if ((itemgrading.getItemGradingId() != null	&& itemgrading.getItemGradingId().intValue() > 0) ||
					(itemgrading.getPublishedAnswerId() != null || itemgrading.getAnswerText() != null) ||
					(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
					adds.addAll(grading);
					break;
				}
			}
			break;
		case 5: // SAQ
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);
				itemgrading.setAgentId(AgentFacade.getAgentString());
				itemgrading.setSubmittedDate(new Date());
			}
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);
				if (itemgrading.getItemGradingId() != null
						&& itemgrading.getItemGradingId().intValue() > 0) {
					adds.addAll(grading);
					break;
				} else if (itemgrading.getAnswerText() != null && !itemgrading.getAnswerText().equals("")) {
					// Change to allow student submissions in rich-text [SAK-17021]
					itemgrading.setAnswerText(ContextUtil.stringWYSIWYG(itemgrading.getAnswerText()));
					adds.addAll(grading);
					break;
				}
			}
			break;
		case 8: // FIB
		case 15: // CALCULATED_QUESTION
		case 16: //IMAGEMAP_QUESTION
		case 11: // FIN
			boolean addedToAdds = false;
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);
				itemgrading.setAgentId(AgentFacade.getAgentString());
				itemgrading.setSubmittedDate(new Date());
			}
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);
				if (itemgrading.getItemGradingId() != null
						&& itemgrading.getItemGradingId().intValue() > 0) {
					adds.addAll(grading);
					break;
				} else if (itemgrading.getAnswerText() != null && !itemgrading.getAnswerText().equals("")) {
					String s = itemgrading.getAnswerText();
					log.debug("s = " + s);
					// Change to allow student submissions in rich-text [SAK-17021]
					itemgrading.setAnswerText(ContextUtil.stringWYSIWYG(s));
					adds.addAll(grading);
					if (!addedToAdds) {
						adds.addAll(grading);
						addedToAdds = true;
					}
				}
			}
			break;
		case 2: // MCMR
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);
				if (itemgrading.getItemGradingId() != null
						&& itemgrading.getItemGradingId().intValue() > 0) {
					// old answer, check which one to keep, not keeping null  answer
					if (itemgrading.getPublishedAnswerId() != null ||
						(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
						itemgrading.setAgentId(AgentFacade.getAgentString());
						itemgrading.setSubmittedDate(new Date());
						adds.add(itemgrading);
					} else {
						removes.add(itemgrading);
					}
				} else {
					 // new answer
					if (itemgrading.getPublishedAnswerId() != null ||
							(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
						// new  addition  not accepting any new answer with null for MCMR
						itemgrading.setAgentId(AgentFacade.getAgentString());
						itemgrading.setSubmittedDate(new Date());
						adds.add(itemgrading);
					}
				}
			}
			break;
		case 14: // Extended Matching Item
			Long assessmentGradingId = delivery.getAssessmentGrading().getAssessmentGradingId();
                       	Long publishedItemId = item.getItemData().getItemId();
			log.debug("Updating answer set for EMI question: publishedItemId=" + publishedItemId + " grading.size()=" + grading.size() +
				" item id=" + item.getItemData().getItemId() + " assessmentGradingId=" + assessmentGradingId);

			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
				if (itemgrading.getItemGradingId() != null
						&& itemgrading.getItemGradingId().intValue() > 0) {
					// old answer, check which one to keep, not keeping null  answer
					if (itemgrading.getPublishedAnswerId() != null) {
						itemgrading.setAgentId(AgentFacade.getAgentString());
						itemgrading.setSubmittedDate(new Date());
						adds.add(itemgrading);
						log.debug("adding answer: " + itemgrading.getItemGradingId());
					} else {
						removes.add(itemgrading);
						log.debug("remove answer: " + itemgrading.getItemGradingId());
					}
				} else {
					 // new answer
					if (itemgrading.getPublishedAnswerId() != null) {
						// new  addition  not accepting any new answer with null for EMI
						itemgrading.setAgentId(AgentFacade.getAgentString());
						itemgrading.setSubmittedDate(new Date());
						adds.add(itemgrading);
						log.debug("adding new answer answer: " + itemgrading.getItemGradingId());
					}
				}

			}

			// We need to remove any answer (response) items in the storage that are not in the above lists
			removes.addAll(identifyOrphanedEMIAnswers(grading, publishedItemId, assessmentGradingId));

			break;
		case 6: // File Upload
		case 7: // Audio
                        handleMarkForReview(grading, adds);
                        break;
		case 13: //Matrix Choices question
			answerModified = false;
			for (int m = 0; m < grading.size(); m++) {
				ItemGradingData itemgrading = grading.get(m);
				if (itemgrading !=null && (itemgrading.getItemGradingId() == null || itemgrading.getItemGradingId().intValue() <= 0)) {
					if (itemgrading.getPublishedAnswerId() != null || (itemgrading.getRationale() != null && StringUtils.isNotBlank(itemgrading.getRationale()))) {
						answerModified = true;
						break;
					}
				}
			}
			// Click the Reset Selection link
			if(item.getUnanswered()) {
				answerModified = true;
			}

			if (answerModified) {
				for (int m = 0; m < grading.size(); m++) {
					ItemGradingData itemgrading = grading.get(m);

					// Remove all previous answers
					if (itemgrading !=null && itemgrading.getItemGradingId() != null && itemgrading.getItemGradingId().intValue() > 0) {
						removes.add(itemgrading);
					}

					// Add all provided answers, regardless if they're new or not
					if (itemgrading !=null && (itemgrading.getPublishedAnswerId() != null || itemgrading.getAnswerText() != null
							|| (itemgrading.getRationale() != null && StringUtils.isNotBlank(itemgrading.getRationale())))) {
						itemgrading.setAgentId(AgentFacade.getAgentString());
						itemgrading.setSubmittedDate(new Date());
						if (itemgrading.getRationale() != null && itemgrading.getRationale().length() > 0) {
							itemgrading.setRationale(TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, itemgrading.getRationale()));
						}
						adds.add(itemgrading);
					}
				}
			}
			else{
				updateItemGradingData(grading, adds);
			}
			break;

		}
		// if it is linear access and there is not answer, we add an fake ItemGradingData
		String actionCommand = "";
		if (ae != null) {
			actionCommand = ae.getComponent().getId();
			log.debug("ae is not null, getActionCommand() = " + actionCommand);
		}
		else {
			log.debug("ae is null");
		}

		if ("1".equals(delivery.getNavigation()) && adds.isEmpty() && !"showFeedback".equals(actionCommand)) {
			log.debug("enter here");
			Long assessmentGradingId = delivery.getAssessmentGrading().getAssessmentGradingId();
			Long publishedItemId = item.getItemData().getItemId();
			log.debug("assessmentGradingId = " + assessmentGradingId);
			log.debug("publishedItemId = " + publishedItemId);
			GradingService gradingService = new GradingService();

			if (gradingService.getItemGradingData(assessmentGradingId.toString(), publishedItemId.toString()) == null) {
				log.debug("Create a new (fake) ItemGradingData");
				ItemGradingData itemGrading = new ItemGradingData();
				itemGrading.setAssessmentGradingId(assessmentGradingId);
				itemGrading.setAgentId(AgentFacade.getAgentString());
				itemGrading.setPublishedItemId(publishedItemId);
				ItemService itemService = new ItemService();
				Long itemTextId = itemService.getItemTextId(publishedItemId);
				log.debug("itemTextId = " + itemTextId);
				if(itemTextId != -1){
					itemGrading.setPublishedItemTextId(itemTextId);
					adds.add(itemGrading);
				}
			}
			else {
				// For File Upload question, if user clicks on "Upload", a ItemGradingData will be created.
				// Therefore, when user clicks on "Next", we shouldn't create it again.
				// Same for Audio question, if user records anything, a ItemGradingData will be created.
				// We don't create it again when user clicks on "Next".
				if ((typeId == 6 || typeId == 7)) {
					log.debug("File Upload or Audio! Do not create empty ItemGradingData if there exists one");
				}
			}
		}
	}

	/**
	 * Identify the items in an EMI Answer that are orphaned
	 * @param grading
	 * @return a list of ItemGradings to be removed
	 */
    private Collection<ItemGradingData> identifyOrphanedEMIAnswers(List<ItemGradingData> grading, Long publishedItemId, Long assessmentGradingId) {
	Set<ItemGradingData> ret = new HashSet<>();

	List<Long> itemsInGrading = new ArrayList<>();
	for (int i = 0; i < grading.size(); i++) {
		ItemGradingData data = grading.get(i);
		itemsInGrading.add(data.getItemGradingId());
	}

    	GradingService gradingService = new GradingService();
    	List<ItemGradingData> data = gradingService.getAllItemGradingDataForItemInGrading(assessmentGradingId, publishedItemId);
    	log.debug("got " + data.size() + " answers from storage");
    	log.debug("got " + grading.size() + " items in the grading object");
    	for (int i = 0; i < data.size(); i++) {
    		ItemGradingData item = data.get(i);
    		if (!itemsInGrading.contains(item.getItemGradingId())) {
    			log.debug("we will remove "  + item.getItemGradingId());
    			ret.add(item);
    		}
    	}

	return ret;
   }

    private void updateItemGradingData(List<ItemGradingData> grading, HashSet<ItemGradingData> adds){
        for (int m = 0; m < grading.size(); m++) {
          ItemGradingData itemgrading = grading.get(m);
          if (itemgrading.getItemGradingId() != null && itemgrading.getItemGradingId().intValue() > 0)  {
        	  adds.add(itemgrading);
          }
        }
      }

    private void handleMarkForReview(List<ItemGradingData> grading, HashSet<ItemGradingData> adds){
      for (int m = 0; m < grading.size(); m++) {
        ItemGradingData itemgrading = grading.get(m);
        if (itemgrading.getItemGradingId() != null
            && itemgrading.getItemGradingId().intValue() > 0
            && itemgrading.getReview() != null)  {
            // we will save itemgrading even though answer was not modified
            // 'cos mark for review may have been modified
          adds.add(itemgrading);
        }
      }
    }

	private Boolean isLate(PublishedAssessmentIfc pub, boolean submitFromTimeoutPopup) {
		AssessmentAccessControlIfc a = pub.getAssessmentAccessControl();
		// If submit from timeout popup, we don't record LATE
		if(submitFromTimeoutPopup) {
			return Boolean.FALSE;
		}

		if (a.getDueDate() != null && a.getDueDate().before(new Date()))
			return Boolean.TRUE;
		else
			return Boolean.FALSE;
	}
}


text:
export * from './createPortal'
export * from './createError'
export * from './functional'
export * from './unit'
export * from './modifyEmit'
export * from './waitFrames'
export * from './assign'

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;
using FluorineFx.Messaging.Config;

namespace FluorineFx.Messaging
{
	/// <summary>
	/// This class is used by the IFlexFactory to store the configuration for an instance created by the factory.
	/// There is one of these for each destination currently since only destinations create these components.
	/// </summary>
	public class FactoryInstance
	{
        /// <summary>
        /// Request scope constant.
        /// </summary>
        public const string RequestScope = "request";
        /// <summary>
        /// Session scope constant.
        /// </summary>
        public const string SessionScope = "session";
        /// <summary>
        /// Application scope constant.
        /// </summary>
        public const string ApplicationScope = "application";

		IFlexFactory _factory;
		string _id;
        DestinationProperties _properties;
		string _scope;
		string _source;
		string _attributeId;

		/// <summary>
        /// Initializes a new instance of the FactoryInstance class.
		/// </summary>
		/// <param name="factory">The IFlexFactory this FactoryInstance is created from.</param>
		/// <param name="id">The Destination's id.</param>
		/// <param name="properties">The configuration properties for this destination.</param>
        public FactoryInstance(IFlexFactory factory, string id, DestinationProperties properties)
		{
			_factory = factory;
			_id = id;
			_properties = properties;
		}
        /// <summary>
        /// Gets the Destination identity.
        /// </summary>
		public string Id
		{
			get{ return _id; }
		}
        /// <summary>
        /// Gets or sets the FactoryInstance scope.
        /// </summary>
		public virtual string Scope
		{
			get{ return _scope; }
			set{ _scope = value; }
		}
        /// <summary>
        /// Gets or sets the FactoryInstance source.
        /// </summary>
		public virtual string Source
		{
			get{ return _source; }
			set{ _source = value; }
		}
        /// <summary>
        /// Gets or sets the FactoryInstance attribute identity.
        /// </summary>
        /// <remarks>Which attribute the component is stored in.</remarks>
		public string AttributeId
		{
			get{ return _attributeId; }
			set{ _attributeId = value; }
		}
        /// <summary>
        /// Gets the configuration properties for this destination.
        /// </summary>
        public DestinationProperties Properties
		{
			get{ return _properties; }
		}
		/// <summary>
		/// If possible, returns the class for the underlying configuration.
		/// This method can return null if the class is not known until the lookup method is called.
		/// The goal is so the factories which know the class at startup time can provide earlier error detection.
		/// If the class is not known, this method can return null and validation will wait until the first lookup call.
		/// </summary>
        /// <returns>A Type instance.</returns>
		public virtual Type GetInstanceClass()
		{
			return null;
		}
		/// <summary>
		/// Return an instance as appropriate for this instance of the given factory. This just calls the lookup method on the factory
		/// that this instance was created on. You override this method to return the specific component for this destination.
		/// </summary>
        /// <returns>Instance of the given factory.</returns>
		public virtual object Lookup()
		{
			return _factory.Lookup(this);
		}
		/// <summary>
		/// When the caller is done with the instance, this method is called. For session scoped components, this gives you the opportunity to
		/// update any state modified in the instance in a remote persistence store.
		/// </summary>
        /// <param name="instance">Instance of the given factory.</param>
		public virtual void OnOperationComplete(object instance)
		{
		}
	}
}


text:
{% extends "layout.html" %}

{% block content %}

  {% include "includes/main_nav.html" %}

Summary - Mr J Smith

      {% set currentClaimantPage = 'summary' %}

      {% include "includes/summary_nav.html" %}
      {% include "includes/summary_table.html" %}

{% endblock %}


text:
<?php

namespace Nelmio\SecurityBundle\Tests\DependencyInjection;

use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Yaml\Yaml;
use Nelmio\SecurityBundle\DependencyInjection\Configuration;
use Symfony\Component\Yaml\Parser;

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    public function testCspReportOnly()
    {
        $this->processYamlConfiguration(
            "csp:\n" .
            "  script:\n" .
            "    - 'self'\n" .
            "  report_only: true"
        );
    }

    public function testCspReportOnlyDefaultIsFalse()
    {
        $config = $this->processYamlConfiguration(
            "csp: ~"
        );
        $this->assertArrayHasKey('report_only', $config['csp']);
        $this->assertFalse($config['csp']['report_only'], 'default value for report_only config should be false');
    }

    public function testCspReportOnlyConfigIsRespectedIfPresent()
    {
        $config = $this->processYamlConfiguration(
            "csp:\n" .
            "  report_only: true"
        );
        $this->assertTrue($config['csp']['report_only']);
    }

    public function testCspWithReportAndEnforceSubtrees()
    {
        $this->processYamlConfiguration(
            "csp:\n" .
            "  report:\n" .
            "    script-src:\n" .
            "      - 'self'\n" .
            "  enforce:\n" .
            "    script-src:\n" .
            "      - 'self'"
        );
    }

    /**
     * @expectedException Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage report_only" and "(report|enforce)" can not be used together
     */
    public function testCspExclusiveReportOnlyAndEnforceSubtree()
    {
        $this->processYamlConfiguration(
            "csp:\n" .
            "  report_only:\n" .
            "  enforce:\n" .
            "    script-src:\n" .
            "      - 'self'"
        );
    }

    /**
     * @expectedException Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage report_only" and "(report|enforce)" can not be used together
     */
    public function testCspExclusiveReportOnlyAndReportSubtree()
    {
        $this->processYamlConfiguration(
            "csp:\n" .
            "  report_only:\n" .
            "  report:\n" .
            "    script-src:\n" .
            "      - 'self'"
        );
    }

    private function processYamlConfiguration($config)
    {
        $parser = new Parser();
        return $this->processYaml($parser->parse($config));
    }

    private function processYaml($parsedYaml)
    {
        $processor = new Processor();
        $configDefinition = new Configuration();
        return $processor->processConfiguration($configDefinition, array($parsedYaml));
    }
}


text:
package com.github.mauricio.async.db.mysql.message.server

case class AuthenticationSwitchRequest(method: String, seed: String) extends ServerMessage(ServerMessage.EOF)


text:
@implementation YunImageHelper

+ (NSString *)base64FormImg:(UIImage *)image {
    return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

+ (UIImage *)imgFromBase64:(NSString *)strEncodeData {
    NSData *data = [[NSData alloc] initWithBase64EncodedString:strEncodeData
                                                       options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}

@end


text:
package org.apache.maven.project;

import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.graph.DependencyFilter;

/**
 * @author Benjamin Bentmann
 */
public class DefaultDependencyResolutionRequest
    implements DependencyResolutionRequest
{

    private MavenProject project;

    private DependencyFilter filter;

    private RepositorySystemSession session;

    public DefaultDependencyResolutionRequest()
    {
        // enables default constructor
    }

    public DefaultDependencyResolutionRequest( MavenProject project, RepositorySystemSession session )
    {
        setMavenProject( project );
        setRepositorySession( session );
    }

    public DependencyFilter getResolutionFilter()
    {
        return filter;
    }

    public MavenProject getMavenProject()
    {
        return project;
    }

    public RepositorySystemSession getRepositorySession()
    {
        return session;
    }

    public DependencyResolutionRequest setResolutionFilter( DependencyFilter filter )
    {
        this.filter = filter;
        return this;
    }

    public DependencyResolutionRequest setMavenProject( MavenProject project )
    {
        this.project = project;
        return this;
    }

    public DependencyResolutionRequest setRepositorySession( RepositorySystemSession repositorySession )
    {
        this.session = repositorySession;
        return this;
    }

}


text:
import { PaginationInstance } from 'ngx-pagination';
import { Observable, of } from 'rxjs';

/**
 * Central class for pagination support. Holds typed collections that can be
 * paginated over.
 *
 * @author Gunnar Hillert
 */
export class Page<T> {
  totalPages: number;
  totalElements: number;

  /**
   * The page number is 0-index-based.
   */
  pageNumber = 0;
  pageSize = 10;
  items: T[] = [];
  filter = {};
  sort = {};
  paginationId: 'pagination-instance';

  public static fromJSON<T>(input): Page<T> {
    const page = new Page<T>();
    if (input && input.page) {
      page.pageNumber = input.page.number;
      page.pageSize = input.page.size;
      page.totalElements = input.page.totalElements;
      page.totalPages = input.page.totalPages;
    }
    return page;
  }

  /**
   * Helper method for ngx-pagination. Allows for passing in
   * pagination meta information directly to ngx-pagination
   * by conforming to the {@link PaginationInstance} interface.
   *
   * If using multiple pagination controls on the page,
   * you may need to set the {@link Page#paginationId} to a different
   * value.
   *
   * One important fact is that the returned currentPage number
   * for {@link PaginationInstance} is 1-index-based. The conversion
   * is done implicitly.
   */
  public getPaginationInstance(): PaginationInstance {
    return {
      id: this.paginationId,
      itemsPerPage: this.pageSize,
      currentPage: this.pageNumber + 1,
      totalItems: this.totalElements
    };
  }

  public getItemsAsObservable(): Observable<T[]> {
    return of(this.items);
  }

  public update(page: Page<T> ) {
    this.items.length = 0;
    this.items.push(...page.items);
    this.pageNumber = page.pageNumber;
    this.pageSize = page.pageSize;
    this.totalElements = page.totalElements;
    this.totalPages = page.totalPages;
  }

}


text:
<?php

namespace Content\Model;

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class Text implements InputFilterAwareInterface
{
    public $id;
    public $sectionId;
    public $name;
    public $alias;
    public $text;
    public $image;

    private $serviceLocator;

    protected $inputFilter;

    public function __construct($serviceLocator = null)
    {
        $this->serviceLocator = $serviceLocator;
    }

    public function exchangeArray($data)
    {
        $this->id       = isset($data['id'])        ? (int)     $data['id'] : null;
        $this->sectionId  = isset($data['sectionId'])   ? (int)     $data['sectionId'] : '';
        $this->name    = isset($data['name'])     ? (string)     $data['name'] : '';
        $this->alias   = isset($data['alias'])    ? (string)     $data['alias'] : '';
        $this->text = isset($data['text'])  ? (string)  $data['text'] : '';
        $this->image = isset($data['image'])  ? (string)  $data['image'] : '';
    }

    public function getArrayCopy() {
        return get_object_vars($this);
    }

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

    public function getInputFilter($action = 'add')
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();

            $inputFilter->add(array('name' => 'id', 'required' => false, 'filters' => array( array('name' => 'Int'), )));
            $inputFilter->add(array('name' => 'sectionId', 'required' => false, 'filters' => array( array('name' => 'Int'), )));
            $inputFilter->add(array('name' => 'name', 'required' => true,
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name' => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min' => 1,
                            'max' => 255,
                        ),
                    ),
                ),
            ));
            $inputFilter->add(array('name' => 'alias', 'required' => true,
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                    array('name' => 'StringToLower'),
                ),
                'validators' => array(
                    array(
                        'name' => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min' => 1,
                            'max' => 255,
                        ),
                    ),
                    array(
                        'name' => 'Regex',
                        'options' => array(
                            'pattern' => '/[a-z0-9_-]+/iu',
                        ),
                    ),
                ),
            ));

            if (isset($this->serviceLocator)) {
                $inputFilter->get('name')->getValidatorChain()->addByName('Db\NoRecordExists', array(
                    'table'   => 'content_texts',
                    'field'   => 'alias',
                    'exclude' => $this->id != null ? array('field' => 'id', 'value' => $this->id) : null,
                    'adapter' => $this->serviceLocator->get('Zend\Db\Adapter\Adapter')
                ));
            }

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }

}


text:
package org.codehaus.griffon.runtime.hessian.monitor;

import griffon.annotations.core.Nonnull;
import griffon.core.env.Metadata;
import griffon.plugins.hessian.HessianClient;
import griffon.plugins.hessian.HessianClientStorage;
import org.codehaus.griffon.runtime.monitor.AbstractObjectStorageMonitor;

/**
 * @author Andres Almiray
 */
public class HessianClientStorageMonitor extends AbstractObjectStorageMonitor<HessianClient> implements HessianClientStorageMonitorMXBean {
    public HessianClientStorageMonitor(@Nonnull Metadata metadata, @Nonnull HessianClientStorage delegate) {
        super(metadata, delegate);
    }

    @Override
    protected String getStorageName() {
        return "hessian";
    }
}


text:
require 'puppet/network/http/handler'
require 'resolv'
require 'webrick'

class Puppet::Network::HTTP::WEBrickREST < WEBrick::HTTPServlet::AbstractServlet

  include Puppet::Network::HTTP::Handler

  def initialize(server, handler)
    raise ArgumentError, "server is required" unless server
    super(server)
    initialize_for_puppet(:server => server, :handler => handler)
  end

  # Retrieve the request parameters, including authentication information.
  def params(request)
    result = request.query
    result = decode_params(result)
    result.merge(client_information(request))
  end

  # WEBrick uses a service method to respond to requests.  Simply delegate to the handler response method.
  def service(request, response)
    process(request, response)
  end

  def accept_header(request)
    request["accept"]
  end

  def content_type_header(request)
    request["content-type"]
  end

  def http_method(request)
    request.request_method
  end

  def path(request)
    request.path
  end

  def body(request)
    request.body
  end

  def client_cert(request)
    request.client_cert
  end

  # Set the specified format as the content type of the response.
  def set_content_type(response, format)
    response["content-type"] = format_to_mime(format)
  end

  def set_response(response, result, status = 200)
    response.status = status
    if status >= 200 and status != 304
      response.body = result
      response["content-length"] = result.stat.size if result.is_a?(File)
    end
    response.reason_phrase = result if status < 200 or status >= 300
  end

  # Retrieve node/cert/ip information from the request object.
  def client_information(request)
    result = {}
    if peer = request.peeraddr and ip = peer[3]
      result[:ip] = ip
    end

    # If they have a certificate (which will almost always be true)
    # then we get the hostname from the cert, instead of via IP
    # info
    result[:authenticated] = false
    if cert = request.client_cert and nameary = cert.subject.to_a.find { |ary| ary[0] == "CN" }
      result[:node] = nameary[1]
      result[:authenticated] = true
    else
      result[:node] = resolve_node(result)
    end

    result
  end
end


text:
class Profile;

namespace gfx {
class Canvas;
}

// ProfileMenuButton
//
// Shows the button for the multiprofile menu with an image layered
// underneath that displays the profile tag.

class ProfileMenuButton : public views::MenuButton {
 public:
  // DefaultActiveTextShadow is a darkened blue color that works with Windows
  // default theme background coloring.
  static const SkColor kDefaultActiveTextShadow = 0xFF708DB3;
  // InactiveTextShadow is a light gray for inactive default themed buttons.
  static const SkColor kDefaultInactiveTextShadow = SK_ColorLTGRAY;
  // DarkTextShadow is used to shadow names on themed browser frames.
  static const SkColor kDarkTextShadow = SK_ColorGRAY;
  // Space between window controls and end of profile tag.
  static const int kProfileTagHorizontalSpacing = 5;

  ProfileMenuButton(views::ButtonListener* listener,
                    const std::wstring& text,
                    views::ViewMenuDelegate* menu_delegate,
                    Profile* profile);

  virtual ~ProfileMenuButton();

  // Override MenuButton to clamp text at kMaxTextWidth.
  virtual void SetText(const std::wstring& text) OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(ProfileMenuButton);
};

#endif  // CHROME_BROWSER_UI_VIEWS_PROFILE_MENU_BUTTON_H_


text:
import postcss from 'postcss';

import filterSelector from './filter-selector';

import { PRESERVE_LINES_END, PRESERVE_LINES_START } from '../const';

/**
 * Provide a PostCSS plugin for extracting and replacing CSS selectors.
 */
export default function postcssSelectorExtract(filters = [], preserveLines = false) {
  return postcss.plugin(`postcss-extract-selectors`, () => (nodes) => {
    // We have to force `any` type, because postcss type
    // definitions seem to be outdated.
    nodes.walkRules((rule) => {
      const ruleSelectors = rule.selector
        .split(`,`)
        .map(ruleSelector => ruleSelector.replace(/(\r\n|\n|\r)/gm, ``).trim())
        .map(ruleSelector => filterSelector({
          ruleSelector,
          ruleParentSelectors: rule.parent.selector ? rule.parent.selector.split(`,`) : [],
          filters,
        }))
        .filter(ruleSelector => ruleSelector.length);

      if (ruleSelectors.length) {
        // eslint-disable-next-line no-param-reassign
        rule.selector = ruleSelectors.join(`,`);
      } else {
        if (preserveLines) {
          const ruleLines = rule.toString().split(/\r\n|\r|\n/).length;

          rule.cloneBefore({
            type: `comment`,
            text: `${PRESERVE_LINES_START}${`\n`.repeat(ruleLines - 1)}${PRESERVE_LINES_END}`,
            raws: Object.assign(rule.raws, { left: ` `, right: ` ` }),
          });
        }
        rule.remove();
      }
    });

    // Remove empty @ rules.
    nodes.walkAtRules((rule) => {
      if (rule.nodes && !rule.nodes.length) {
        rule.remove();
      }
    });
  });
}


text:
My Account {{vm.user.nickname}} ({{vm.user.email}})

My Address

 Create a new address

          <address>
            {{vm.user.address.street}}

            {{vm.user.address.city}}, {{vm.user.address.state}} {{vm.user.address.zip}}
          </address>


text:
namespace SolrNet
{
    public interface ISolrOperationsProvider {
        ISolrBasicOperations<T> GetBasicOperations<T>(string url);

        ISolrOperations<T> GetOperations<T>(string url);
    }
}


text:
class Profile;

namespace extensions {

// Class used to read icons of extensions-based bookmark apps.
// TODO(crbug.com/877898): Erase this subclass once BookmarkApps are off
// Extensions.
class BookmarkAppIconManager : public web_app::AppIconManager {
 public:
  explicit BookmarkAppIconManager(Profile* profile);
  ~BookmarkAppIconManager() override;

  // AppIconManager:
  bool HasIcons(
      const web_app::AppId& app_id,
      const std::vector<SquareSizePx>& icon_sizes_in_px) const override;
  bool HasSmallestIcon(const web_app::AppId& app_id,
                       SquareSizePx icon_size_in_px) const override;
  void ReadIcons(const web_app::AppId& app_id,
                 const std::vector<SquareSizePx>& icon_sizes_in_px,
                 ReadIconsCallback callback) const override;
  void ReadAllIcons(const web_app::AppId& app_id,
                    ReadIconsCallback callback) const override;
  void ReadAllShortcutIcons(const web_app::AppId& app_id,
                            ReadShortcutIconsCallback callback) const override;
  void ReadSmallestIcon(const web_app::AppId& app_id,
                        SquareSizePx icon_size_in_px,
                        ReadIconCallback callback) const override;
  void ReadSmallestCompressedIcon(
      const web_app::AppId& app_id,
      SquareSizePx icon_size_in_px,
      ReadCompressedIconCallback callback) const override;

 private:
  Profile* const profile_;

  DISALLOW_COPY_AND_ASSIGN(BookmarkAppIconManager);
};

}  // namespace extensions

#endif  // CHROME_BROWSER_WEB_APPLICATIONS_EXTENSIONS_BOOKMARK_APP_ICON_MANAGER_H_


text:
layout: example
title: Navbar template
---

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

      </button>
      Project name

Home

About

Contact

            Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Default

Static top

Fixed top

Navbar example

This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

      View navbar docs »


text: GIFs sind böse!


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
		"http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>doh.robot ColorPalette Test</title>

		<style>
			@import "../../../util/doh/robot/robot.css";
		</style>

		<!-- required: dojo.js -->
		<script type="text/javascript" src="../../../dojo/dojo.js"
			djConfig="isDebug: true"></script>

		<script type="text/javascript">
			dojo.require("dijit.robotx");

			dojo.addOnLoad(function(){
				doh.robot.initRobot('../test_ColorPalette.html');

				var big, small, prog;

				// log of calls to onChange handler
				var changes = [];

				doh.register("dijit.ColorPalette tests", [
					{
						name: "initial conditions",
						setUp: function(){

							// refs to ColorPalette widgets
					    	big = dijit.byId("big");
					    	small = dijit.byId("small");
					    	prog = dijit.byId("prog");

					    	// setup onChange handler to monitor onChange calls
							dojo.connect(big, 'onChange', function(val){
								console.log('onchange w/value: ', val);
								changes.push(val);
							});
						},
						runTest: function(){
							doh.f(big.get('value'), "no value for big");
							doh.f(small.get('value'), "no value for small");
							doh.f(prog.get('value'), "no value for prog");
						}
					},

					// TODO: when attr() is implemented as a setter, add tests like big.set("value", "#ffc0cb")

					{
						name: "focus",
						timeout: 10000,
						runTest: function(){
							var d = new doh.Deferred();

							big.focus();

							doh.robot.sequence(d.getTestCallback(function(){
								doh.is(0, changes.length, "no onchange events yet");

								// test that focus is on top left cell
								var focus = dojo.global.dijit._curFocus;
								doh.t(focus, "something is focused");
								var imgNode = focus.getElementsByTagName("img")[0]
								doh.t(imgNode, "found image node");
                                //
                                var dye = big._getDye(focus);
								doh.is("#ffffff", dye.getValue(), "focused on white");
							}), 500);

							return d;
						}
					},

					{
						name: "arrow navigation",
						timeout: 10000,
						runTest: function(){
							var d = new doh.Deferred(),
								enterPressed = false;

							// Move around some
							doh.robot.keyPress(dojo.keys.RIGHT_ARROW, 500, {});
							doh.robot.keyPress(dojo.keys.RIGHT_ARROW, 500, {});
							doh.robot.keyPress(dojo.keys.DOWN_ARROW, 500, {});
							doh.robot.keyPress(dojo.keys.LEFT_ARROW, 500, {});

							// Focus should follow the current position for the benefit of screen readers.
							doh.robot.sequence(d.getTestErrback(dojo.hitch(this, function(){
								var focus = dojo.global.dijit._curFocus;
								doh.t(focus, "something is focused");

								var imgNode = focus.getElementsByTagName("img")[0]
								doh.t(imgNode, "found image node");
                                //
                                var dye = big._getDye(focus);
								doh.is("#ffc0cb", dye.getValue(), "focused on right color");
							})), 1000);

							// Setup handler to catch onChange event from ENTER keypress below
							handle = dojo.connect(big, "onChange", d.getTestCallback(dojo.hitch(this, function(val){
								dojo.disconnect(handle);
								handle = null;

								doh.is("#ffc0cb", val, "onChange() argument");
								doh.is("#ffc0cb", big.get("value"), "get('value')");

								doh.is(1, changes.length, 'just one onchange event');
								doh.t(enterPressed, "onChange event didn't come until enter key was pressed");

								big.set('value', null);
								doh.is(big.get('value'), null, "value has been cleared");
							})));

							// Select the current value
							doh.robot.sequence(function(){
								enterPressed = true;
							}, 0);
							doh.robot.keyPress(dojo.keys.ENTER, 500, {});

							return d;
						},
						tearDown: function(){
							if(handle){
								dojo.disconnect(handle);
							}
						}
					},

					{
						name: "tab stops",
						timeout: 10000,
						runTest: function(){
							// After the navigation above, make sure that there's (still) exactly one
							// tab stop associated w/the color picker
							var d = new doh.Deferred();

							dojo.byId("beforeBig").focus();
							doh.robot.keyPress(dojo.keys.TAB, 500, {});
							doh.robot.sequence(d.getTestErrback(function(){
								doh.is("pink", dojo.global.dijit._curFocus.title, "tab into colorpalette, focus goes to pink (last focused cell)")
							}), 1000);

							doh.robot.keyPress(dojo.keys.TAB, 500, {});
							doh.robot.sequence(d.getTestErrback(function(){
								doh.is("afterBig", dojo.global.dijit._curFocus.id, "another tab, went to input after ColorPalette")
							}), 1000);

							doh.robot.keyPress(dojo.keys.TAB, 500, {shift: true});
							doh.robot.sequence(d.getTestErrback(function(){
								doh.is("pink", dojo.global.dijit._curFocus.title, "shift-tab back into colorpalette")
							}), 1000);

							doh.robot.keyPress(dojo.keys.TAB, 500, {shift: true});
							doh.robot.sequence(d.getTestCallback(function(){
								doh.is("beforeBig", dojo.global.dijit._curFocus.id, "another shift-tab, to input before ColorPalette")
							}), 1000);

							return d;
						}
					},
					{
						name: "small palette (keyboard)",
						timeout: 10000,
						runTest: function(){
							var d = new doh.Deferred();

							// go to small colorpalette
							dojo.byId("beforeSmall").focus();
							doh.robot.keyPress(dojo.keys.TAB, 500, {});

							// select a value
							doh.robot.keyPress(dojo.keys.DOWN_ARROW, 500, {});
							doh.robot.keyPress(dojo.keys.RIGHT_ARROW, 500, {});
							doh.robot.keyPress(dojo.keys.SPACE, 500, {});

							doh.robot.sequence(d.getTestCallback(function(){
								var value = small.get('value');
								doh.is("#ffff00", value);
							}), 1000);

							return d;
						}
					},

					{
						name: "small palette (mouse)",
						timeout: 10000,
						runTest: function(){
							var d = new doh.Deferred();

							// Testing nls too...
							var red = dojo.query("[title=rojo]", small.domNode);
							doh.is(1, red.length, "found rojo (red)");

							doh.robot.mouseMoveAt(red[0], 500);
							doh.robot.mouseClick({left: true}, 500);
							if(dojo.isMoz){
								// workaround robot bug where first mouse click doesn't happen occasionally :-(
								doh.robot.mouseClick({left: true}, 500);
							}

							var green = dojo.query("[title=verde]", small.domNode);
							doh.is(1, green.length, "found verde (green)");

							doh.robot.mouseMoveAt(green[0], 500);
							doh.robot.mouseClick({left: true}, 500);
							if(dojo.isMoz){
								// workaround robot bug where first mouse click doesn't happen occasionally :-(
								doh.robot.mouseClick({left: true}, 500);
							}

							doh.robot.sequence(d.getTestCallback(function(){
								// test that value set
								var value = small.get('value');
								doh.is("#008000", value, "value");

								// test that focus also got set
								var focus = dojo.global.dijit._curFocus;
								doh.t(focus, "something is focused");
								var imgNode = focus.getElementsByTagName("img")[0]
								doh.t(imgNode, "found image node");
								var dye = small._getDye(focus);
								doh.is("#008000", dye.getValue(), "focused");

								//test that selected style was removed from previously selected cell and added to new selection
								doh.f(dojo.hasClass(red[0], "dijitPaletteCellSelected"),
									"Red swatch should not have selected class, actual class is: " + red[0].className);
								doh.t(dojo.hasClass(green[0], "dijitPaletteCellSelected"),
									"Green swatch should have selected class, actual class is: " + green[0].className);
							}), 1000);

							return d;
						}
					}
				]);

				doh.run();
			});
		</script>
	</head>
</html>


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <servlet>
        <servlet-name>SquidReportingServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.squid.SquidReportingServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SquidInkServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.squid.SquidReportingServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SquidInkLoginServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.squidink.SquidInkLoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SquidInkRegisterServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.squidink.SquidInkRegisterServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>CalamariServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.calamari.CalamariServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>AmbapoServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.ambapo.AmbapoServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>TopsoilServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.topsoil.TopsoilServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SquidInkTestServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.squidink.SquidInkTester</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SquidInkStartupServlet</servlet-name>
        <servlet-class>org.cirdles.webServices.squidink.SquidInkStartupServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>FileSender</servlet-name>
        <servlet-class>org.cirdles.webServices.squidink.FileSender</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CalamariServlet</servlet-name>
        <url-pattern>/prawn</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SquidInkServlet</servlet-name>
        <url-pattern>/squidinkserve</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SquidInkLoginServlet</servlet-name>
        <url-pattern>/squidinklogin</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SquidInkRegisterServlet</servlet-name>
        <url-pattern>/squidinkregister</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SquidInkStartupServlet</servlet-name>
        <url-pattern>/squidinkstartup</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SquidInkTestServlet</servlet-name>
        <url-pattern>/squidinktester</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SquidReportingServlet</servlet-name>
        <url-pattern>/squidReporting</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>FileSender</servlet-name>
        <url-pattern>/filesender/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>AmbapoServlet</servlet-name>
        <url-pattern>/ambapo/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TopsoilServlet</servlet-name>
        <url-pattern>/topsoil</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
        <init-param>
            <param-name>cors.allowOrigin</param-name>
            <param-value>http://localhost:5000,http://localhost:80,http://localhost:8080</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.methods</param-name>
            <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.headers</param-name>
            <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
        </init-param>
        <init-param>
            <param-name>cors.exposed.headers</param-name>
            <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="Description" content="Ngx Stripe" />
    <title>Ngx Stripe -- Collect payments with Stripe the Angular way</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="msapplication-TileColor" content="#ffffff" />
    <meta name="msapplication-TileImage" content="/assets/favicon/ms-icon-144x144.png" />
    <meta name="theme-color" content="#ffffff" />
    <link rel="manifest" href="/assets/manifest.json" />
    <link rel="apple-touch-icon" sizes="57x57" href="/assets/favicon/apple-icon-57x57.png" />
    <link rel="apple-touch-icon" sizes="60x60" href="/assets/favicon/apple-icon-60x60.png" />
    <link rel="apple-touch-icon" sizes="72x72" href="/assets/favicon/apple-icon-72x72.png" />
    <link rel="apple-touch-icon" sizes="76x76" href="/assets/favicon/apple-icon-76x76.png" />
    <link rel="apple-touch-icon" sizes="114x114" href="/assets/favicon/apple-icon-114x114.png" />
    <link rel="apple-touch-icon" sizes="120x120" href="/assets/favicon/apple-icon-120x120.png" />
    <link rel="apple-touch-icon" sizes="144x144" href="/assets/favicon/apple-icon-144x144.png" />
    <link rel="apple-touch-icon" sizes="152x152" href="/assets/favicon/apple-icon-152x152.png" />
    <link rel="apple-touch-icon" sizes="180x180" href="/assets/favicon/apple-icon-180x180.png" />
    <link rel="icon" type="image/png" sizes="192x192" href="/assets/favicon/android-icon-192x192.png" />
    <link rel="icon" type="image/png" sizes="32x32" href="/assets/favicon/favicon-32x32.png" />
    <link rel="icon" type="image/png" sizes="96x96" href="/assets/favicon/favicon-96x96.png" />
    <link rel="icon" type="image/png" sizes="16x16" href="/assets/favicon/favicon-16x16.png" />
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
  </head>
  <body class="mat-typography">
    <ngstr-root></ngstr-root>
  </body>
</html>


text:
var socketIO = require('socket.io');
var os = require('os');
var fs = require('fs');
var path = require('path');
var Promise = require('es6-promise').Promise;
var events = require('events');
var ClientArray = require('./client-array');
var packageJson = require('../package.json');

function checkAuth(authMethod, token) {
  return new Promise(function (accept, reject) {
    if (typeof authMethod === 'function') {
      var result = authMethod(token);

      if (typeof result === 'object' && typeof result.then === 'function') {
        return result.then(accept, reject);
      } else if (typeof result === 'function') {
        return result(accept, reject);
      } else if (result === true){
        return accept();
      }
    } else if (authMethod === token) {
      return accept();
    }
    reject();
  });
}

function checkIP(ipList, ip) {
  return ipList.reduce(function (result, exp) {
    var regExp = new RegExp('^' + exp
      .replace(/([.:])/g, '\$1')
      .replace(/\*/g, '.*') + '$');
    return regExp.test(ip) || result;
  }, false);
}

function BunyanRemote(options) {
  options = Object.assign({
    auth: BunyanRemote.AUTH_NONE,
    authenticate: function () { return true; }
  }, options);
  var tempFilename = path.join(os.tmpdir(), '/bunyan-' + Date.now());
  var fsStream = fs.createWriteStream(tempFilename, {flags: 'a', encoding: 'utf8'});
  var streamer = new events.EventEmitter();
  var io = socketIO(options.server || 3232);
  io.clients = new ClientArray();

  // check client IP is in allowed list
  io.use(function (socket, next) {
    var clientIp = socket.handshake.address;

    if (!options.allowedIPs || checkIP(options.allowedIPs, clientIp)) return next();
    next(new Error('Connection closed'));
  });

  io.on('connection', function (socket) {

    // send server info
    socket.emit('info', {
      hostname: os.hostname(),
      version: packageJson.version,
      auth: options.auth || BunyanRemote.AUTH_NONE
    });

    // authentication
    socket.on('auth', function (payload) {
      var token = options.auth === BunyanRemote.AUTH_USER ? payload.user + ':' + payload.password : payload;
      var authFunc = options.authenticate;

      if (options.auth === BunyanRemote.AUTH_NONE) {
        authFunc = function () { return true; };
      }

      checkAuth(authFunc, token).then(function onAccept() {
        fs.readFile(tempFilename, {encoding: 'utf8'}, function (err, data) {
          var history = JSON.parse('[' + data.substr(0, data.length - 2) + ']');
          socket.emit('auth', { status: 'ok', history: history });
          io.clients.add(socket);
        });
      }, function onReject() {
        socket.emit('auth', { status: 'error', error: options.auth === BunyanRemote.AUTH_USER ? 'Invalid credentials' : 'Invalid key' });
        socket.disconnect(true);
      });
    });

    socket.on('disconnect', function(){
      io.clients.remove(socket);
    });
  });

  streamer.write = function (record) {
    io.clients.emit('log', record);
    fsStream.write(JSON.stringify(record) + ',\n');
  };

  return {
    type: 'raw',
    stream: streamer,
    level: 'debug',
  };
}

BunyanRemote.AUTH_NONE = 0;
BunyanRemote.AUTH_KEY = 1;
BunyanRemote.AUTH_USER = 2;

module.exports = BunyanRemote;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>ajia</groupId>
		<artifactId>common-aspectj</artifactId>
		<version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>Section10.6ExceptionMonitoring</artifactId>
    <packaging>jar</packaging>
    <name>Section10.6ExceptionMonitoring</name>
</project>


text:
package org.openxava.test.actions;

import org.openxava.actions.*;

/**
 * @author Javier Paniza
 */
public class ChangeZoneAction extends BaseAction {

	public void execute() throws Exception {
		// Not implemented
	}

}