text:
package org.kuali.rice.krad.web.form;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.UifConstants.ViewType;
import org.kuali.rice.krad.uif.UifParameters;
import org.kuali.rice.krad.uif.UifPropertyPaths;
import org.kuali.rice.krad.uif.component.Component;
import org.kuali.rice.krad.uif.lifecycle.ViewPostMetadata;
import org.kuali.rice.krad.uif.service.ViewHelperService;
import org.kuali.rice.krad.uif.service.ViewService;
import org.kuali.rice.krad.uif.util.SessionTransient;
import org.kuali.rice.krad.uif.view.View;
import org.kuali.rice.krad.uif.view.ViewModel;
import org.kuali.rice.krad.util.CsrfValidator;
import org.kuali.rice.krad.util.KRADUtils;
import org.kuali.rice.krad.web.bind.RequestAccessible;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * Base form class for views within the KRAD User Interface Framework.
 *
 *
Holds properties necessary to determine the {@link org.kuali.rice.krad.uif.view.View} instance that
 * will be used to render the user interface

 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class UifFormBase implements ViewModel {

    private static final long serialVersionUID = 8432543267099454434L;

    @RequestAccessible
    protected String viewId;

    @RequestAccessible
    protected String viewName;

    @RequestAccessible
    protected ViewType viewTypeName;

    @RequestAccessible
    protected String pageId;

    @RequestAccessible
    protected String methodToCall;

    @RequestAccessible
    protected String formKey;

    @RequestAccessible
    @SessionTransient
    protected String requestedFormKey;

    @RequestAccessible
    protected String flowKey;

    protected String sessionId;
    protected int sessionTimeoutInterval;

    @SessionTransient
    protected HistoryFlow historyFlow;
    @SessionTransient
    protected HistoryManager historyManager;

    @RequestAccessible
    @SessionTransient
    protected String jumpToId;

    @SessionTransient
    protected String jumpToName;

    @RequestAccessible
    @SessionTransient
    protected String focusId;

    @RequestAccessible
    @SessionTransient
    protected boolean dirtyForm;

    protected String formPostUrl;
    protected String controllerMapping;

    @SessionTransient
    private String requestUrl;
    private Map<String, String[]> initialRequestParameters;

    protected String state;

    @RequestAccessible
    protected boolean renderedInDialog;

    @RequestAccessible
    protected boolean renderedInIframe;

    @SessionTransient
    protected String growlScript;

    @SessionTransient
    protected View view;
    protected ViewPostMetadata viewPostMetadata;

    protected Map<String, String> viewRequestParameters;
    protected List<String> readOnlyFieldsList;

    protected Map<String, Object> newCollectionLines;

    @RequestAccessible
    @SessionTransient
    protected String triggerActionId;

    @RequestAccessible
    @SessionTransient
    protected Map<String, String> actionParameters;

    protected Map<String, Object> clientStateForSyncing;

    @SessionTransient
    protected Map<String, Set<String>> selectedCollectionLines;

    protected Set<String> selectedLookupResultsCache;

    protected List<Object> addedCollectionItems;

    @SessionTransient
    protected MultipartFile attachmentFile;

    // navigation
    @RequestAccessible
    protected String returnLocation;

    @RequestAccessible
    protected String returnFormKey;

    @RequestAccessible
    @SessionTransient
    protected boolean ajaxRequest;

    @RequestAccessible
    @SessionTransient
    protected String ajaxReturnType;

    @SessionTransient
    private String requestJsonTemplate;
    @SessionTransient
    private boolean collectionPagingRequest;

    // dialog fields
    @RequestAccessible
    @SessionTransient
    protected String showDialogId;

    @RequestAccessible
    @SessionTransient
    protected String returnDialogId;

    @RequestAccessible
    @SessionTransient
    protected String returnDialogResponse;

    @RequestAccessible
    protected Map<String, String> dialogExplanations;
    protected Map<String, DialogResponse> dialogResponses;

    @SessionTransient
    protected boolean requestRedirected;

    @RequestAccessible
    @SessionTransient
    protected String updateComponentId;
    @SessionTransient
    private Component updateComponent;

    @RequestAccessible
    protected Map<String, Object> extensionData;

    protected boolean applyDefaultValues;

    protected boolean evaluateFlagsAndModes;
    protected Boolean canEditView;
    protected Map<String, Boolean> actionFlags;
    protected Map<String, Boolean> editModes;

    protected String csrfToken;

    protected HttpServletRequest request;

    private Object dialogDataObject;

    public UifFormBase() {
        renderedInDialog = false;
        renderedInIframe = false;
        requestRedirected = false;

        readOnlyFieldsList = new ArrayList<String>();
        viewRequestParameters = new HashMap<String, String>();
        newCollectionLines = new HashMap<String, Object>();
        actionParameters = new HashMap<String, String>();
        clientStateForSyncing = new HashMap<String, Object>();
        selectedCollectionLines = new HashMap<String, Set<String>>();
        selectedLookupResultsCache = new HashSet<String>();
        addedCollectionItems = new ArrayList<Object>();
        dialogExplanations = new HashMap<String, String>();
        dialogResponses = new HashMap<String, DialogResponse>();
        extensionData = new HashMap<String, Object>();

        applyDefaultValues = true;
        evaluateFlagsAndModes = true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void preBind(HttpServletRequest request) {
        String formKeyParam = request.getParameter(UifParameters.FORM_KEY);
        if (StringUtils.isNotBlank(formKeyParam)) {
            UifFormManager uifFormManager = (UifFormManager) request.getSession().getAttribute(
                    UifParameters.FORM_MANAGER);

            // retrieves the session form and updates the request from with the session transient attributes
            uifFormManager.updateFormWithSession(this, formKeyParam);
        }

        String requestedFormKey = request.getParameter(UifParameters.REQUESTED_FORM_KEY);
        if (StringUtils.isNotBlank(requestedFormKey)) {
            setRequestedFormKey(requestedFormKey);
        } else {
            setRequestedFormKey(formKeyParam);
        }

        String csrfToken = CsrfValidator.getSessionToken(request);
        setCsrfToken(csrfToken);

        this.request = request;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void postBind(HttpServletRequest request) {
        // assign form key if this is a new form or the requested form key is not in session
        UifFormManager uifFormManager = (UifFormManager) request.getSession().getAttribute(UifParameters.FORM_MANAGER);
        if (StringUtils.isBlank(formKey) || !uifFormManager.hasSessionForm(formKey)) {
            formKey = generateFormKey();
        }

        // default form post URL to request URL
        formPostUrl = request.getRequestURL().toString();

        controllerMapping = request.getPathInfo();

        if (request.getSession() != null) {
            sessionId = request.getSession().getId();
            sessionTimeoutInterval = request.getSession().getMaxInactiveInterval();
        }

        // get any sent client view state and parse into map
        if (request.getParameterMap().containsKey(UifParameters.CLIENT_VIEW_STATE)) {
            String clientStateJSON = request.getParameter(UifParameters.CLIENT_VIEW_STATE);
            if (StringUtils.isNotBlank(clientStateJSON)) {
                // change single quotes to double quotes (necessary because the reverse was done for sending)
                clientStateJSON = StringUtils.replace(clientStateJSON, "\\'", "\"");
                clientStateJSON = StringUtils.replace(clientStateJSON, "\\[", "[");
                clientStateJSON = StringUtils.replace(clientStateJSON, "\\]", "]");
                clientStateJSON = StringUtils.replace(clientStateJSON, "'", "\"");

                ObjectMapper mapper = new ObjectMapper();
                try {
                    clientStateForSyncing = mapper.readValue(clientStateJSON, Map.class);
                } catch (IOException e) {
                    throw new RuntimeException("Unable to decode client side state JSON: " + clientStateJSON, e);
                }
            }
        }

        String requestUrl = KRADUtils.stripXSSPatterns(KRADUtils.getFullURL(request));
        setRequestUrl(requestUrl);

        String referer = request.getHeader(UifConstants.REFERER);
        if (StringUtils.isBlank(referer) && StringUtils.isBlank(getReturnLocation())) {
            setReturnLocation(UifConstants.NO_RETURN);
        } else if (StringUtils.isBlank(getReturnLocation())) {
            setReturnLocation(referer);
        }

        if (getInitialRequestParameters() == null) {
            Map<String, String[]> requestParams = new HashMap<String, String[]>();
            Enumeration<String> names = request.getParameterNames();

            while (names != null && names.hasMoreElements()) {
                String name = KRADUtils.stripXSSPatterns(names.nextElement());
                String[] values = KRADUtils.stripXSSPatterns(request.getParameterValues(name));

                requestParams.put(name, values);
            }

            requestParams.remove(UifConstants.UrlParams.LOGIN_USER);
            setInitialRequestParameters(requestParams);
        }

        // populate read only fields list
        if (request.getParameter(UifParameters.READ_ONLY_FIELDS) != null) {
            String readOnlyFields = request.getParameter(UifParameters.READ_ONLY_FIELDS);
            setReadOnlyFieldsList(KRADUtils.convertStringParameterToList(readOnlyFields));
        }

        // collect dialog response, or initialize new map of responses
        if (request.getParameter(UifParameters.RETURN_FROM_DIALOG) != null) {
            String dialogExplanation = null;
            if ((dialogExplanations != null) && dialogExplanations.containsKey(returnDialogId)) {
                dialogExplanation = dialogExplanations.get(returnDialogId);
            }

            DialogResponse response = new DialogResponse(returnDialogId, returnDialogResponse, dialogExplanation);
            this.dialogResponses.put(this.returnDialogId, response);
        } else {
            this.dialogResponses = new HashMap<String, DialogResponse>();
        }

        Object historyManager = request.getSession().getAttribute(UifConstants.HistoryFlow.HISTORY_MANAGER);
        if (historyManager != null && historyManager instanceof HistoryManager) {
            setHistoryManager((HistoryManager) historyManager);

            String flowKey = request.getParameter(UifConstants.HistoryFlow.FLOW);
            setFlowKey(flowKey);
        }

        // clean parameters from XSS attacks that will be written out as hiddens
        this.pageId = KRADUtils.stripXSSPatterns(this.pageId);
        this.methodToCall = KRADUtils.stripXSSPatterns(this.methodToCall);
        this.formKey = KRADUtils.stripXSSPatterns(this.formKey);
        this.requestedFormKey = KRADUtils.stripXSSPatterns(this.requestedFormKey);
        this.flowKey = KRADUtils.stripXSSPatterns(this.flowKey);
        this.sessionId = KRADUtils.stripXSSPatterns(this.sessionId);
        this.formPostUrl = KRADUtils.stripXSSPatterns(this.formPostUrl);
        this.returnLocation = KRADUtils.stripXSSPatterns(this.returnLocation);
        this.returnFormKey = KRADUtils.stripXSSPatterns(this.returnFormKey);
        this.requestUrl = KRADUtils.stripXSSPatterns(this.requestUrl);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void preRender(HttpServletRequest request) {
        // clear dialog properties so previous values do not appear for new dialogs
        this.returnDialogId = null;
        this.returnDialogResponse = null;
        this.dialogExplanations = new HashMap<String, String>();
    }

    /**
     * Creates the unique id used to store this "conversation" in the session.
     * The default method generates a java UUID.
     *
     * @return UUID
     */
    protected String generateFormKey() {
        return UUID.randomUUID().toString();
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getViewId()
     */
    @Override
    public String getViewId() {
        return this.viewId;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setViewId(String)
     */
    @Override
    public void setViewId(String viewId) {
        this.viewId = viewId;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getViewName()
     */
    @Override
    public String getViewName() {
        return this.viewName;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setViewName(String)
     */
    @Override
    public void setViewName(String viewName) {
        this.viewName = viewName;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getViewTypeName()
     */
    @Override
    public ViewType getViewTypeName() {
        return this.viewTypeName;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setViewTypeName(org.kuali.rice.krad.uif.UifConstants.ViewType)
     */
    @Override
    public void setViewTypeName(ViewType viewTypeName) {
        this.viewTypeName = viewTypeName;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getPageId()
     */
    @Override
    public String getPageId() {
        return this.pageId;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setPageId(String)
     */
    @Override
    public void setPageId(String pageId) {
        this.pageId = pageId;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getFormPostUrl()
     */
    @Override
    public String getFormPostUrl() {
        return this.formPostUrl;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setFormPostUrl(String)
     */
    @Override
    public void setFormPostUrl(String formPostUrl) {
        this.formPostUrl = formPostUrl;
    }

    /**
     * Name of the controllerMapping for this form (includes slash)
     *
     * @return the controllerMapping string
     */
    public String getControllerMapping() {
        return controllerMapping;
    }

    /**
     * The current {@link HistoryFlow} for this form which stores a trail of urls/breadcrumbs primarily used for
     * path-based breadcrumb display
     *
     * @return the {@link HistoryFlow}
     */
    public HistoryFlow getHistoryFlow() {
        return historyFlow;
    }

    /**
     * Set the current HistoryFlow for this form
     */
    public void setHistoryFlow(HistoryFlow historyFlow) {
        this.historyFlow = historyFlow;
    }

    /**
     * The current {@link HistoryManager} that was pulled from session which store all {@link HistoryFlow} objects in
     * the current session to keep track of the path the user has taken across views (primarily used by path-based
     * breadcrumbs)
     *
     * @return the HistoryManager
     */
    public HistoryManager getHistoryManager() {
        return historyManager;
    }

    /**
     * Set the current HistoryManager
     */
    public void setHistoryManager(HistoryManager historyManager) {
        this.historyManager = historyManager;
    }

    /**
     * The flowKey representing the HistoryFlow this form may be in.
     *
     *
This allows for a flow to continue by key or start (if set to "start").
     * If null or blank, no flow (or path based
     * breadcrumbs) are being tracked.

     *
     * @return the flowKey
     */
    public String getFlowKey() {
        return flowKey;
    }

    /**
     * Set the flowKey
     */
    public void setFlowKey(String flowKey) {
        this.flowKey = flowKey;
    }

    /**
     * The original requestUrl for the View represented by this form (url received by the controller for initial
     * request)
     *
     * @return the requestUrl
     */
    public String getRequestUrl() {
        return requestUrl;
    }

    /**
     * Set the requestUrl
     */
    public void setRequestUrl(String requestUrl) {
        this.requestUrl = requestUrl;
    }

    /**
     * The requestParameters represent all the parameters in the query string that were initially passed to this View
     * by the initial request
     *
     * @return the requestParameters
     */
    public Map<String, String[]> getInitialRequestParameters() {
        return initialRequestParameters;
    }

    /**
     * Set the requestParameters
     */
    public void setInitialRequestParameters(Map<String, String[]> requestParameters) {
        this.initialRequestParameters = requestParameters;
    }

    public String getReturnLocation() {
        return this.returnLocation;
    }

    public void setReturnLocation(String returnLocation) {
        this.returnLocation = returnLocation;
    }

    public String getReturnFormKey() {
        return this.returnFormKey;
    }

    public void setReturnFormKey(String returnFormKey) {
        this.returnFormKey = returnFormKey;
    }

    /**
     * Holds the id for the user's current session
     *
     *

     * The user's session id is used to track when a timeout has occurred and enforce the policy
     * configured with the {@link org.kuali.rice.krad.uif.view.ViewSessionPolicy}. This property gets initialized
     * in the {@link #postBind(javax.servlet.http.HttpServletRequest)} method and then is written out as a
     * hidden on the view. Therefore each post done on the view will send back the session id when the view was
     * rendering, and the {@link org.kuali.rice.krad.web.filter.UifSessionTimeoutFilter} can use that to determine
     * if a timeout has occurred
     *

     *
     * @return id for the user's current session
     */
    public String getSessionId() {
        return sessionId;
    }

    /**
     * Holds the configured session timeout interval
     *
     *

     * Holds the session timeout interval so it can be referenced to give the user notifications (for example the
     * session timeout warning reads this property). This is initialized from the session object in
     * {@link #postBind(javax.servlet.http.HttpServletRequest)}
     *

     *
     * @return amount of time in milliseconds before the session will timeout
     */
    public int getSessionTimeoutInterval() {
        return sessionTimeoutInterval;
    }

    /**
     * Identifies the controller method that should be invoked to fulfill a
     * request. The value will be matched up against the 'params' setting on the
     * {@code RequestMapping} annotation for the controller method
     *
     * @return String method to call
     */
    public String getMethodToCall() {
        return this.methodToCall;
    }

    /**
     * Setter for the method to call
     */
    public void setMethodToCall(String methodToCall) {
        this.methodToCall = methodToCall;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Map<String, String> getViewRequestParameters() {
        return this.viewRequestParameters;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setViewRequestParameters(Map<String, String> viewRequestParameters) {
        this.viewRequestParameters = viewRequestParameters;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<String> getReadOnlyFieldsList() {
        return readOnlyFieldsList;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setReadOnlyFieldsList(List<String> readOnlyFieldsList) {
        this.readOnlyFieldsList = readOnlyFieldsList;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getNewCollectionLines()
     */
    @Override
    public Map<String, Object> getNewCollectionLines() {
        return this.newCollectionLines;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setNewCollectionLines(Map<String, Object> newCollectionLines) {
        this.newCollectionLines = newCollectionLines;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getTriggerActionId() {
        return triggerActionId;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setTriggerActionId(String triggerActionId) {
        this.triggerActionId = triggerActionId;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getActionParameters()
     */
    @Override
    public Map<String, String> getActionParameters() {
        return this.actionParameters;
    }

    /**
     * Returns the action parameters map as a {@code Properties} instance
     *
     * @return Properties action parameters
     */
    public Properties getActionParametersAsProperties() {
        return KRADUtils.convertMapToProperties(actionParameters);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setActionParameters(Map<String, String> actionParameters) {
        this.actionParameters = actionParameters;
    }

    /**
     * Retrieves the value for the given action parameter, or empty string if
     * not found
     *
     * @param actionParameterName - name of the action parameter to retrieve value for
     * @return String parameter value or empty string
     */
    public String getActionParamaterValue(String actionParameterName) {
        if ((actionParameters != null) && actionParameters.containsKey(actionParameterName)) {
            return actionParameters.get(actionParameterName);
        }

        return "";
    }

    /**
     * Returns the action event that was sent in the action parameters (if any)
     *
     *

     * The action event is a special action parameter that can be sent to indicate a type of action being taken. This
     * can be looked at by the view or components to render differently
     *

     *
     * TODO: make sure action parameters are getting reinitialized on each request
     *
     * @return String action event name or blank if action event was not sent
     */
    public String getActionEvent() {
        if ((actionParameters != null) && actionParameters.containsKey(UifConstants.UrlParams.ACTION_EVENT)) {
            return actionParameters.get(UifConstants.UrlParams.ACTION_EVENT);
        }

        return "";
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getClientStateForSyncing()
     */
    @Override
    public Map<String, Object> getClientStateForSyncing() {
        return clientStateForSyncing;
    }

    /**
     * Setter for the client state
     */
    public void setClientStateForSyncing(Map<String, Object> clientStateForSyncing) {
        this.clientStateForSyncing = clientStateForSyncing;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getSelectedCollectionLines()
     */
    @Override
    public Map<String, Set<String>> getSelectedCollectionLines() {
        return selectedCollectionLines;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setSelectedCollectionLines(Map<String, Set<String>> selectedCollectionLines) {
        this.selectedCollectionLines = selectedCollectionLines;
    }

    /**
     * Holds Set of String identifiers for lines that were selected in a lookup collection results
     * across multiple pages.
     * The value in the cache is preserved in the session across multiple requests. This allows for the
     * server side paging of results to retain the user choices as they move through the pages.
     *
     * @return set of identifiers
     */
    public Set<String> getSelectedLookupResultsCache() {
        return selectedLookupResultsCache;
    }

    /**
     * Sets the lookup result selection cache values
     */
    public void setSelectedLookupResultsCache(Set<String> selectedLookupResultsCache) {
        this.selectedLookupResultsCache = selectedLookupResultsCache;
    }

    /**
     * Key string that identifies the form instance in session storage
     *
     *

     * When the view is posted, the previous form instance is retrieved and then
     * populated from the request parameters. This key string is retrieve the
     * session form from the session service
     *

     *
     * @return String form session key
     */
    public String getFormKey() {
        return this.formKey;
    }

    /**
     * Setter for the form's session key
     */
    public void setFormKey(String formKey) {
        this.formKey = formKey;
    }

    /**
     * This is the formKey sent on the original request.  It may differ from the actual form key stored in formKey
     * based on if the form still exists in session by this key or not.
     *
     * @return the original requested form key
     */
    public String getRequestedFormKey() {
        return requestedFormKey;
    }

    /**
     * Set the requestedFormKey
     */
    public void setRequestedFormKey(String requestedFormKey) {
        this.requestedFormKey = requestedFormKey;
    }

    /**
     * Indicates whether a redirect has been requested for the view
     *
     * @return boolean true if redirect was requested, false if not
     */
    public boolean isRequestRedirected() {
        return requestRedirected;
    }

    /**
     * Setter for the request redirect indicator
     */
    public void setRequestRedirected(boolean requestRedirected) {
        this.requestRedirected = requestRedirected;
    }

    /**
     * Holder for files that are attached through the view
     *
     * @return MultipartFile representing the attachment
     */
    public MultipartFile getAttachmentFile() {
        return this.attachmentFile;
    }

    /**
     * Setter for the form's attachment file
     */
    public void setAttachmentFile(MultipartFile attachmentFile) {
        this.attachmentFile = attachmentFile;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getUpdateComponentId()
     */
    @Override
    public String getUpdateComponentId() {
        return updateComponentId;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setUpdateComponentId(java.lang.String)
     */
    @Override
    public void setUpdateComponentId(String updateComponentId) {
        this.updateComponentId = updateComponentId;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getUpdateComponent()
     */
    public Component getUpdateComponent() {
        return updateComponent;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setUpdateComponent(org.kuali.rice.krad.uif.component.Component)
     */
    public void setUpdateComponent(Component updateComponent) {
        this.updateComponent = updateComponent;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getView()
     */
    @Override
    public View getView() {
        return this.view;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setView(org.kuali.rice.krad.uif.view.View)
     */
    @Override
    public void setView(View view) {
        this.view = view;
    }

    /**
     * Returns an instance of the view's configured view helper service.
     *
     *
First checks if there is an initialized view containing a view helper instance. If not, and there is
     * a view id on the form, a call is made to retrieve the view helper instance or class configuration.

     *
     * {@inheritDoc}
     */
    @Override
    public ViewHelperService getViewHelperService() {
        if ((getView() != null) && (getView().getViewHelperService() != null)) {
            return getView().getViewHelperService();
        }

        String viewId = getViewId();
        if (StringUtils.isBlank(viewId) && (getView() != null)) {
            viewId = getView().getId();
        }

        if (StringUtils.isBlank(viewId)) {
            return null;
        }

        ViewHelperService viewHelperService =
                (ViewHelperService) KRADServiceLocatorWeb.getDataDictionaryService().getDictionaryBeanProperty(viewId,
                        UifPropertyPaths.VIEW_HELPER_SERVICE);
        if (viewHelperService == null) {
            Class<?> viewHelperServiceClass =
                    (Class<?>) KRADServiceLocatorWeb.getDataDictionaryService().getDictionaryBeanProperty(viewId,
                            UifPropertyPaths.VIEW_HELPER_SERVICE_CLASS);

            if (viewHelperServiceClass != null) {
                try {
                    viewHelperService = (ViewHelperService) viewHelperServiceClass.newInstance();
                } catch (Exception e) {
                    throw new RuntimeException("Unable to instantiate view helper class: " + viewHelperServiceClass, e);
                }
            }
        }

        return viewHelperService;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ViewPostMetadata getViewPostMetadata() {
        return viewPostMetadata;
    }

    /**
     * @see UifFormBase#getViewPostMetadata()
     */
    @Override
    public void setViewPostMetadata(ViewPostMetadata viewPostMetadata) {
        this.viewPostMetadata = viewPostMetadata;
    }

    /**
     * Instance of the {@code ViewService} that can be used to retrieve
     * {@code View} instances
     *
     * @return ViewService implementation
     */
    protected ViewService getViewService() {
        return KRADServiceLocatorWeb.getViewService();
    }

    /**
     * The jumpToId for this form, the element with this id will be jumped to automatically
     * when the form is loaded in the view.
     * Using "TOP" or "BOTTOM" will jump to the top or the bottom of the resulting page.
     * jumpToId always takes precedence over jumpToName, if set.
     *
     * @return the jumpToId
     */
    public String getJumpToId() {
        return this.jumpToId;
    }

    /**
     * @param jumpToId the jumpToId to set
     */
    public void setJumpToId(String jumpToId) {
        this.jumpToId = jumpToId;
    }

    /**
     * The jumpToName for this form, the element with this name will be jumped to automatically
     * when the form is loaded in the view.
     * WARNING: jumpToId always takes precedence over jumpToName, if set.
     *
     * @return the jumpToName
     */
    public String getJumpToName() {
        return this.jumpToName;
    }

    /**
     * @param jumpToName the jumpToName to set
     */
    public void setJumpToName(String jumpToName) {
        this.jumpToName = jumpToName;
    }

    /**
     * Field to place focus on when the page loads
     * An empty focusId will result in focusing on the first visible input element by default.
     *
     * @return the focusId
     */
    public String getFocusId() {
        return this.focusId;
    }

    /**
     * @param focusId the focusId to set
     */
    public void setFocusId(String focusId) {
        this.focusId = focusId;
    }

    /**
     * True when the form is considered dirty (data has changed from original value), false otherwise
     *
     *
For most scenarios, this flag should NOT be set to true.
     * If this is set, it must be managed explicitly by the application.  This flag exists for marking a
     * form dirty from a server call, so it must be changed to false when the form is no longer considered dirty.
     * The krad save Action and navigate methodToCall resets this flag back to false, but any other setting of
     * this flag must be managed by custom configuration/methods, if custom dirtyForm management is needed.

     *
     * @return true if the form is considered dirty, false otherwise
     */
    public boolean isDirtyForm() {
        return dirtyForm;
    }

    /**
     * Sets the dirtyForm flag
     *
     *
For most scenarios, this flag should NOT be set to true.
     * If this is set, it must be managed explicitly by the application.  This flag exists for marking a
     * form dirty from a server call, so it must be changed to false when the form is no longer considered dirty.
     * The krad save Action and navigate methodToCall resets this flag back to false, but any other setting of
     * this flag must be managed by custom configuration/methods, if custom dirtyForm management is needed.

     */
    public void setDirtyForm(boolean dirtyForm) {
        this.dirtyForm = dirtyForm;
    }

    /**
     * Set the dirtyForm flag using a String that will be converted to boolean
     */
    public void setDirtyForm(String dirtyForm) {
        if (dirtyForm != null) {
            this.dirtyForm = Boolean.parseBoolean(dirtyForm);
        }
    }

    /**
     * Indicates whether the view is rendered within a lightbox
     *
     *

     * Some discussion (for example how a close button behaves) need to change based on whether the
     * view is rendered within a lightbox or the standard browser window. This boolean is true when it is
     * within a lightbox
     *

     *
     * @return boolean true if view is rendered within a lightbox, false if not
     */
    public boolean isRenderedInDialog() {
        return this.renderedInDialog;
    }

    /**
     * Setter for the rendered within lightbox indicator
     */
    public void setRenderedInDialog(boolean renderedInDialog) {
        this.renderedInDialog = renderedInDialog;
    }

    /**
     * Indicates whether the view is rendered within an iframe (this setting must be passed to the View on the url)
     *
     * @return boolean true if view is rendered within a iframe, false if not
     */
    public boolean isRenderedInIframe() {
        return renderedInIframe;
    }

    /**
     * @see org.kuali.rice.krad.web.form.UifFormBase#isRenderedInIframe()
     */
    public void setRenderedInIframe(boolean renderedInIframe) {
        this.renderedInIframe = renderedInIframe;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isApplyDefaultValues()
     */
    @Override
    public boolean isApplyDefaultValues() {
        return applyDefaultValues;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setApplyDefaultValues(boolean)
     */
    @Override
    public void setApplyDefaultValues(boolean applyDefaultValues) {
        this.applyDefaultValues = applyDefaultValues;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isEvaluateFlagsAndModes()
     */
    public boolean isEvaluateFlagsAndModes() {
        return evaluateFlagsAndModes;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setEvaluateFlagsAndModes(boolean)
     */
    public void setEvaluateFlagsAndModes(boolean evaluateFlagsAndModes) {
        this.evaluateFlagsAndModes = evaluateFlagsAndModes;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isCanEditView()
     */
    public Boolean isCanEditView() {
        return canEditView;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setCanEditView(Boolean)
     */
    public void setCanEditView(Boolean canEditView) {
        this.canEditView = canEditView;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getActionFlags()
     */
    public Map<String, Boolean> getActionFlags() {
        return actionFlags;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setActionFlags(java.util.Map<java.lang.String,java.lang.Boolean>)
     */
    public void setActionFlags(Map<String, Boolean> actionFlags) {
        this.actionFlags = actionFlags;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getEditModes()
     */
    public Map<String, Boolean> getEditModes() {
        return editModes;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setEditModes(java.util.Map<java.lang.String,java.lang.Boolean>)
     */
    public void setEditModes(Map<String, Boolean> editModes) {
        this.editModes = editModes;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getGrowlScript()
     */
    @Override
    public String getGrowlScript() {
        return growlScript;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setGrowlScript(String)
     */
    @Override
    public void setGrowlScript(String growlScript) {
        this.growlScript = growlScript;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getState()
     */
    @Override
    public String getState() {
        return state;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setState(String)
     */
    @Override
    public void setState(String state) {
        this.state = state;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isAjaxRequest()
     */
    @Override
    public boolean isAjaxRequest() {
        return ajaxRequest;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setAjaxRequest(boolean)
     */
    @Override
    public void setAjaxRequest(boolean ajaxRequest) {
        this.ajaxRequest = ajaxRequest;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getAjaxReturnType()
     */
    @Override
    public String getAjaxReturnType() {
        return ajaxReturnType;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setAjaxReturnType(String)
     */
    @Override
    public void setAjaxReturnType(String ajaxReturnType) {
        this.ajaxReturnType = ajaxReturnType;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isUpdateComponentRequest()
     */
    @Override
    public boolean isUpdateComponentRequest() {
        return isAjaxRequest() && StringUtils.isNotBlank(getAjaxReturnType()) && getAjaxReturnType().equals(
                UifConstants.AjaxReturnTypes.UPDATECOMPONENT.getKey());
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isUpdateDialogRequest()
     */
    @Override
    public boolean isUpdateDialogRequest() {
        return isAjaxRequest() && StringUtils.isNotBlank(getAjaxReturnType()) && getAjaxReturnType().equals(
                UifConstants.AjaxReturnTypes.UPDATEDIALOG.getKey());
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isUpdatePageRequest()
     */
    @Override
    public boolean isUpdatePageRequest() {
        return StringUtils.isNotBlank(getAjaxReturnType()) && getAjaxReturnType().equals(
                UifConstants.AjaxReturnTypes.UPDATEPAGE.getKey());
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isUpdateNoneRequest()
     */
    @Override
    public boolean isUpdateNoneRequest() {
        return StringUtils.isNotBlank(getAjaxReturnType()) && getAjaxReturnType().equals(
                UifConstants.AjaxReturnTypes.UPDATENONE.getKey());
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#isJsonRequest()
     */
    @Override
    public boolean isJsonRequest() {
        return StringUtils.isNotBlank(getRequestJsonTemplate());
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getRequestJsonTemplate()
     */
    @Override
    public String getRequestJsonTemplate() {
        return requestJsonTemplate;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#setRequestJsonTemplate
     */
    @Override
    public void setRequestJsonTemplate(String requestJsonTemplate) {
        this.requestJsonTemplate = requestJsonTemplate;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isCollectionPagingRequest() {
        return collectionPagingRequest;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setCollectionPagingRequest(boolean collectionPagingRequest) {
        this.collectionPagingRequest = collectionPagingRequest;
    }

    /**
     * For cases where the request was triggered from within a dialog, we want to show that dialog,
     * identified by this id, again.
     */
    public String getShowDialogId() {
        return showDialogId;
    }

    /**
     * @see UifFormBase#getShowDialogId()
     */
    public void setShowDialogId(String dialogId) {
        this.showDialogId = dialogId;
    }

    /**
     * Used by the dialog framework to set the dialog id for a return dialog call (when the server has
     * triggered a dialog).
     *
     *
Note this is a request only property. On a return call the value for this gets pulled and used to
     * create an entry in {@link UifFormBase#getDialogResponses()}

     *
     * @return String id for the dialog being returned from
     */
    public String getReturnDialogId() {
        return returnDialogId;
    }

    /**
     * @see UifFormBase#getReturnDialogId()
     */
    public void setReturnDialogId(String returnDialogId) {
        this.returnDialogId = returnDialogId;
    }

    /**
     * Used by the dialog framework to set the dialog response for a return dialog call (when the server has
     * triggered a dialog).
     *
     *
Note this is a request only property. On a return call the value for this gets pulled and used to
     * create an entry in {@link UifFormBase#getDialogResponses()}

     *
     * @return String response for the dialog being returned from
     */
    public String getReturnDialogResponse() {
        return returnDialogResponse;
    }

    /**
     * @see UifFormBase#getReturnDialogResponse()
     */
    public void setReturnDialogResponse(String returnDialogResponse) {
        this.returnDialogResponse = returnDialogResponse;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Map<String, String> getDialogExplanations() {
        return dialogExplanations;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setDialogExplanations(Map<String, String> dialogExplanations) {
        this.dialogExplanations = dialogExplanations;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Map<String, DialogResponse> getDialogResponses() {
        return dialogResponses;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DialogResponse getDialogResponse(String dialogId) {
        if ((dialogResponses != null) && dialogResponses.containsKey(dialogId)) {
            return dialogResponses.get(dialogId);
        }

        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setDialogResponses(Map<String, DialogResponse> dialogResponses) {
        this.dialogResponses = dialogResponses;
    }

    /**
     * @see org.kuali.rice.krad.uif.view.ViewModel#getExtensionData()
     */
    @Override
    public Map<String, Object> getExtensionData() {
        return extensionData;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setExtensionData(Map<String, Object> extensionData) {
        this.extensionData = extensionData;
    }

    /**
     * Http servlet request instance for the current request being processed.
     *
     * @return HttpServletRequest instance
     */
    public HttpServletRequest getRequest() {
        return request;
    }

    /**
     * @see UifFormBase#getRequest()
     */
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * The {@code List} that contains all newly added items for the collections on the model
     *
     *

     * This list contains the new items for all the collections on the model.
     *

     *
     * @return List of the newly added item lists
     */
    public List getAddedCollectionItems() {
        return addedCollectionItems;
    }

    /**
     * Setter for the newly added item list
     */
    public void setAddedCollectionItems(List addedCollectionItems) {
        this.addedCollectionItems = addedCollectionItems;
    }

    /**
     * Indicates whether an collection item has been newly added
     *
     *

     * Tests collection items against the list of newly added items on the model. This list gets cleared when the view
     * is submitted and the items are persisted.
     *

     *
     * @param item - the item to test against list of newly added items
     * @return boolean true if the item has been newly added
     */
    public boolean isAddedCollectionItem(Object item) {
        return addedCollectionItems.contains(item);
    }

    /**
     * The data object to bind to for a dialog
     *
     *
The data object serves as a placeholder for temporary properties that might be used within a dialog. The
     * purpose of placeholder is to provide a separation between the dialog object and the underlying object for use
     * in cases like object manipulation.

     */
    public Object getDialogDataObject() {
        return dialogDataObject;
    }

    /**
     * @see UifFormBase#getDialogDataObject()
     */
    public void setDialogDataObject(Object dataObject) {
        this.dialogDataObject = dataObject;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(getClass().getSimpleName()).append(" [viewId=").append(this.viewId).append(", viewName=").append(
                this.viewName).append(", viewTypeName=").append(this.viewTypeName).append(", pageId=").append(
                this.pageId).append(", methodToCall=").append(this.methodToCall).append(", formKey=").append(
                this.formKey).append(", requestedFormKey=").append(this.requestedFormKey).append("]");
        return builder.toString();
    }

    public String getCsrfToken() {
        return csrfToken;
    }

    public void setCsrfToken(String csrfToken) {
        this.csrfToken = csrfToken;
    }

}


text:
/**
 * markdown chat
 */

var express = require('express');
var user = require('./routes/user');
var http = require('http');
var https = require('https');
var mongoose = require('mongoose');
var path = require('path');
var ejs = require('ejs');
var fs = require('fs');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');
var _ = require('lodash');
var Q = require('q');
var express_ex = require('./utils/express_ex');
var $ = require('cheerio');

var config = require('./config');

var app = express();

var server = http.createServer(app);

if (process.env.MONGOLAB_URI) {
  mongoose.connect(process.env.MONGOLAB_URI);
}
else {
  mongoose.connect('mongodb://localhost/markdown_chat2');
}

// load local libraries
require('./model');

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'markdown-chat-0E46CB44-0B66-4B74-AD6B-8D467D51FBC8' }));

app.use(flash());
app.use(passport.initialize());
app.use(passport.session());

// force to use https
if ('production'.toString() === app.get('env').toString()) {
  app.use(function(req, res, next) {
    var schema = req.headers['x-forwarded-proto'];
    if (schema.toString() === 'https'.toString()) {
      // Already https; don't do anything special.
      next();
    }
    else {
      // Redirect to https.
      res.redirect('https://' + req.headers.host + req.url);
    }
  });
}

if (process.env.MD_BASIC_USER && process.env.MD_BASIC_PASSWD) {
   app.all('*', express_ex.basicAuth(function(user, pass) {
     return user.toString() === process.env.MD_BASIC_USER.toString() && pass.toString() === process.env.MD_BASIC_PASSWD.toString();
   }));
   // app.use(function(req, res, next) {
   //   req.basicAuthUser = req.user;
   //   req.user = null;
   //   next();
   // });
}

app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development'.toString() === app.get('env').toString()) {
  app.use(express.errorHandler());
}

// routing
var routes = require('./routes');
routes.routes.forEach(function(r) {
  if (r.get_url && r.get) {
    if (r.get_url instanceof Array) {
      r.get_url.forEach(function(u) {
        app.get(u, r.get);
      });
    }
    else {
      app.get(r.get_url, r.get);
    }
  }
  if (r.post_url && r.post) {
    if (r.post_url instanceof Array) {
      r.post_url.forEach(function(u) {
        app.post(u, r.post);
      });
    }
    else {
      app.post(r.post_url, r.post);
    }
  }
});

// plugins
var plugins = require('./plugins').plugins;

var Say = mongoose.model('Say');
// settings for socket.io
var io = require('socket.io').listen(server, {'log level': 2});

server.listen(app.get('port'), function() {
  console.log('express server listening on port ' + app.get('port'));
});

var clients = [];
var sockets = [];
io.sockets.on('connection', function(socket) {
  sockets.push(socket);
  var user_id = null;
  var User = mongoose.model('User');
  var pushActiveUsers = function() {
    var active_user_ids = _(clients).filter().uniq().value();

    User.find({_id: {$in: active_user_ids}}, function(err, users) {
      if (err !== null) {
        console.log(err);
      }
      else {
        var data = {
          users: _.map(users, function(u) {
            return {name: u.nickname, url: u.getIconURL(), id: u._id};
          })
        };
        socket.broadcast.emit('users active', data);
        socket.emit('users active', data);
      }
    });
  };

  pushActiveUsers();
  socket.on('disconnect', function() {
    if (user_id) {
      clients.splice(clients.indexOf(user_id), 1);
      console.log(clients.length + ' clients');
    }
    pushActiveUsers();
  });

  // 初回接続時の履歴取得
  socket.on('msg update', function(msg) {
    if (msg.hasOwnProperty('user_id')) {
      if (msg['user_id']) {
        user_id = msg['user_id'];
        clients.push(user_id);
        pushActiveUsers();
      }
    }
    Say.countObject()
      .then(function(say_count) {
        Say.find()
          .sort([['date', 'ascending']])
          .skip(Math.max(say_count - config.PAGE_MAX, 0))
          .limit(config.PAGE_MAX)
          .populate('user')
          .exec(function(err, docs) {
            socket.emit('msg open', docs.map(function(doc) {
              if (user_id && doc.user._id.toString() === user_id.toString()) {
                return {
                  html: doc.renderMeWithEJS(),
                  date: doc.date,
                  _id: doc._id
                };
              }
              else {
                return {
                  html: doc.renderWithEJS(),
                  date: doc.date,
                  _id: doc._id
                };
              }
            }));
          });
      });
  });

  socket.on('msg edit', function(data) {
    var say_id = data.say_id;
    var markdown = data.markdown;
    Say.find({_id: say_id})
      .populate('user')
      .exec(function(err, says) {
        var say = null;
        if (says.length === 1) {
          say = says[0];
        }
        if (err) {
          console.log('failed to find say object');
          console.log(err);
        }
        else if (say === null) {
          console.log('cannot find say: ' + say_id);
        }
        else {
          say.updateMarkdown(markdown)
            .then(function(html) {
              // broadcasting the message
              sockets.forEach(function(socket) {
                var the_user_id = socket.user_id;
                socket.emit('msg changed', {
                  html: html,
                  say_id: say_id,
                  raw_markdown: markdown,
                  user_id: user_id
                });
              });
            })
            .fail(function(err) {
              console.log('failed to update markdown');
              console.log(err);
            });
        }
      });
  });

  // when received message

  socket.on('msg send', function(data) {
    var now = new Date(); // now
    var say = new Say({
      name: data.name,
      date: now,
      raw_markdown: data.msg,
      message: data.message,
      user: user_id
    });
    // populate user
    Say.populate(say, {path: 'user'}, function(err, say) {
      say.renderMarkdown(user_id)
        .then(function(me_html) {
          say.renderMarkdown()
            .then(function(other_html) {
              var send_data = {
                me_html: me_html,
                other_html: other_html,
                date: now,
                _id: say._id,
                user_id: user_id
              };
              socket.emit('msg push', send_data);
              socket.broadcast.emit('msg push', send_data);
            })
            .fail(function(err) {
              console.log(err);
            });
        })
        .fail(function(err) {
          console.log(err);
        });
    });
  });

  // delete from database
  socket.on('msg delete', function(data) {
    var say_id = data.say_id;
    if (say_id) {
      Say.findById(say_id, function(err, say) {
        if (err) {
          console.log('[msg delete] failed to find say');
        }
        else if (!say) {
          console.log('[msg delete] cannod find say');
        }
        else {
          say.remove(function(err) {
            if (err) {
              console.log('[msg delete] failed to remove say object');
            }
            else {
              socket.broadcast.emit('msg delete-one', {say_id: say_id});
            }
          });
        }
      });
    }
    //console.log('msg delete');
    //console.log(data);
  });

  socket.on('msg push', function(data){
    var mentions = plugins.containsMentions(data.msg);
    if (mentions.find("jskbot")){
      var msgs = data.msg.split(' ').slice(1).join(' ');
      plugins.getZatsudan(msgs, function(err, res, body){
        if (!err && res.statusCode == 200){
          var send_data = {
            me_html: null,
            other_html: null,
            date: now,
            _id: 'jskbot',
            user_id: user_id
          };
          socket.broadcast.emit('msg push', send_data);
        } else {
          console.log(err);
        }
      });
    }
  });

  socket.on('disconnect', function() {
    console.log('disconnected.');
  });

});

redpajama_set_name: RedPajamaGithub


text:
#include "BitFont.hpp"
#include <fstream>
#include <iostream>

using namespace std;

BitFont::BitFont(const char *font) : fontPath(font)
{

}

BitFontChar* BitFont::GetSymbol(uint8_t sym)
{
    if(table.find(sym) != table.end())
        return &table[sym];
    else
        return nullptr;
}

uint8_t BitFont::GetWidth()
{
    return header.size_width;
}

uint8_t BitFont::GetHeight()
{
    return header.size_height;
}

BitFont::~BitFont()
{
    for(auto sym : table)
        delete[] sym.second.data;
}

size_t BitFont::serialize_size() const
{
    size_t size = 0;
    for(auto e : table)
    {
        size += e.second.size + 2;
    }
    return sizeof(BitFontHeader) + size;
}

void BitFont::serialize(char *dataOut) const
{
    char *p = dataOut;
    p = SerializablePOD<BitFontHeader>::serialize(p, header);
    for(const auto& element : table)
    {

        p = SerializablePOD<uint8_t>::serialize(p, element.second.index);
        p = SerializablePOD<uint8_t>::serialize(p, element.second.size);
        for(int i = 0; i < element.second.size;i++)
            p = SerializablePOD<uint8_t>::serialize(p, element.second.data[i]);
    }
}

void BitFont::deserialize(const char *dataIn)
{
    dataIn = SerializablePOD<BitFontHeader>::deserialize(dataIn, header);
    if(header.magic != BitFontHeader::MAGIC_VERSIONS::DEFAULT)
        throw runtime_error("unknown font format");
    for(int i = 0; i < header.s_count; i++)
    {
        BitFontChar element;
        dataIn = SerializablePOD<uint8_t>::deserialize(dataIn, element.index);
        dataIn = SerializablePOD<uint8_t>::deserialize(dataIn, element.size);
        element.data = new uint8_t[element.size];
        for(int i = 0; i < element.size;i++)
            dataIn = SerializablePOD<uint8_t>::deserialize(dataIn, element.data[i]);
        table[element.index] = element;
    }
}

void BitFont::SetChar(const BitFontChar &chr)
{
    table[chr.index] = chr;
}

void BitFont::SetHeader(const BitFontHeader &hdr)
{
    header = hdr;
}

BitFontChar *BitFont::CreateChar(uint8_t index)
{
    if(table[index].size)
        delete[] table[index].data;
    else
        header.s_count++;
    table[index].index = index;
    table[index].size = header.size_height * header.size_width;
    table[index].data = new uint8_t[table[index].size];
    memset(table[index].data, 0, table[index].size);

    return &table[index];
}

bool BitFont::ShrinkChar(BitFontChar *chr)
{
    bool ok = false;
    uint8_t i;
    for(i = chr->size - 1; i != 0; i--)
        if(chr->data[i] != 0)
            break;

    uint8_t *newChr = nullptr;
    if(i)
    {
        newChr = new uint8_t[i];
        copy(chr->data, chr->data + i, newChr);
    }

    delete chr->data;
    chr->data = newChr;
    if(chr->size != i + 1)
        ok = true;
    chr->size = i;
    return ok;
}

BitFont &BitFont::Save()
{
    ofstream file(fontPath, ofstream::binary);
    vector<char> tmp;
    size_t size = serialize_size();
    tmp.resize(size);

    serialize(&tmp[0]);

    file.write(&tmp[0], size);

    return *this;
}

BitFont &BitFont::Load()
{
    ifstream file(fontPath, ifstream::binary);
    if(!file.is_open())
        throw invalid_argument("Font not found or permissions denied");

    if (!file.eof() && !file.fail())
    {
        vector<char> tmp;
        file.seekg(0, std::ios_base::end);
        std::streampos fileSize = file.tellg();
        tmp.resize(static_cast<unsigned long>(fileSize));

        file.seekg(0, std::ios_base::beg);
        file.read(&tmp[0], fileSize);

        deserialize(&tmp[0]);
    }

    return *this;
}

const BitFontHeader &BitFont::GetHeader() const
{
    return header;
}


text:
<?php

namespace Alius\Injector\Fixtures;

class MultipleRecursiveClass
{
    public function __construct(OneSimpleClass $argument1, OneRecursiveClass $argument2)
    {
        $this->argument1 = $argument1;
        $this->argument2 = $argument2;
    }

    public static function make()
    {
        return new static(
            OneSimpleClass::make(),
            OneRecursiveClass::make()
        );
    }
}


text:
layout: page
title: "Software Development Videos"
id: tech-videos
---
{% assign tagged_techvideos= (site.data.techvideos | group_by: 'tag' | sort: 'name' ) %}

{% for tag in tagged_techvideos %}
{{ tag.name }}
{% endfor %}

### Category

---

{% for tag in tagged_techvideos %}

{{ tag.name }}

{% assign sorted_techvideos= (tag.items | sort: 'name') %}
{% for techvideo in sorted_techvideos %}

{{ techvideo.name }}

{% endfor %}
{% endfor %}


text:
extern const struct TTSymbol {
__unsafe_unretained NSString *const Laptop;

} TTSymbol;


text:
module AthenaHealth
  module Endpoints
    module CustomFields
      def all_custom_fields(practice_id:, params: {})
        response = @api.call(
          endpoint: "#{practice_id}/customfields",
          method: :get,
          params: params
        )
        response.map { |field| CustomField.new(field) }
      end
    end
  end
end


text:
package org.cdlib.xtf.lazyTree;
import net.sf.saxon.om.SequenceIterator;
import net.sf.saxon.pattern.NodeTest;

final class ChildEnumeration extends TreeEnumeration
{

    public ChildEnumeration(NodeImpl node, NodeTest nodeTest)
    {
        super(node, nodeTest);
        next = (NodeImpl)node.getFirstChild();
        while (!conforms(next)) {
            step();
        }
    }

    protected void step() {
        next = (NodeImpl)next.getNextSibling();
    }

    /**
    * Get another enumeration of the same nodes
    */

    public SequenceIterator getAnother() {
        return new ChildEnumeration(start, nodeTest);
    }
}

//
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is: all this file.
//
// The Initial Developer of the Original Code is Michael H. Kay.
//
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
//
// Contributor(s): none.
//


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AppLib.Forms
{
    public class ApplicationBaseFileDialog
    {
        #region ATTRIBUTES

        private string m_authorisedEntension;
        private string m_currentFullName;
        private string m_currentWorkingDirectory;

        #endregion

        #region DECLARATION

        #endregion

        #region CONSTRUCTOR

        protected ApplicationBaseFileDialog(string authorisedEntension, string currentFullName = "")
        {
            m_authorisedEntension = authorisedEntension;

            if (currentFullName != "")
            {
                if (System.IO.File.Exists(currentFullName))
                {
                    m_currentFullName = currentFullName;
                }

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(currentFullName);
                if (System.IO.Directory.Exists(fileInfo.DirectoryName))
                {
                    m_currentWorkingDirectory = fileInfo.DirectoryName;
                }
            }
        }

        #endregion

        #region PROPERTIES

        public string EXTENSION
        {
            get
            {
                return m_authorisedEntension;
            }
        }

        protected string FULL_NAME
        {
            get
            {
                return m_currentFullName;
            }
        }

        protected string WORKING_DIRECTORY
        {
            get
            {
                return m_currentWorkingDirectory;
            }
        }

        protected string FILTER
        {
            get
            {
                return "Files (*." + EXTENSION + "*)|*." + EXTENSION + "*";
            }
        }
        protected string getUnAuthoriedMessage()
        {
            return "only (*." + EXTENSION + ") extention is authorized as project format";
        }
        #endregion

    }
}


text:
title: "Wieder on Tour"
date: 2008-04-30 08:02
---
Wir sind bereits wieder unterwegs und frühstücken bei blauem Himmel und Sonne draussen.


text:
var ngGridFlexibleHeightPlugin = function(opts) {
    var self = this;
    self.grid = null;
    self.scope = null;
    self.init = function (scope, grid, services) {
        self.domUtilityService = services.DomUtilityService;
        self.grid = grid;
        self.scope = scope;
        var recalcHeightForData = function () { setTimeout(innerRecalcForData, 1); };
        var innerRecalcForData = function () {
            var gridId = self.grid.gridId;
            var footerPanelSel = '.' + gridId + ' .ngFooterPanel';
            var extraHeight = self.grid.$topPanel.height() + $(footerPanelSel).height();
            var naturalHeight = self.grid.$canvas.height() + 1;
            if (opts != null) {
                if (opts.minHeight != null && (naturalHeight + extraHeight) < opts.minHeight) {
                    naturalHeight = opts.minHeight - extraHeight - 2;
                }
            }

            var BOTTOM_MARGIN = 25;
            var newViewportHeight = naturalHeight + BOTTOM_MARGIN;
            if (!self.scope.baseViewportHeight || self.scope.baseViewportHeight !== newViewportHeight) {
                self.grid.$viewport.css('height', newViewportHeight + 'px');
                self.grid.$root.css('height', (newViewportHeight + extraHeight) + 'px');
                self.scope.baseViewportHeight = newViewportHeight;
                self.domUtilityService.RebuildGrid(self.scope, self.grid);
            }
        };
        self.scope.catHashKeys = function () {
            var hash = '',
                idx;
            for (idx in self.scope.renderedRows) {
                hash += self.scope.renderedRows[idx].$$hashKey;
            }
            return hash;
        };
        self.scope.$watch('catHashKeys()', innerRecalcForData);
        self.scope.$watch(self.grid.config.data, recalcHeightForData);
    };
}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
        />

        <title>reveal.js</title>

        <link rel="stylesheet" href="dist/reset.css" />
        <link rel="stylesheet" href="dist/reveal.css" />
        <link rel="stylesheet" href="dist/theme/solarized.css" id="theme" />

        <link
            rel="stylesheet"
            href="plugin/highlight/monokai.css"
            id="highlight-theme"
        />


text:
package cucumber.runtime.java.picocontainer;

import cucumber.api.java.ObjectFactory;
import cucumber.runtime.Utils;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.PicoBuilder;

import java.lang.reflect.Constructor;
import java.util.HashSet;
import java.util.Set;

public class PicoFactory implements ObjectFactory {
    private MutablePicoContainer pico;
    private final Set<Class<?>> classes = new HashSet<Class<?>>();

    public void start() {
        pico = new PicoBuilder().withCaching().build();
        for (Class<?> clazz : classes) {
            pico.addComponent(clazz);
        }
        pico.start();
    }

    public void stop() {
        pico.stop();
        pico.dispose();
    }

    public void addClass(Class<?> clazz) {
        if (Utils.isInstantiable(clazz) && classes.add(clazz)) {
            addConstructorDependencies(clazz);
        }
    }

    public <T> T getInstance(Class<T> type) {
        return pico.getComponent(type);
    }

    private void addConstructorDependencies(Class<?> clazz) {
        for (Constructor constructor : clazz.getConstructors()) {
            for (Class paramClazz : constructor.getParameterTypes()) {
                addClass(paramClazz);
            }
        }
    }
}


text:
using namespace arangodb::aql;

DocumentProducingNode::DocumentProducingNode(Variable const* outVariable)
    : _outVariable(outVariable),
      _count(false),
      _useCache(true),
      _maxProjections(kMaxProjections) {
  TRI_ASSERT(_outVariable != nullptr);
}

DocumentProducingNode::DocumentProducingNode(ExecutionPlan* plan,
                                             arangodb::velocypack::Slice slice)
    : _outVariable(
          Variable::varFromVPack(plan->getAst(), slice, "outVariable")),
      _projections(arangodb::aql::Projections::fromVelocyPack(slice)),
      _filterProjections(arangodb::aql::Projections::fromVelocyPack(
          slice, "filterProjections")),
      _count(false),
      _useCache(true),
      _maxProjections(kMaxProjections) {
  TRI_ASSERT(_outVariable != nullptr);

  VPackSlice p = slice.get(StaticStrings::Filter);
  if (!p.isNone()) {
    Ast* ast = plan->getAst();
    // new AstNode is memory-managed by the Ast
    setFilter(std::make_unique<Expression>(ast, ast->createNode(p)));
  }

  _count = arangodb::basics::VelocyPackHelper::getBooleanValue(slice, "count",
                                                               false);
  _readOwnWrites = arangodb::basics::VelocyPackHelper::getBooleanValue(
                       slice, StaticStrings::ReadOwnWrites, false)
                       ? ReadOwnWrites::yes
                       : ReadOwnWrites::no;

  _useCache = arangodb::basics::VelocyPackHelper::getBooleanValue(
      slice, StaticStrings::UseCache, _useCache);

  p = slice.get(StaticStrings::MaxProjections);
  if (!p.isNone()) {
    setMaxProjections(p.getNumber<size_t>());
  }
}

void DocumentProducingNode::cloneInto(ExecutionPlan* plan,
                                      DocumentProducingNode& c) const {
  if (_filter != nullptr) {
    c.setFilter(
        std::unique_ptr<Expression>(_filter->clone(plan->getAst(), true)));
  }
  c.copyCountFlag(this);
  c.setCanReadOwnWrites(canReadOwnWrites());
  c.setMaxProjections(maxProjections());
  c.setUseCache(useCache());
}

void DocumentProducingNode::replaceVariables(
    std::unordered_map<VariableId, Variable const*> const& replacements) {
  if (hasFilter()) {
    _filter->replaceVariables(replacements);
  }
}

void DocumentProducingNode::toVelocyPack(arangodb::velocypack::Builder& builder,
                                         unsigned flags) const {
  builder.add(VPackValue("outVariable"));
  _outVariable->toVelocyPack(builder);

  _projections.toVelocyPack(builder);

  if (_filter != nullptr) {
    builder.add(VPackValue(StaticStrings::Filter));
    _filter->toVelocyPack(builder, flags);

    _filterProjections.toVelocyPack(builder, "filterProjections");
  } else {
    builder.add("filterProjections", VPackValue(VPackValueType::Array));
    builder.close();
  }

  // "producesResult" is read by AQL explainer. don't remove it!
  builder.add("count", VPackValue(doCount()));
  if (doCount()) {
    TRI_ASSERT(_filter == nullptr);
    builder.add(StaticStrings::ProducesResult, VPackValue(false));
  } else {
    builder.add(
        StaticStrings::ProducesResult,
        VPackValue(_filter != nullptr ||
                   dynamic_cast<ExecutionNode const*>(this)->isVarUsedLater(
                       _outVariable)));
  }
  builder.add(StaticStrings::ReadOwnWrites,
              VPackValue(_readOwnWrites == ReadOwnWrites::yes));

  builder.add(StaticStrings::UseCache, VPackValue(useCache()));
  builder.add(StaticStrings::MaxProjections, VPackValue(maxProjections()));
}

Variable const* DocumentProducingNode::outVariable() const {
  return _outVariable;
}

/// @brief remember the condition to execute for early filtering
void DocumentProducingNode::setFilter(std::unique_ptr<Expression> filter) {
  _filter = std::move(filter);
}

arangodb::aql::Projections const& DocumentProducingNode::projections()
    const noexcept {
  return _projections;
}

arangodb::aql::Projections& DocumentProducingNode::projections() noexcept {
  return _projections;
}

arangodb::aql::Projections const& DocumentProducingNode::filterProjections()
    const noexcept {
  return _filterProjections;
}

void DocumentProducingNode::setProjections(
    arangodb::aql::Projections projections) {
  _projections = std::move(projections);
}

bool DocumentProducingNode::doCount() const {
  return _count && (_filter == nullptr);
}


text:
//-----------------------------------------------------------------------
// <copyright file="AddBuildProfileForm.cs" company="42A Consulting">
//     Copyright 2011 42A Consulting
//     Licensed under the Apache License, Version 2.0 (the "License");
//     you may not use this file except in compliance with the License.
//     You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//     Unless required by applicable law or agreed to in writing, software
//     distributed under the License is distributed on an "AS IS" BASIS,
//     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
//     limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace C42A.CAB42.Windows.Forms
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    /// <summary>
    /// A form used to create new build profiles.
    /// </summary>
    public partial class AddBuildProfileForm : Form
    {
        /// <summary>
        /// The build profile to edit or the profile created.
        /// </summary>
        private BuildProfile profile;

        /// <summary>
        /// Initializes a new instance of the <see cref="AddBuildProfileForm"/> class.
        /// </summary>
        public AddBuildProfileForm()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Gets or sets the build profile to edit. If null, a build profile will be created.
        /// </summary>
        public BuildProfile Value
        {
            get
            {
                return this.profile;
            }

            set
            {
                this.profile = value;

                if (value != null)
                {
                    this.tbFileName.Text = value.Name;
                }
                else
                {
                    this.tbFileName.Text = string.Empty;
                }
            }
        }

        /// <summary>
        /// Occurs when the user has clicked the OK button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An <see cref="EventArgs"/> that contain the event data.</param>
        private void OnOKClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.tbFileName.Text))
            {
                MessageBox.Show(this, "The name must not be empty", this.Text);
                return;
            }

            if (this.profile == null)
            {
                this.profile = new BuildProfile();
            }

            this.profile.Name = this.tbFileName.Text;

            this.Close(DialogResult.OK);
        }

        /// <summary>
        /// Occurs when the user has clicked the Cancel button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An <see cref="EventArgs"/> that contain the event data.</param>
        private void OnCancelClick(object sender, EventArgs e)
        {
            this.Close(DialogResult.Cancel);
        }

        /// <summary>
        /// Closes the form after the dialogresult has been set.
        /// </summary>
        /// <param name="dialogResult">The dialog result to set before closing the form.</param>
        private void Close(System.Windows.Forms.DialogResult dialogResult)
        {
            this.DialogResult = dialogResult;

            this.Close();
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<NodeIdExample>
    <Content code="i1234">Test content for showing node identifiers</Content>
</NodeIdExample>


text:
<?php

namespace SocialiteProviders\Weibo;

use SocialiteProviders\Manager\OAuth2\User;
use Laravel\Socialite\Two\ProviderInterface;
use SocialiteProviders\Manager\OAuth2\AbstractProvider;

class Provider extends AbstractProvider implements ProviderInterface
{
    /**
     * Unique Provider Identifier.
     */
    const IDENTIFIER = 'WEIBO';

    /**
     * {@inheritdoc}.
     */
    protected function getAuthUrl($state)
    {
        return $this->buildAuthUrlFromBase('https://api.weibo.com/oauth2/authorize', $state);
    }

    /**
     * {@inheritdoc}.
     */
    protected function getTokenUrl()
    {
        return 'https://api.weibo.com/oauth2/access_token';
    }

    /**
     * {@inheritdoc}.
     */
    protected function getUserByToken($token)
    {
        $response = $this->getHttpClient()->get('https://api.weibo.com/2/users/show.json', [
            'query' => [
                'access_token' => $token,
                'uid' => $this->getUid($token),
            ],
        ]);

        return json_decode($this->removeCallback($response->getBody()->getContents()), true);
    }

    /**
     * {@inheritdoc}.
     */
    protected function mapUserToObject(array $user)
    {
        return (new User())->setRaw($user)->map([
            'id' => $user['idstr'], 'nickname' => $user['name'],
            'avatar' => $user['avatar_large'], 'name' => null, 'email' => null,
        ]);
    }

    /**
     * {@inheritdoc}.
     */
    protected function getTokenFields($code)
    {
        return array_merge(parent::getTokenFields($code), [
            'grant_type' => 'authorization_code',
        ]);
    }

    /**
     * {@inheritdoc}.
     */
    public function getAccessToken($code)
    {
        $response = $this->getHttpClient()->post($this->getTokenUrl(), [
            'query' => $this->getTokenFields($code),
        ]);

        $this->credentialsResponseBody = json_decode($response->getBody(), true);

        return $this->parseAccessToken($response->getBody());
    }

    /**
     * @param mixed $response
     *
     * @return string
     */
    protected function removeCallback($response)
    {
        if (strpos($response, 'callback') !== false) {
            $lpos = strpos($response, '(');
            $rpos = strrpos($response, ')');
            $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
        }

        return $response;
    }

    /**
     * @param $token
     *
     * @return string
     */
    protected function getUid($token)
    {
        $response = $this->getHttpClient()->get('https://api.weibo.com/2/account/get_uid.json', [
            'query' => ['access_token' => $token],
        ]);

        return json_decode($response->getBody(), true)['uid'];
    }
}


text:
package ccv3

import (
	"bytes"
	"encoding/json"

	"code.cloudfoundry.org/cli/api/cloudcontroller"
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/internal"
)

// Relationship represents a one to one relationship.
// An empty GUID will be marshaled as `null`.
type Relationship struct {
	GUID string
}

func (r Relationship) MarshalJSON() ([]byte, error) {
	if r.GUID == "" {
		var emptyCCRelationship struct {
			Data interface{} `json:"data"`
		}
		return json.Marshal(emptyCCRelationship)
	}

	var ccRelationship struct {
		Data struct {
			GUID string `json:"guid"`
		} `json:"data"`
	}

	ccRelationship.Data.GUID = r.GUID
	return json.Marshal(ccRelationship)
}

func (r *Relationship) UnmarshalJSON(data []byte) error {
	var ccRelationship struct {
		Data struct {
			GUID string `json:"guid"`
		} `json:"data"`
	}

	err := cloudcontroller.DecodeJSON(data, &ccRelationship)
	if err != nil {
		return err
	}

	r.GUID = ccRelationship.Data.GUID
	return nil
}

// DeleteIsolationSegmentOrganization will delete the relationship between
// the isolation segment and the organization provided.
func (client *Client) DeleteIsolationSegmentOrganization(isolationSegmentGUID string, orgGUID string) (Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.DeleteIsolationSegmentRelationshipOrganizationRequest,
		URIParams:   internal.Params{"isolation_segment_guid": isolationSegmentGUID, "organization_guid": orgGUID},
	})
	if err != nil {
		return nil, err
	}

	var response cloudcontroller.Response
	err = client.connection.Make(request, &response)

	return response.Warnings, err
}

// DeleteServiceInstanceRelationshipsSharedSpace will delete the sharing relationship
// between the service instance and the shared-to space provided.
func (client *Client) DeleteServiceInstanceRelationshipsSharedSpace(serviceInstanceGUID string, spaceGUID string) (Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.DeleteServiceInstanceRelationshipsSharedSpaceRequest,
		URIParams:   internal.Params{"service_instance_guid": serviceInstanceGUID, "space_guid": spaceGUID},
	})
	if err != nil {
		return nil, err
	}

	response := cloudcontroller.Response{}
	err = client.connection.Make(request, &response)
	return response.Warnings, err
}

// GetOrganizationDefaultIsolationSegment returns the relationship between an
// organization and it's default isolation segment.
func (client *Client) GetOrganizationDefaultIsolationSegment(orgGUID string) (Relationship, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetOrganizationRelationshipDefaultIsolationSegmentRequest,
		URIParams:   internal.Params{"organization_guid": orgGUID},
	})
	if err != nil {
		return Relationship{}, nil, err
	}

	var relationship Relationship
	response := cloudcontroller.Response{
		Result: &relationship,
	}

	err = client.connection.Make(request, &response)
	return relationship, response.Warnings, err
}

// GetSpaceIsolationSegment returns the relationship between a space and it's
// isolation segment.
func (client *Client) GetSpaceIsolationSegment(spaceGUID string) (Relationship, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetSpaceRelationshipIsolationSegmentRequest,
		URIParams:   internal.Params{"space_guid": spaceGUID},
	})
	if err != nil {
		return Relationship{}, nil, err
	}

	var relationship Relationship
	response := cloudcontroller.Response{
		Result: &relationship,
	}

	err = client.connection.Make(request, &response)
	return relationship, response.Warnings, err
}

// SetApplicationDroplet sets the specified droplet on the given application.
func (client *Client) SetApplicationDroplet(appGUID string, dropletGUID string) (Relationship, Warnings, error) {
	relationship := Relationship{GUID: dropletGUID}
	bodyBytes, err := json.Marshal(relationship)
	if err != nil {
		return Relationship{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PatchApplicationCurrentDropletRequest,
		URIParams:   map[string]string{"app_guid": appGUID},
		Body:        bytes.NewReader(bodyBytes),
	})
	if err != nil {
		return Relationship{}, nil, err
	}

	var responseRelationship Relationship
	response := cloudcontroller.Response{
		Result: &responseRelationship,
	}
	err = client.connection.Make(request, &response)

	return responseRelationship, response.Warnings, err
}

// UpdateOrganizationDefaultIsolationSegmentRelationship sets the default isolation segment
// for an organization on the controller.
// If isoSegGuid is empty it will reset the default isolation segment.
func (client *Client) UpdateOrganizationDefaultIsolationSegmentRelationship(orgGUID string, isoSegGUID string) (Relationship, Warnings, error) {
	body, err := json.Marshal(Relationship{GUID: isoSegGUID})
	if err != nil {
		return Relationship{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PatchOrganizationRelationshipDefaultIsolationSegmentRequest,
		Body:        bytes.NewReader(body),
		URIParams:   internal.Params{"organization_guid": orgGUID},
	})
	if err != nil {
		return Relationship{}, nil, err
	}

	var relationship Relationship
	response := cloudcontroller.Response{
		Result: &relationship,
	}
	err = client.connection.Make(request, &response)
	return relationship, response.Warnings, err
}

// UpdateSpaceIsolationSegmentRelationship assigns an isolation segment to a space and
// returns the relationship.
func (client *Client) UpdateSpaceIsolationSegmentRelationship(spaceGUID string, isolationSegmentGUID string) (Relationship, Warnings, error) {
	body, err := json.Marshal(Relationship{GUID: isolationSegmentGUID})
	if err != nil {
		return Relationship{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PatchSpaceRelationshipIsolationSegmentRequest,
		URIParams:   internal.Params{"space_guid": spaceGUID},
		Body:        bytes.NewReader(body),
	})
	if err != nil {
		return Relationship{}, nil, err
	}

	var relationship Relationship
	response := cloudcontroller.Response{
		Result: &relationship,
	}

	err = client.connection.Make(request, &response)
	return relationship, response.Warnings, err
}


text:
namespace IronText.Logging
{
    public class LogEntry
    {
        public Severity Severity = Severity.Message;
        public Loc      Location;
        public HLoc     HLocation;
        public string   Code;
        public string   Message;
        public string   Origin;
    }
}


text:
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/fcntl.h>
#include <linux/fs.h>
#include <linux/ip.h>
#include <linux/kfifo.h>

#include <linuxver.h>
#include <osl.h>
#include <bcmutils.h>
#include <bcmendian.h>
#include <bcmdevs.h>
#include <dngl_stats.h>
#include <dhd.h>
#include <dhd_dbg.h>
#include <dhd_linux_wq.h>

struct dhd_deferred_event_t {
	u8	event; /* holds the event */
	void	*event_data; /* Holds event specific data */
	event_handler_t event_handler;
};
#define DEFRD_EVT_SIZE	sizeof(struct dhd_deferred_event_t)

struct dhd_deferred_wq {
	struct work_struct	deferred_work; /* should be the first member */

	/*
	 * work events may occur simultaneously.
	 * Can hold upto 64 low priority events and 4 high priority events
	 */
#define DHD_PRIO_WORK_FIFO_SIZE	(4 * sizeof(struct dhd_deferred_event_t))
#define DHD_WORK_FIFO_SIZE	(64 * sizeof(struct dhd_deferred_event_t))
	struct kfifo			*prio_fifo;
	struct kfifo			*work_fifo;
	u8				*prio_fifo_buf;
	u8				*work_fifo_buf;
	spinlock_t			work_lock;
	void				*dhd_info; /* review: does it require */
};

static inline struct kfifo*
dhd_kfifo_init(u8 *buf, int size, spinlock_t *lock)
{
	struct kfifo *fifo;
	gfp_t flags = CAN_SLEEP()? GFP_KERNEL : GFP_ATOMIC;

#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 33))
	fifo = kfifo_init(buf, size, flags, lock);
#else
	fifo = (struct kfifo *)kzalloc(sizeof(struct kfifo), flags);
	if (!fifo) {
		return NULL;
	}
	kfifo_init(fifo, buf, size);
#endif /* (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 33)) */
	return fifo;
}

static inline void
dhd_kfifo_free(struct kfifo *fifo)
{
	kfifo_free(fifo);
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 31))
	/* FC11 releases the fifo memory */
	kfree(fifo);
#endif
}

/* deferred work functions */
static void dhd_deferred_work_handler(struct work_struct *data);

void*
dhd_deferred_work_init(void *dhd_info)
{
	struct dhd_deferred_wq	*work = NULL;
	u8*	buf;
	unsigned long	fifo_size = 0;
	gfp_t	flags = CAN_SLEEP()? GFP_KERNEL : GFP_ATOMIC;

	if (!dhd_info) {
		DHD_ERROR(("%s: dhd info not initialized\n", __FUNCTION__));
		goto return_null;
	}

	work = (struct dhd_deferred_wq *)kzalloc(sizeof(struct dhd_deferred_wq),
		flags);

	if (!work) {
		DHD_ERROR(("%s: work queue creation failed \n", __FUNCTION__));
		goto return_null;
	}

	INIT_WORK((struct work_struct *)work, dhd_deferred_work_handler);

	/* initialize event fifo */
	spin_lock_init(&work->work_lock);

	/* allocate buffer to hold prio events */
	fifo_size = DHD_PRIO_WORK_FIFO_SIZE;
	fifo_size = is_power_of_2(fifo_size)? fifo_size : roundup_pow_of_two(fifo_size);
	buf = (u8*)kzalloc(fifo_size, flags);
	if (!buf) {
		DHD_ERROR(("%s: prio work fifo allocation failed \n", __FUNCTION__));
		goto return_null;
	}

	/* Initialize prio event fifo */
	work->prio_fifo = dhd_kfifo_init(buf, fifo_size, &work->work_lock);
	if (!work->prio_fifo) {
		kfree(buf);
		goto return_null;
	}

	/* allocate buffer to hold work events */
	fifo_size = DHD_WORK_FIFO_SIZE;
	fifo_size = is_power_of_2(fifo_size)? fifo_size : roundup_pow_of_two(fifo_size);
	buf = (u8*)kzalloc(fifo_size, flags);
	if (!buf) {
		DHD_ERROR(("%s: work fifo allocation failed \n", __FUNCTION__));
		goto return_null;
	}

	/* Initialize event fifo */
	work->work_fifo = dhd_kfifo_init(buf, fifo_size, &work->work_lock);
	if (!work->work_fifo) {
		kfree(buf);
		goto return_null;
	}

	work->dhd_info = dhd_info;
	DHD_ERROR(("%s: work queue initialized \n", __FUNCTION__));
	return work;

return_null:

	if (work)
		dhd_deferred_work_deinit(work);

	return NULL;
}

void
dhd_deferred_work_deinit(void *work)
{
	struct dhd_deferred_wq *deferred_work = work;

	if (!deferred_work) {
		DHD_ERROR(("%s: deferred work has been freed alread \n", __FUNCTION__));
		return;
	}

	/* cancel the deferred work handling */
	cancel_work_sync((struct work_struct *)deferred_work);

	/*
	 * free work event fifo.
	 * kfifo_free frees locally allocated fifo buffer
	 */
	if (deferred_work->prio_fifo)
		dhd_kfifo_free(deferred_work->prio_fifo);

	if (deferred_work->work_fifo)
		dhd_kfifo_free(deferred_work->work_fifo);

	kfree(deferred_work);
}

/*
 *	Prepares event to be queued
 *	Schedules the event
 */
int
dhd_deferred_schedule_work(void *workq, void *event_data, u8 event,
	event_handler_t event_handler, u8 priority)
{
	struct dhd_deferred_wq *deferred_wq = (struct dhd_deferred_wq *) workq;
	struct	dhd_deferred_event_t	deferred_event;
	int	status;

	if (!deferred_wq) {
		DHD_ERROR(("%s: work queue not initialized \n", __FUNCTION__));
		ASSERT(0);
		return DHD_WQ_STS_UNINITIALIZED;
	}

	if (!event || (event >= DHD_MAX_WQ_EVENTS)) {
		DHD_ERROR(("%s: Unknown event \n", __FUNCTION__));
		return DHD_WQ_STS_UNKNOWN_EVENT;
	}

	/*
	 * default element size is 1, which can be changed
	 * using kfifo_esize(). Older kernel(FC11) doesn't support
	 * changing element size. For compatibility changing
	 * element size is not prefered
	 */
	ASSERT(kfifo_esize(deferred_wq->prio_fifo) == 1);
	ASSERT(kfifo_esize(deferred_wq->work_fifo) == 1);

	deferred_event.event = event;
	deferred_event.event_data = event_data;
	deferred_event.event_handler = event_handler;

	if (priority == DHD_WORK_PRIORITY_HIGH) {
		status = kfifo_in_spinlocked(deferred_wq->prio_fifo, &deferred_event,
			DEFRD_EVT_SIZE, &deferred_wq->work_lock);
	} else {
		status = kfifo_in_spinlocked(deferred_wq->work_fifo, &deferred_event,
			DEFRD_EVT_SIZE, &deferred_wq->work_lock);
	}

	if (!status) {
		return DHD_WQ_STS_SCHED_FAILED;
	}
	schedule_work((struct work_struct *)deferred_wq);
	return DHD_WQ_STS_OK;
}

static int
dhd_get_scheduled_work(struct dhd_deferred_wq *deferred_wq, struct dhd_deferred_event_t *event)
{
	int	status = 0;

	if (!deferred_wq) {
		DHD_ERROR(("%s: work queue not initialized \n", __FUNCTION__));
		return DHD_WQ_STS_UNINITIALIZED;
	}

	/*
	 * default element size is 1 byte, which can be changed
	 * using kfifo_esize(). Older kernel(FC11) doesn't support
	 * changing element size. For compatibility changing
	 * element size is not prefered
	 */
	ASSERT(kfifo_esize(deferred_wq->prio_fifo) == 1);
	ASSERT(kfifo_esize(deferred_wq->work_fifo) == 1);

	/* first read  priorit event fifo */
	status = kfifo_out_spinlocked(deferred_wq->prio_fifo, event,
		DEFRD_EVT_SIZE, &deferred_wq->work_lock);

	if (!status) {
		/* priority fifo is empty. Now read low prio work fifo */
		status = kfifo_out_spinlocked(deferred_wq->work_fifo, event,
			DEFRD_EVT_SIZE, &deferred_wq->work_lock);
	}

	return status;
}

/*
 *	Called when work is scheduled
 */
static void
dhd_deferred_work_handler(struct work_struct *work)
{
	struct dhd_deferred_wq		*deferred_work = (struct dhd_deferred_wq *)work;
	struct dhd_deferred_event_t	work_event;
	int				status;

	if (!deferred_work) {
		DHD_ERROR(("%s: work queue not initialized\n", __FUNCTION__));
		return;
	}

	do {
		status = dhd_get_scheduled_work(deferred_work, &work_event);
		DHD_TRACE(("%s: event to handle %d \n", __FUNCTION__, status));
		if (!status) {
			DHD_TRACE(("%s: No event to handle %d \n", __FUNCTION__, status));
			break;
		}

		if (work_event.event > DHD_MAX_WQ_EVENTS) {
			DHD_TRACE(("%s: Unknown event %d \n", __FUNCTION__, work_event.event));
			break;
		}

		if (work_event.event_handler) {
			work_event.event_handler(deferred_work->dhd_info,
				work_event.event_data, work_event.event);
		} else {
			DHD_ERROR(("%s: event not defined %d\n", __FUNCTION__, work_event.event));
		}
	} while (1);
	return;
}


text:
title: Oct 19th Class
date: 10/19/2015
icon: checkbox-marked-circle
taxonomy:
  tag: [preparation]
reading:
  link: "https://login.proxy.lib.sfu.ca/login?url=http://dl.acm.org/citation.cfm?id=503355.503366&coll=DL&dl=ACM&CFID=521069893&CFTOKEN=17492962"
  text: "Conceptual Models: Begin by Designing What to Design, ACM"
quiz:
  link: "https://canvas.sfu.ca/courses/22099/quizzes/28959"
  text: "Required Reading Quiz"
continue_link: false
published: true
---

##### Slides to be Presented
[Conceptual Models (in progress)](http://slides.com/paulhibbitts/cmpt-363-153-conceptual-models#/)

After attending this class, [share your one-minute summary](https://canvas.sfu.ca/courses/22099/discussion_topics/382630) before midnight, October 19th.


text:
from django import forms

class StartForm(forms.Form):
    name = forms.CharField(
        max_length=255,
        label="What is your name?",
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )