text:
package android.os;

import java.util.ArrayList;

/**
 * Gives access to the system properties store.  The system properties
 * store contains a list of string key-value pairs.
 *
 * {@hide}
 */
public class SystemProperties
{
    public static final int PROP_NAME_MAX = 31;
    public static final int PROP_VALUE_MAX = 91;

    private static final ArrayList<Runnable> sChangeCallbacks = new ArrayList<Runnable>();

    private static native String native_get(String key);
    private static native String native_get(String key, String def);
    private static native int native_get_int(String key, int def);
    private static native long native_get_long(String key, long def);
    private static native boolean native_get_boolean(String key, boolean def);
    private static native void native_set(String key, String def);
    private static native void native_add_change_callback();

    /**
     * Get the value for the given key.
     * @return an empty string if the key isn't found
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
    public static String get(String key) {
        if (key.length() > PROP_NAME_MAX) {
            throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
        }
        return native_get(key);
    }

    /**
     * Get the value for the given key.
     * @return if the key isn't found, return def if it isn't null, or an empty string otherwise
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
    public static String get(String key, String def) {
        if (key.length() > PROP_NAME_MAX) {
            throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
        }
        return native_get(key, def);
    }

    /**
     * Get the value for the given key, and return as an integer.
     * @param key the key to lookup
     * @param def a default value to return
     * @return the key parsed as an integer, or def if the key isn't found or
     *         cannot be parsed
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
    public static int getInt(String key, int def) {
        if (key.length() > PROP_NAME_MAX) {
            throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
        }
        return native_get_int(key, def);
    }

    /**
     * Get the value for the given key, and return as a long.
     * @param key the key to lookup
     * @param def a default value to return
     * @return the key parsed as a long, or def if the key isn't found or
     *         cannot be parsed
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
    public static long getLong(String key, long def) {
        if (key.length() > PROP_NAME_MAX) {
            throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
        }
        return native_get_long(key, def);
    }

    /**
     * Get the value for the given key, returned as a boolean.
     * Values 'n', 'no', '0', 'false' or 'off' are considered false.
     * Values 'y', 'yes', '1', 'true' or 'on' are considered true.
     * (case sensitive).
     * If the key does not exist, or has any other value, then the default
     * result is returned.
     * @param key the key to lookup
     * @param def a default value to return
     * @return the key parsed as a boolean, or def if the key isn't found or is
     *         not able to be parsed as a boolean.
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
    public static boolean getBoolean(String key, boolean def) {
        if (key.length() > PROP_NAME_MAX) {
            throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
        }
        return native_get_boolean(key, def);
    }

    /**
     * Set the value for the given key.
     * @throws IllegalArgumentException if the key exceeds 32 characters
     * @throws IllegalArgumentException if the value exceeds 92 characters
     */
    public static void set(String key, String val) {
        if (key.length() > PROP_NAME_MAX) {
            throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
        }
        if (val != null && val.length() > PROP_VALUE_MAX) {
            throw new IllegalArgumentException("val.length > " +
                PROP_VALUE_MAX);
        }
        native_set(key, val);
    }

    public static void addChangeCallback(Runnable callback) {
        synchronized (sChangeCallbacks) {
            if (sChangeCallbacks.size() == 0) {
                native_add_change_callback();
            }
            sChangeCallbacks.add(callback);
        }
    }

    static void callChangeCallbacks() {
        synchronized (sChangeCallbacks) {
            //Log.i("foo", "Calling " + sChangeCallbacks.size() + " change callbacks!");
            if (sChangeCallbacks.size() == 0) {
                return;
            }
            ArrayList<Runnable> callbacks = new ArrayList<Runnable>(sChangeCallbacks);
            for (int i=0; i<callbacks.size(); i++) {
                callbacks.get(i).run();
            }
        }
    }
}


text:
using Landis.SpatialModeling;

namespace Landis.Extension.BiomassHarvest
{
    public class IntPixel : Pixel
    {
        public Band<int> MapCode  = "The numeric code for each raster cell";

        public IntPixel()
        {
            SetBands(MapCode);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

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

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>{{title}}</title>

    <link href="/assets/css/paper.css" rel="stylesheet">
    <link href="/assets/css/navbar.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Community Thing

Home

About

Contact


text:
package org.insightech.er.common.widgets;

import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.insightech.er.ERDiagramActivator;
import org.insightech.er.common.dialog.AbstractDialog;
import org.insightech.er.common.dialog.ValidatableTabWrapper;
import org.insightech.er.editor.model.ERDiagram;
import org.insightech.er.editor.view.dialog.common.EditableTable;

public class ListenerAppender {

    public static void addTextAreaListener(final Text text, final AbstractDialog dialog, final boolean selectAll, final boolean imeOn) {
        addFocusListener(text, selectAll, imeOn);
        addTraverseListener(text);
        if (dialog != null) {
            addModifyListener(text, dialog);
        }
    }

    public static void addTextListener(final Text text, final AbstractDialog dialog, final boolean imeOn) {
        addFocusListener(text, imeOn);
        if (dialog != null) {
            addModifyListener(text, dialog);
        }
    }

    public static void addFocusListener(final Text text, final boolean imeOn) {
        addFocusListener(text, true, imeOn);
    }

    public static void addFocusListener(final Text text, final boolean selectAll, final boolean imeOn) {
        text.addFocusListener(new FocusAdapter() {

            /**
             * {@inheritDoc}
             */
            @Override
            public void focusGained(final FocusEvent e) {
                final ERDiagram diagram = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getAdapter(ERDiagram.class);

                if (diagram != null) {
                    if (diagram.getDiagramContents().getSettings().isAutoImeChange()) {
                        if (imeOn) {
                            text.getShell().setImeInputMode(SWT.DBCS | SWT.NATIVE);

                        } else {
                            text.getShell().setImeInputMode(SWT.ALPHA);
                        }
                    }
                }

                if (selectAll) {
                    text.selectAll();
                }

                super.focusGained(e);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void focusLost(final FocusEvent e) {
                // text.clearSelection();
                super.focusLost(e);
            }
        });
    }

    public static void addFocusListener(final Combo combo, final boolean imeOn) {
        combo.addFocusListener(new FocusAdapter() {

            /**
             * {@inheritDoc}
             */
            @Override
            public void focusGained(final FocusEvent e) {
                final ERDiagram diagram = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getAdapter(ERDiagram.class);

                if (diagram != null) {
                    if (diagram.getDiagramContents().getSettings().isAutoImeChange()) {
                        if (imeOn) {
                            combo.getShell().setImeInputMode(SWT.DBCS | SWT.NATIVE);

                        } else {
                            combo.getShell().setImeInputMode(SWT.ALPHA);
                        }
                    }
                }

                super.focusGained(e);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void focusLost(final FocusEvent e) {
                super.focusLost(e);
            }
        });
    }

    public static void addTraverseListener(final Text textArea) {
        textArea.addTraverseListener(new TraverseListener() {
            @Override
            public void keyTraversed(final TraverseEvent e) {
                if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
                    e.doit = true;
                }
            }
        });
    }

    public static void addModifyListener(final Text text, final AbstractDialog dialog) {
        text.addModifyListener(new ModifyListener() {
            @Override
            public void modifyText(final ModifyEvent e) {
                dialog.validate();
            }

        });
    }

    public static void addComboListener(final Combo combo, final AbstractDialog dialog, final boolean imeOn) {
        addFocusListener(combo, imeOn);

        if (dialog != null) {
            combo.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(final ModifyEvent e) {
                    dialog.validate();
                }
            });
        }
    }

    public static void addCheckBoxListener(final Button button, final AbstractDialog dialog) {
        button.addSelectionListener(new SelectionListener() {
            @Override
            public void widgetDefaultSelected(final SelectionEvent e) {
                widgetSelected(e);
            }

            @Override
            public void widgetSelected(final SelectionEvent e) {
                dialog.validate();
            }
        });

        button.addFocusListener(new FocusAdapter() {

            /**
             * {@inheritDoc}
             */
            @Override
            public void focusGained(final FocusEvent e) {
                final ERDiagram diagram = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getAdapter(ERDiagram.class);

                if (diagram != null) {
                    if (diagram.getDiagramContents().getSettings().isAutoImeChange()) {
                        button.getShell().setImeInputMode(SWT.ALPHA);
                    }
                }
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void focusLost(final FocusEvent e) {}
        });
    }

    public static void addTableEditListener(final Table table, final TableEditor tableEditor, final EditableTable editableTable) {

        table.addMouseListener(new MouseAdapter() {

            private Point getSelectedCell(final MouseEvent e) {
                final int vIndex = table.getSelectionIndex();
                if (vIndex != -1) {
                    final TableItem item = table.getItem(vIndex);
                    for (int hIndex = 0; hIndex < table.getColumnCount(); hIndex++) {
                        if (item.getBounds(hIndex).contains(e.x, e.y)) {
                            final Point xy = new Point(hIndex, vIndex);
                            xy.y = vIndex;
                            xy.x = hIndex;
                            return xy;
                        }
                    }
                }
                return null;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void mouseDown(final MouseEvent event) {
                if (!editableTable.validate()) {
                    return;
                }
                try {
                    final Point xy = getSelectedCell(event);
                    if (xy != null) {
                        final TableItem tableItem = table.getItem(xy.y);
                        createEditor(table, tableItem, tableEditor, xy, editableTable);
                    }
                } catch (final Exception e) {
                    ERDiagramActivator.log(e);
                }
            }

            @Override
            public void mouseDoubleClick(final MouseEvent event) {
                try {
                    final Point xy = getSelectedCell(event);
                    if (xy != null) {
                        editableTable.onDoubleClicked(xy);
                    }
                } catch (final Exception e) {
                    ERDiagramActivator.log(e);
                }
            }
        });
    }

    private static void createEditor(final Table table, final TableItem tableItem, final TableEditor tableEditor, final Point xy, final EditableTable editableTable) {
        final Control control = editableTable.getControl(xy);
        if (control == null) {
            return;
        }

        if (control instanceof Text) {
            final Text text = (Text) control;
            text.setText(tableItem.getText(xy.x));
        }

        // フォーカスが外れたときの処理
        control.addFocusListener(new FocusAdapter() {

            /**
             * {@inheritDoc}
             */
            @Override
            public void focusLost(final FocusEvent e) {
                setEditValue(control, tableItem, xy, editableTable);
            }

        });

        // ENTERとESCが押されたときの処理
        control.addKeyListener(new KeyAdapter() {

            /**
             * {@inheritDoc}
             */
            @Override
            public void keyReleased(final KeyEvent keyevent) {
                if (keyevent.character == SWT.CR) {
                    setEditValue(control, tableItem, xy, editableTable);

                } else if (keyevent.character == SWT.ESC) {
                    control.dispose();
                }

            }
        });

        tableEditor.setEditor(control, tableItem, xy.x);
        control.setFocus();
        table.setSelection(new int[0]);

        if (control instanceof Text) {
            final Text text = (Text) control;
            text.selectAll();
        }
    }

    private static void setEditValue(final Control control, final TableItem tableItem, final Point xy, final EditableTable editableTable) {
        editableTable.setData(xy, control);
        if (editableTable.validate()) {
            control.dispose();
        }
    }

    public static void addTabListener(final TabFolder tabFolder, final List<ValidatableTabWrapper> tabWrapperList) {
        tabFolder.addSelectionListener(new SelectionListener() {

            @Override
            public void widgetDefaultSelected(final SelectionEvent e) {}

            @Override
            public void widgetSelected(final SelectionEvent e) {
                final int index = tabFolder.getSelectionIndex();

                final ValidatableTabWrapper selectedTabWrapper = tabWrapperList.get(index);
                selectedTabWrapper.restruct();
                selectedTabWrapper.setInitFocus();
            }

        });
    }

    public static void addModifyListener(final Scale scale, final Spinner spinner, final int diff, final AbstractDialog dialog) {
        if (dialog != null) {
            spinner.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(final SelectionEvent e) {
                    final int value = spinner.getSelection();
                    scale.setSelection(value - diff);
                    dialog.validate();
                }
            });

            scale.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(final SelectionEvent e) {
                    final int value = scale.getSelection();
                    spinner.setSelection(value + diff);
                    dialog.validate();
                }

            });
        }
    }

    public static void addPathTextListener(final AbstractPathText pathText, final AbstractDialog dialog) {

        if (dialog != null) {
            pathText.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(final ModifyEvent e) {
                    dialog.validate();
                }

            });
        }
    }

}


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

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

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math.util.MathUtils;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingAttachment;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AttachmentIfc;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.services.GradebookServiceException;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.ui.bean.evaluation.AgentResults;
import org.sakaiproject.tool.assessment.ui.bean.evaluation.QuestionScoresBean;
import org.sakaiproject.tool.assessment.ui.bean.evaluation.TotalScoresBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.tool.assessment.util.TextFormat;

/**
 *

 * This handles the updating of the Question Score page.
 *

 *
Description: Action Listener Evaluation Updating Question Score front door

 *
Copyright: Copyright (c) 2004

 *
Organization: Sakai Project

 * @author Ed Smiley
 * @version $Id$
 */

public class QuestionScoreUpdateListener
  implements ActionListener
{
  private static Log log = LogFactory.getLog(QuestionScoreUpdateListener.class);
  //private static EvaluationListenerUtil util;
  //private static BeanSort bs;
  //private static ContextUtil cu;

  /**
   * Standard process action method.
   * @param ae ActionEvent
   * @throws AbortProcessingException
   */
  public void processAction(ActionEvent ae) throws
    AbortProcessingException
  {
    log.debug("Question Score Update LISTENER.");
    QuestionScoresBean bean = (QuestionScoresBean) ContextUtil.lookupBean("questionScores");
    TotalScoresBean tbean = (TotalScoresBean) ContextUtil.lookupBean("totalScores");
    log.debug("Calling saveQuestionScores.");

    Long publishedId = Long.valueOf(ContextUtil.lookupParam("publishedId"));
    Long publishedIdFromBean = tbean.getPublishedAssessment().getPublishedAssessmentId();
    if (publishedId != null && publishedIdFromBean != null && !publishedId.equals(publishedIdFromBean)) {
    	throw new IllegalArgumentException("Published id has changed from " + publishedIdFromBean + " to " + publishedId);
    }

    tbean.setAssessmentGradingHash(publishedIdFromBean);
    try{
      if (!saveQuestionScores(bean, tbean))
      {
        throw new RuntimeException("failed to call saveQuestionScores.");
      }
    } catch (GradebookServiceException ge) {
       FacesContext context = FacesContext.getCurrentInstance();
       String err=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.AuthorMessages", "gradebook_exception_error");
       context.addMessage(null, new FacesMessage(err));

    }

  }

  /**
   * Persist the results from the ActionForm in the question page.
   * @param bean QuestionScoresBean bean
   * @return true if successful
   */
  public boolean saveQuestionScores(QuestionScoresBean bean, TotalScoresBean tbean)
  {
    try
    {
      GradingService delegate = new GradingService();
      //String publishedId = ContextUtil.lookupParam("publishedId");
      String itemId = ContextUtil.lookupParam("itemId");
      String which = ContextUtil.lookupParam("allSubmissions");
      if (which == null)
        which = "false";
      Collection agents = bean.getAgents();
      //ArrayList items = new ArrayList();
      Iterator iter = agents.iterator();
      while (iter.hasNext())
      {
        // each agent has a list of modified itemGrading
        AgentResults ar = (AgentResults) iter.next();
        // Get the itemgradingdata list for this result
        ArrayList datas = (ArrayList) bean.getScoresByItem().get
          (ar.getAssessmentGradingId() + ":" + itemId);
        if (datas == null)
          datas = new ArrayList();

        int fibFinNumCorrect  = 0;
        if (bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) {
        	Iterator iter1 = datas.iterator();
        	while (iter1.hasNext()){
        		Object obj = iter1.next();
        		ItemGradingData data = (ItemGradingData) obj;
        		if (data.getIsCorrect() != null && data.getIsCorrect().booleanValue()) {
        			fibFinNumCorrect++;
        		}
        	}
        }

        boolean hasUpdateAttachment = false;
        Iterator iter2 = datas.iterator();
        while (iter2.hasNext()){
          Object obj = iter2.next();
          //log.info("Data = " + obj);
          ItemGradingData data = (ItemGradingData) obj;

          // check if there is differnce in score, if so, update. Otherwise, do nothing
          double newAutoScore = 0;
          if ((bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) && fibFinNumCorrect != 0) {
        	  if (Boolean.TRUE.equals(data.getIsCorrect())) {
        		  newAutoScore = (Double.valueOf(ar.getTotalAutoScore())).doubleValue() / (double) fibFinNumCorrect;
        	  }
          }
          else {
        	  newAutoScore = (Double.valueOf(ar.getTotalAutoScore())).doubleValue() / (double) datas.size();
          }
          String newComments = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, ar.getComments());
          ar.setComments(newComments);
          if (newComments!=null) {
        	  newComments = newComments.trim();
          }
          else {
        	  newComments = "";
          }

          double oldAutoScore = 0;
          if (data.getAutoScore() !=null)
            oldAutoScore=data.getAutoScore().doubleValue();

          String oldComments = data.getComments();
          if (oldComments!=null) {
        	  oldComments = oldComments.trim();
          }
          else {
        	  oldComments = "";
          }

          StringBuffer logString = new StringBuffer();
          logString.append("gradedBy=");
          logString.append(AgentFacade.getAgentString());
          logString.append(", itemGradingId=");
          logString.append(data.getItemGradingId());

          // if newAutoScore != oldAutoScore
          if (!(MathUtils.equalsIncludingNaN(newAutoScore, oldAutoScore, 0.0001))) {
        	data.setAutoScore(Double.valueOf(newAutoScore));
        	logString.append(", newAutoScore=");
            logString.append(newAutoScore);
            logString.append(", oldAutoScore=");
            logString.append(oldAutoScore);
          }
          if (!newComments.equals(oldComments)) {
            data.setComments(ar.getComments());
            logString.append(", newComments=");
            logString.append(newComments);
            logString.append(", oldComments=");
            logString.append(oldComments);
          }

          // if newAutoScore != oldAutoScore or newComments != oldComments
          if (!(MathUtils.equalsIncludingNaN(newAutoScore, oldAutoScore, 0.0001)) || !newComments.equals(oldComments)){
            data.setGradedBy(AgentFacade.getAgentString());
            data.setGradedDate(new Date());
            String targetString = "siteId=" + AgentFacade.getCurrentSiteId() + ", " + logString.toString();
            String safeString = targetString.length() > 255 ? targetString.substring(0, 255) : targetString;
            EventTrackingService.post(EventTrackingService.newEvent("sam.question.score.update", safeString, true));
            delegate.updateItemScore(data, newAutoScore-oldAutoScore, tbean.getPublishedAssessment());
          }

          if (!hasUpdateAttachment) {
        	  hasUpdateAttachment = true;
        	  updateAttachment(data, ar, bean);
          }
        }
      }

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

    }
    catch (Exception e)
    {
      e.printStackTrace();
      return false;
    }
    return true;
  }

  private void updateAttachment(ItemGradingData itemGradingData, AgentResults agentResults, QuestionScoresBean bean){
	  List oldList = itemGradingData.getItemGradingAttachmentList();
	  List newList = agentResults.getItemGradingAttachmentList();
	  if ((oldList == null || oldList.size() == 0 ) && (newList == null || newList.size() == 0)) return;
	  List attachmentList = new ArrayList();
	  HashMap map = getAttachmentIdHash(oldList);
	  for (int i=0; i<newList.size(); i++){
		  ItemGradingAttachment itemGradingAttachment = (ItemGradingAttachment) newList.get(i);
		  if (map.get(itemGradingAttachment.getAttachmentId()) != null){
			  // exist already, remove it from map
			  map.remove(itemGradingAttachment.getAttachmentId());
		  }
		  else{
			  // new attachments
			  itemGradingAttachment.setItemGrading(itemGradingData);
			  itemGradingAttachment.setAttachmentType(AttachmentIfc.ITEMGRADING_ATTACHMENT);
			  attachmentList.add(itemGradingAttachment);
		  }
	  }
	  // save new ones
	  GradingService gradingService = new GradingService();
	  if (attachmentList.size() > 0) {
			gradingService.saveOrUpdateAttachments(attachmentList);
			EventTrackingService.post(EventTrackingService.newEvent("sam.student.score.update",
					"siteId=" + AgentFacade.getCurrentSiteId() + ", Adding " + attachmentList.size() + " attachments for itemGradingData id = " + itemGradingData.getItemGradingId(),
					true));
		}

	  // remove old ones
	  Set set = map.keySet();
	  Iterator iter = set.iterator();
	  while (iter.hasNext()){
		  Long attachmentId = (Long)iter.next();
		  gradingService.removeItemGradingAttachment(attachmentId.toString());
		  EventTrackingService.post(EventTrackingService.newEvent("sam.student.score.update",
				  "siteId=" + AgentFacade.getCurrentSiteId() + ", Removing attachmentId = " + attachmentId, true));
	  }
	  bean.setIsAnyItemGradingAttachmentListModified(true);
  }

  private HashMap getAttachmentIdHash(List list){
    HashMap map = new HashMap();
    for (int i=0; i<list.size(); i++){
    	ItemGradingAttachment a = (ItemGradingAttachment)list.get(i);
      map.put(a.getAttachmentId(), a);
    }
    return map;
  }
}


text:
package org.apache.rocketmq.client.impl;

import java.lang.reflect.Field;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.hook.SendMessageContext;
import org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.PlainAccessConfig;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader;
import org.apache.rocketmq.common.protocol.header.SendMessageResponseHeader;
import org.apache.rocketmq.remoting.InvokeCallback;
import org.apache.rocketmq.remoting.RemotingClient;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.remoting.netty.NettyClientConfig;
import org.apache.rocketmq.remoting.netty.ResponseFuture;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;

@RunWith(MockitoJUnitRunner.class)
public class MQClientAPIImplTest {
    private MQClientAPIImpl mqClientAPI = new MQClientAPIImpl(new NettyClientConfig(), null, null, new ClientConfig());
    @Mock
    private RemotingClient remotingClient;
    @Mock
    private DefaultMQProducerImpl defaultMQProducerImpl;

    private String brokerAddr = "127.0.0.1";
    private String brokerName = "DefaultBroker";
    private static String group = "FooBarGroup";
    private static String topic = "FooBar";
    private Message msg = new Message("FooBar", new byte[] {});

    @Before
    public void init() throws Exception {
        Field field = MQClientAPIImpl.class.getDeclaredField("remotingClient");
        field.setAccessible(true);
        field.set(mqClientAPI, remotingClient);
    }

    @Test
    public void testSendMessageOneWay_Success() throws RemotingException, InterruptedException, MQBrokerException {
        doNothing().when(remotingClient).invokeOneway(anyString(), any(RemotingCommand.class), anyLong());
        SendResult sendResult = mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(),
            3 * 1000, CommunicationMode.ONEWAY, new SendMessageContext(), defaultMQProducerImpl);
        assertThat(sendResult).isNull();
    }

    @Test
    public void testSendMessageOneWay_WithException() throws RemotingException, InterruptedException, MQBrokerException {
        doThrow(new RemotingTimeoutException("Remoting Exception in Test")).when(remotingClient).invokeOneway(anyString(), any(RemotingCommand.class), anyLong());
        try {
            mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(),
                3 * 1000, CommunicationMode.ONEWAY, new SendMessageContext(), defaultMQProducerImpl);
            failBecauseExceptionWasNotThrown(RemotingException.class);
        } catch (RemotingException e) {
            assertThat(e).hasMessage("Remoting Exception in Test");
        }

        doThrow(new InterruptedException("Interrupted Exception in Test")).when(remotingClient).invokeOneway(anyString(), any(RemotingCommand.class), anyLong());
        try {
            mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(),
                3 * 1000, CommunicationMode.ONEWAY, new SendMessageContext(), defaultMQProducerImpl);
            failBecauseExceptionWasNotThrown(InterruptedException.class);
        } catch (InterruptedException e) {
            assertThat(e).hasMessage("Interrupted Exception in Test");
        }
    }

    @Test
    public void testSendMessageSync_Success() throws InterruptedException, RemotingException, MQBrokerException {
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                RemotingCommand request = mock.getArgument(1);
                return createSuccessResponse(request);
            }
        }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

        SendMessageRequestHeader requestHeader = createSendMessageRequestHeader();

        SendResult sendResult = mqClientAPI.sendMessage(brokerAddr, brokerName, msg, requestHeader,
            3 * 1000, CommunicationMode.SYNC, new SendMessageContext(), defaultMQProducerImpl);

        assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
        assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
        assertThat(sendResult.getQueueOffset()).isEqualTo(123L);
        assertThat(sendResult.getMessageQueue().getQueueId()).isEqualTo(1);
    }

    @Test
    public void testSendMessageSync_WithException() throws InterruptedException, RemotingException, MQBrokerException {
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                RemotingCommand request = mock.getArgument(1);
                RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class);
                response.setCode(ResponseCode.SYSTEM_ERROR);
                response.setOpaque(request.getOpaque());
                response.setRemark("Broker is broken.");
                return response;
            }
        }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

        SendMessageRequestHeader requestHeader = createSendMessageRequestHeader();

        try {
            mqClientAPI.sendMessage(brokerAddr, brokerName, msg, requestHeader,
                3 * 1000, CommunicationMode.SYNC, new SendMessageContext(), defaultMQProducerImpl);
            failBecauseExceptionWasNotThrown(MQBrokerException.class);
        } catch (MQBrokerException e) {
            assertThat(e).hasMessageContaining("Broker is broken.");
        }
    }

    @Test
    public void testSendMessageAsync_Success() throws RemotingException, InterruptedException, MQBrokerException {
        doNothing().when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.class));
        SendResult sendResult = mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(),
            3 * 1000, CommunicationMode.ASYNC, new SendMessageContext(), defaultMQProducerImpl);
        assertThat(sendResult).isNull();

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                InvokeCallback callback = mock.getArgument(3);
                RemotingCommand request = mock.getArgument(1);
                ResponseFuture responseFuture = new ResponseFuture(null, request.getOpaque(), 3 * 1000, null, null);
                responseFuture.setResponseCommand(createSuccessResponse(request));
                callback.operationComplete(responseFuture);
                return null;
            }
        }).when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.class));
        SendMessageContext sendMessageContext = new SendMessageContext();
        sendMessageContext.setProducer(new DefaultMQProducerImpl(new DefaultMQProducer()));
        mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(), 3 * 1000, CommunicationMode.ASYNC,
            new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
                    assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
                    assertThat(sendResult.getQueueOffset()).isEqualTo(123L);
                    assertThat(sendResult.getMessageQueue().getQueueId()).isEqualTo(1);
                }

                @Override
                public void onException(Throwable e) {
                }
            },
            null, null, 0, sendMessageContext, defaultMQProducerImpl);
    }

    @Test
    public void testSendMessageAsync_WithException() throws RemotingException, InterruptedException, MQBrokerException {
        doThrow(new RemotingTimeoutException("Remoting Exception in Test")).when(remotingClient)
            .invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.class));
        try {
            mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(),
                3 * 1000, CommunicationMode.ASYNC, new SendMessageContext(), defaultMQProducerImpl);
            failBecauseExceptionWasNotThrown(RemotingException.class);
        } catch (RemotingException e) {
            assertThat(e).hasMessage("Remoting Exception in Test");
        }

        doThrow(new InterruptedException("Interrupted Exception in Test")).when(remotingClient)
            .invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.class));
        try {
            mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(),
                3 * 1000, CommunicationMode.ASYNC, new SendMessageContext(), defaultMQProducerImpl);
            failBecauseExceptionWasNotThrown(InterruptedException.class);
        } catch (InterruptedException e) {
            assertThat(e).hasMessage("Interrupted Exception in Test");
        }
    }

    @Test
    public void testCreatePlainAccessConfig_Success() throws InterruptedException, RemotingException, MQBrokerException {

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                RemotingCommand request = mock.getArgument(1);
                return createSuccessResponse4UpdateAclConfig(request);
            }
        }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

        PlainAccessConfig config = createUpdateAclConfig();

        try {
            mqClientAPI.createPlainAccessConfig(brokerAddr, config, 3 * 1000);
        } catch (MQClientException ex) {

        }
    }

    @Test
    public void testCreatePlainAccessConfig_Exception() throws InterruptedException, RemotingException, MQBrokerException {

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                RemotingCommand request = mock.getArgument(1);
                return createErrorResponse4UpdateAclConfig(request);
            }
        }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

        PlainAccessConfig config = createUpdateAclConfig();
        try {
            mqClientAPI.createPlainAccessConfig(brokerAddr, config, 3 * 1000);
        } catch (MQClientException ex) {
            assertThat(ex.getResponseCode()).isEqualTo(209);
            assertThat(ex.getErrorMessage()).isEqualTo("corresponding to accessConfig has been updated failed");
        }
    }

    @Test
    public void testDeleteAccessConfig_Success() throws InterruptedException, RemotingException, MQBrokerException {

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                RemotingCommand request = mock.getArgument(1);
                return createSuccessResponse4DeleteAclConfig(request);
            }
        }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

        String accessKey = "1234567";
        try {
            mqClientAPI.deleteAccessConfig(brokerAddr, accessKey, 3 * 1000);
        } catch (MQClientException ex) {

        }
    }

    @Test
    public void testDeleteAccessConfig_Exception() throws InterruptedException, RemotingException, MQBrokerException {

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                RemotingCommand request = mock.getArgument(1);
                return createErrorResponse4DeleteAclConfig(request);
            }
        }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

        try {
            mqClientAPI.deleteAccessConfig(brokerAddr, "11111", 3 * 1000);
        } catch (MQClientException ex) {
            assertThat(ex.getResponseCode()).isEqualTo(210);
            assertThat(ex.getErrorMessage()).isEqualTo("corresponding to accessConfig has been deleted failed");
        }
    }

    @Test
    public void testResumeCheckHalfMessage_WithException() throws RemotingException, InterruptedException, MQBrokerException, MQClientException {
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                RemotingCommand request = mock.getArgument(1);
                RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class);
                response.setCode(ResponseCode.SYSTEM_ERROR);
                response.setOpaque(request.getOpaque());
                response.setRemark("Put message back to RMQ_SYS_TRANS_HALF_TOPIC failed.");
                return response;
            }
        }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

        boolean result = mqClientAPI.resumeCheckHalfMessage(brokerAddr, "test", 3000);
        assertThat(result).isEqualTo(false);
    }

    @Test
    public void testResumeCheckHalfMessage_Success() throws InterruptedException, RemotingException, MQBrokerException, MQClientException {
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                RemotingCommand request = mock.getArgument(1);
                return createResumeSuccessResponse(request);
            }
        }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

        boolean result = mqClientAPI.resumeCheckHalfMessage(brokerAddr, "test", 3000);

        assertThat(result).isEqualTo(true);
    }

    @Test
    public void testSendMessageTypeofReply() throws Exception {
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                InvokeCallback callback = mock.getArgument(3);
                RemotingCommand request = mock.getArgument(1);
                ResponseFuture responseFuture = new ResponseFuture(null, request.getOpaque(), 3 * 1000, null, null);
                responseFuture.setResponseCommand(createSuccessResponse(request));
                callback.operationComplete(responseFuture);
                return null;
            }
        }).when(remotingClient).invokeAsync(Matchers.anyString(), Matchers.any(RemotingCommand.class), Matchers.anyLong(), Matchers.any(InvokeCallback.class));
        SendMessageContext sendMessageContext = new SendMessageContext();
        sendMessageContext.setProducer(new DefaultMQProducerImpl(new DefaultMQProducer()));
        msg.getProperties().put("MSG_TYPE", "reply");
        mqClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(), 3 * 1000, CommunicationMode.ASYNC,
            new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
                    assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
                    assertThat(sendResult.getQueueOffset()).isEqualTo(123L);
                    assertThat(sendResult.getMessageQueue().getQueueId()).isEqualTo(1);
                }

                @Override
                public void onException(Throwable e) {
                }
            }, null, null, 0, sendMessageContext, defaultMQProducerImpl);
    }

    private RemotingCommand createResumeSuccessResponse(RemotingCommand request) {
        RemotingCommand response = RemotingCommand.createResponseCommand(null);
        response.setCode(ResponseCode.SUCCESS);
        response.setOpaque(request.getOpaque());
        return response;
    }

    private RemotingCommand createSuccessResponse(RemotingCommand request) {
        RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class);
        response.setCode(ResponseCode.SUCCESS);
        response.setOpaque(request.getOpaque());

        SendMessageResponseHeader responseHeader = (SendMessageResponseHeader) response.readCustomHeader();
        responseHeader.setMsgId("123");
        responseHeader.setQueueId(1);
        responseHeader.setQueueOffset(123L);

        response.addExtField(MessageConst.PROPERTY_MSG_REGION, "RegionHZ");
        response.addExtField(MessageConst.PROPERTY_TRACE_SWITCH, "true");
        response.addExtField("queueId", String.valueOf(responseHeader.getQueueId()));
        response.addExtField("msgId", responseHeader.getMsgId());
        response.addExtField("queueOffset", String.valueOf(responseHeader.getQueueOffset()));
        return response;
    }

    private RemotingCommand createSuccessResponse4UpdateAclConfig(RemotingCommand request) {
        RemotingCommand response = RemotingCommand.createResponseCommand(null);
        response.setCode(ResponseCode.SUCCESS);
        response.setOpaque(request.getOpaque());
        response.markResponseType();
        response.setRemark(null);

        return response;
    }

    private RemotingCommand createSuccessResponse4DeleteAclConfig(RemotingCommand request) {
        RemotingCommand response = RemotingCommand.createResponseCommand(null);
        response.setCode(ResponseCode.SUCCESS);
        response.setOpaque(request.getOpaque());
        response.markResponseType();
        response.setRemark(null);

        return response;
    }

    private RemotingCommand createErrorResponse4UpdateAclConfig(RemotingCommand request) {
        RemotingCommand response = RemotingCommand.createResponseCommand(null);
        response.setCode(ResponseCode.UPDATE_AND_CREATE_ACL_CONFIG_FAILED);
        response.setOpaque(request.getOpaque());
        response.markResponseType();
        response.setRemark("corresponding to accessConfig has been updated failed");

        return response;
    }

    private RemotingCommand createErrorResponse4DeleteAclConfig(RemotingCommand request) {
        RemotingCommand response = RemotingCommand.createResponseCommand(null);
        response.setCode(ResponseCode.DELETE_ACL_CONFIG_FAILED);
        response.setOpaque(request.getOpaque());
        response.markResponseType();
        response.setRemark("corresponding to accessConfig has been deleted failed");

        return response;
    }

    private PlainAccessConfig createUpdateAclConfig() {

        PlainAccessConfig config = new PlainAccessConfig();
        config.setAccessKey("Rocketmq111");
        config.setSecretKey("123456789");
        config.setAdmin(true);
        config.setWhiteRemoteAddress("127.0.0.1");
        config.setDefaultTopicPerm("DENY");
        config.setDefaultGroupPerm("SUB");
        return config;
    }

    private SendMessageRequestHeader createSendMessageRequestHeader() {
        SendMessageRequestHeader requestHeader = new SendMessageRequestHeader();
        requestHeader.setBornTimestamp(System.currentTimeMillis());
        requestHeader.setTopic(topic);
        requestHeader.setProducerGroup(group);
        requestHeader.setQueueId(1);
        requestHeader.setMaxReconsumeTimes(10);
        return requestHeader;
    }
}


text:
package intervals

import "sort"

func coveredIntervals(intervals [][]int) int {
	return useSorting(intervals)
}

// useSorting time complexity O(N*logN), space complexity O(1)
func useSorting(intervals [][]int) int {
	// sort intervals based on the start time
	sort.Slice(intervals, func(i, j int) bool {
		return intervals[i][0] < intervals[j][0]
	})
	n := len(intervals)
	if n <= 1 {
		return n
	}
	left, right := intervals[0][0], intervals[0][1]
	var ans int
	for i := 1; i < n; i++ {
		if intervals[i][0] >= left && intervals[i][1] <= right {
			ans++
		} else {
			if intervals[i][0] <= left && intervals[i][1] >= right {
				ans++
			}
			left, right = intervals[i][0], intervals[i][1]
		}
	}
	return n - ans

}


text:
module Pione
  module Package
    class PackageScanner
      class << self
        def scan(location)
          new(location).scan
        end
      end

      def initialize(location)
        @package_location = location
      end

      # Scan the package location and return package informations.
      def scan
        if @package_location.directory?
          documents = scan_documents(@package_location)
          name, editor, tag, parents = scan_annotations(documents)
          scenarios = scan_scenarios(@package_location)
          bins = scan_bins(@package_location)
          etcs = scan_etcs(@package_location)

          return PackageInfo.new(
            name: name,
            editor: editor,
            tag: tag,
            parents: parents,
            documents: documents,
            scenarios: scenarios,
            bins: bins,
            etcs: etcs
          )
        else
          # the case for single document package
          name, editor, tag, parents = scan_annotations([@package_location])
          documents = [@package_location.basename]

          return PackageInfo.new(
            name: name, editor: editor, tag: tag, parents: parents,
            documents: documents
          )
        end
      end

      private

      # Scan PIONE documents in this package. This scans each directory
      # excluding scenarios in the location recursively.
      def scan_documents(location)
        location.entries.each_with_object([]) do |entry, paths|
          if entry.file?
            # PIONE document has extension ".pione"
            if /^[^.].*.pione$/.match(entry.basename)
              # document path should be relative
              paths << entry.path.relative_path_from(@package_location.path).to_s
            end
          else
            # excepting dot-headed or scenario, scan the directory recursively
            unless /^\./.match(entry.basename) or ScenarioScanner.scenario?(entry)
              paths.concat(scan_documents(entry))
            end
          end
        end
      end

      # Scan annotations from documents.
      def scan_annotations(documents)
        # setup temporary language environment for reading annotations
        env = Lang::Environment.new.setup_new_package("PackageScanner")

        # read documents
        documents.each do |doc|
          location = doc.is_a?(Location::DataLocation) ? doc : @package_location + doc
          Document.load(env, location, nil, nil, nil, doc)
        end

        # get annotations
        annotations = env.package_get(Lang::PackageExpr.new(package_id: env.current_package_id)).annotations
        name = find_package_info(annotations, "PackageName")
        editor = find_package_info(annotations, "Editor")
        tag = find_package_info(annotations, "Tag")
        parents = find_parents(annotations)

        return name, editor, tag, parents
      end

      # Find package information of the annotation type from annotations.
      def find_package_info(annotations, annotation_type)
        annotations.each do |annotation|
          if annotation.annotation_type == annotation_type
            return annotation.pieces.first.value
          end
        end

        return nil
      end

      # Find parents from annotaions.
      def find_parents(annotations)
        annotations.each_with_object([]) do |annotation, parents|
          if annotation.annotation_type == "Parent"
            annotation.pieces.each do |parent|
              name = parent.name
              editor = parent.editor ? parent.editor.value : nil
              tag = parent.tag ? parent.tag.value : nil
              parents << ParentPackageInfo.new(name: name, editor: editor, tag: tag)
            end
          end
        end
      end

      # Scan scenarios recursively. See ScnarioScanner for details of scenario
      # directory.
      def scan_scenarios(location)
        location.entries.each_with_object([]) do |entry, list|
          if entry.directory?
            if ScenarioScanner.scenario?(entry)
              list << entry.path.relative_path_from(@package_location.path).to_s
            else
              list.concat(scan_scenarios(entry))
            end
          end
        end
      end

      # Scan executable files.
      def scan_bins(location)
        if (location + "bin").exist?
          (location + "bin").entries.each_with_object([]) do |entry, list|
            if entry.file?
              list << entry.path.relative_path_from(@package_location.path).to_s
            end
          end
        else
          return []
        end
      end

      # Scan etc files.
      def scan_etcs(location)
        if (location + "etc").exist?
          (location + "etc").entries.each_with_object([]) do |entry, list|
            if entry.file?
              list << entry.path.relative_path_from(@package_location.path).to_s
            end
          end
        else
          return []
        end
      end
    end
  end
end


text:
package org.apache.reef.runtime.common.client.defaults;

import org.apache.reef.annotations.Provided;
import org.apache.reef.annotations.audience.ClientSide;
import org.apache.reef.client.JobMessage;
import org.apache.reef.wake.EventHandler;

import javax.inject.Inject;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Default event handler for job message: Logging it.
 */
@Provided
@ClientSide
public final class DefaultJobMessageHandler implements EventHandler<JobMessage> {

  private static final Logger LOG = Logger.getLogger(DefaultJobMessageHandler.class.getName());

  @Inject
  private DefaultJobMessageHandler() {
  }

  @Override
  public void onNext(final JobMessage message) {
    LOG.log(Level.FINE, "Received message: {0}", message);
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Raspberry Pi - webové rozhranie: lib/parser.hpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Raspberry Pi - webové rozhranie

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

 All Classes Files Functions Friends

lib

parser.hpp

Go to the documentation of this file.

    1

    9 #ifndef PARSER

   10 #define PARSER

   11

   12 #include "lexer.hpp"

   13 #include "array.hpp"

   14 #include "tree.hpp"

   15

   16 class CParser

   17 {

   18     public:

   26             CParser( const char *file, const CArray *data );

   27             ~CParser();

   34         CTree* execParser();

   41         char* getError();

   42     private:

   49         void saveError( const char *x );

   50

   55         CTree* Start();

   56

   68         CVar* ForRange( int *first, int *last );

   69

   76         int   Number();

   77

   84         CVar* Array();

   85

   93         void ArrayType( char **id, CVar::IdentType *type );

   94

  105         char* comparsion( CLexer::SymbolType x, bool getNext );

  106

  113         CTree* Else();

  114

  121         CTree* Expression();

  122

  129         CTree* Opr1();

  130

  137         CTree* Opr2();

  138

  145         CTree* Opd();

  146

  153         CTree* Opr1_( CTree *op );

  154

  161         CTree* Opr2_( CTree *op );

  162

  169         CTree* Opr3_( CTree *op );

  170         //==========================

  171         CTree *m_main;

  172         //? struct tree *block

  173         const CArray        *m_data;

  174         CLexer              *m_lexer;

  175         char                *m_error;

  176 };

  177

  178 #endif

tree.hpp

class represents syntactic structure of template file

CParser::execParser

CTree * execParser()

Method start parsing.

Definition: parser.cpp:31

CParser

Definition: parser.hpp:16

lexer.hpp

lexer

CTree

Main virtual class.

Definition: tree.hpp:18

CArray

Definition: array.hpp:16

array.hpp

infinite associative array

CVar

Variable node class, print one value from data Array from View, indexed by string or variable...

Definition: tree.hpp:144

CLexer

Lexer class.

Definition: lexer.hpp:22

CParser::getError

char * getError()

Method to get error, that occurred during parsing.

Definition: parser.cpp:64

CParser::CParser

CParser(const char *file, const CArray *data)

Constructor.

Definition: parser.cpp:18

<address class="footer">
Generated on Sun Dec 7 2014 19:00:11 for Raspberry Pi - webové rozhranie by

 1.8.6
</address>


text:
package org.apache.flink.streaming.api.operators.co;

import org.apache.flink.api.common.typeutils.TypeSerializerSnapshotMigrationTestBase;
import org.apache.flink.api.common.typeutils.base.StringSerializer;
import org.apache.flink.streaming.api.operators.co.IntervalJoinOperator.BufferEntry;
import org.apache.flink.streaming.api.operators.co.IntervalJoinOperator.BufferEntrySerializer;
import org.apache.flink.streaming.api.operators.co.IntervalJoinOperator.BufferEntrySerializerSnapshot;
import org.apache.flink.testutils.migration.MigrationVersion;

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Collection;

/**
 * State migration tests for {@link BufferEntrySerializer}.
 */
@RunWith(Parameterized.class)
public class BufferEntrySerializerMigrationTest extends TypeSerializerSnapshotMigrationTestBase<BufferEntry<String>> {

	public BufferEntrySerializerMigrationTest(TestSpecification<BufferEntry<String>> testSpecification) {
		super(testSpecification);
	}

	@SuppressWarnings("unchecked")
	@Parameterized.Parameters(name = "Test Specification = {0}")
	public static Collection<TestSpecification<?>> testSpecifications() {

		final TestSpecifications testSpecifications = new TestSpecifications(MigrationVersion.v1_6, MigrationVersion.v1_7);

		testSpecifications.add(
			"buffer-entry-serializer",
			BufferEntrySerializer.class,
			BufferEntrySerializerSnapshot.class,
			() -> new BufferEntrySerializer<>(StringSerializer.INSTANCE));

		return testSpecifications.get();
	}
}


text:
package org.lable.lapin.maven;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;

import static org.apache.maven.plugins.annotations.LifecyclePhase.POST_INTEGRATION_TEST;
import static org.apache.maven.plugins.annotations.LifecyclePhase.PRE_INTEGRATION_TEST;

@Mojo(name = "stop-local-hbase", defaultPhase = POST_INTEGRATION_TEST)
public class StopHbaseMojo extends AbstractHbaseMojo {
    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("Stopping local Hbase server.");

        LocalHbaseManager localHbaseManager =
                (LocalHbaseManager) session.getPluginContext(plugin, project).get("hbaseManager");

        localHbaseManager.stop();

        getLog().info("Local Hbase server stopped.");
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:orientation="vertical">

            <TextView
                android:id="@+id/testitem"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="5dp"
                android:textSize="@dimen/size_little"
                android:textStyle="bold" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:gravity="center"
                android:orientation="horizontal"
                android:padding="5dp"
                android:weightSum="3">

                <ImageView
                    android:id="@+id/testimg"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1.5" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:gravity="center"
                android:orientation="horizontal"
                android:weightSum="6">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="阈值:"
                    android:textSize="16sp" />

                <com.okq.generalfoodsafe.View.myEdittext
                    android:id="@+id/threshold"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@drawable/testmsgedit_selector"
                    android:gravity="center"
                    android:inputType="number"
                    android:padding="3dp"
                    android:singleLine="true"
                    android:text="100"
                    android:textSize="16sp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="horizontal"
                android:padding="3dp"
                android:weightSum="7">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="5"
                    android:gravity="center"
                    android:orientation="horizontal">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="拍照进度:"
                        android:textSize="16sp" />

                    <ProgressBar
                        android:id="@+id/testprogress"
                        style="@android:style/Widget.ProgressBar.Horizontal"
                        android:layout_width="0dp"
                        android:layout_height="3dp"
                        android:layout_weight="1"
                        android:max="100"
                        android:progressDrawable="@drawable/progressbar_horizontal"
                        android:secondaryProgress="100" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:gravity="center"
                android:orientation="horizontal"
                android:weightSum="8">

                <TextView
                    android:id="@+id/paramset"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.5"
                    android:background="@drawable/btn_bg_selector"
                    android:gravity="center"
                    android:paddingBottom="3dp"
                    android:paddingTop="3dp"
                    android:text="@string/param_set"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/size_little" />

                <View
                    style="@style/viewstyle_weight1"
                    android:layout_weight="0.3" />

                <TextView
                    android:id="@+id/takephoto"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.5"
                    android:background="@drawable/btn_bg_selector"
                    android:gravity="center"
                    android:paddingBottom="3dp"
                    android:paddingTop="3dp"
                    android:text="@string/take_photo"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/size_little" />

                <View
                    style="@style/viewstyle_weight1"
                    android:layout_weight="0.3" />

                <TextView
                    android:id="@+id/calculate"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.5"
                    android:background="@drawable/btn_bg_selector"
                    android:gravity="center"
                    android:paddingBottom="3dp"
                    android:paddingTop="3dp"
                    android:text="计算"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/size_little" />

                <View
                    style="@style/viewstyle_weight1"
                    android:layout_weight="0.3" />

                <TextView
                    android:id="@+id/nextstep"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.5"
                    android:background="@drawable/btn_bg_selector"
                    android:gravity="center"
                    android:paddingBottom="3dp"
                    android:paddingTop="3dp"
                    android:text="@string/nextstep"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/size_little" />
            </LinearLayout>
        </LinearLayout>

        <com.okq.generalfoodsafe.View.DashedLine
            android:layout_width="1dp"
            android:layout_height="match_parent" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/img_notice" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:text="提示"
                    android:textSize="26sp"
                    android:textStyle="bold" />
            </LinearLayout>

            <ScrollView
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:overScrollMode="never"
                android:scrollbars="none">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="5dp"
                        android:text="@string/thinlayer_sample_notice1"
                        android:textSize="@dimen/size_little" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="5dp"
                        android:text="@string/thinlayer_sample_notice2"
                        android:textSize="@dimen/size_little" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="5dp"
                        android:text="@string/thinlayer_sample_notice3"
                        android:textSize="@dimen/size_little" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="5dp"
                        android:text="@string/thinlayer_sample_notice4"
                        android:textSize="@dimen/size_little" />
                </LinearLayout>
            </ScrollView>
        </LinearLayout>
    </LinearLayout>

    <com.okq.generalfoodsafe.View.DashedLineHor
        android:layout_width="match_parent"
        android:layout_height="1dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1.3"
        android:orientation="vertical">

        <include layout="@layout/layout_testmsg" />
    </LinearLayout>
</LinearLayout>


text:
package me.fornever.checktimer

import java.time.Duration
import javafx.animation.{KeyFrame, Timeline}
import javafx.event.{ActionEvent, EventHandler}

import me.fornever.checktimer.dto.TrackDto

import scalafx.animation.Animation
import scalafx.beans.binding.{Bindings, StringBinding}
import scalafx.beans.property.ObjectProperty

class ApplicationModel(outFileName: Option[String] = None) {

  val currentTrack = new ObjectProperty[Track]
  val currentTime = new ObjectProperty[Duration]

  val currentProjectInfo: StringBinding = Bindings.createStringBinding(() => {
    Option(currentTrack.value) map (t => s"${t.project} / ${t.activity}") getOrElse ""
  }, currentTrack)

  val currentTimeString: StringBinding = Bindings.createStringBinding(() => {
    Option(currentTime.value) map DateTimeUtils.toString getOrElse ""
  }, currentTime)

  private val timeline = new Timeline(
    new KeyFrame(javafx.util.Duration.seconds(1.0), new EventHandler[ActionEvent] {
      override def handle(event: ActionEvent): Unit = {
        Option(currentTrack.value) foreach (track => track.duration foreach (d => currentTime.value = d))
      }
    }))
  timeline.setCycleCount(Animation.INDEFINITE)

  def start(project: String, activity: String): Unit = {
    println(s"Starting project $project / $activity")
    currentTrack.value = Track(project, activity).start()
    currentTime.value = Duration.ZERO
    timeline.play()
  }

  def stop(): Unit = {
    println("Stopping project")
    timeline.stop()
    Option(currentTrack.value) foreach { track =>
      val trackDuration = track.duration()

      currentTrack.value = null
      currentTime.value = null

      (track.startDateTime, trackDuration) match {
        case (Some(startDateTime), Some(duration)) =>
          val dto = TrackDto(startDateTime, duration, track.project, track.activity)
          saveTime(dto)
        case _ =>
      }
    }
  }

  private def saveTime(track: TrackDto): Unit = {
    outFileName foreach { fileName =>
      println(s"Saving data to $fileName")
      CsvFile.append(fileName, track)
    }
  }
}


text:
/**
 * Author: Ken
 * Date: 24/09/2013
 * Time: 22:16
 */
/*global define*/
define(['../javascripts/constant.js',
    '../javascripts/loader.js',
    '../javascripts/helper.js',
    '../javascripts/dom.js',
    '../javascripts/notification.js'], function (CONSTANT, Loader, H, Dom, Notification) {
    "use strict";
    function Contacts() {
        var self = this,
            aDom = new Dom();

        /**
         * remove the current contact
         * @param event a DOM event such as a click
         * NOTE: this event should contain a current target which holds the contact ID
         */
        function removeCurrentContact(event) {
            var docId,
                contactItem,
                aLoader = new Loader(),
                aNotification = new Notification();
            function successCB(res) {
                aNotification.notificationSuccess();
                contactItem.parentNode.remove();
            }
            function errorCB(err) {
                aNotification.notificationFail();
            }
            if (event.currentTarget &&
                    event.currentTarget.parentNode &&
                    event.currentTarget.parentNode.previousSibling) {
                contactItem = event.currentTarget.parentNode.previousSibling;
                docId = contactItem.dataset.docId;
                aLoader.requestURL('DELETE', '/contact/' + docId + '/delete', null, successCB, errorCB);
            }
        }

        /**
         * sanitise basic input, will be further check on the server side
         * @param input
         * @returns {XML|string}
         */
        function basicSanitise(input) {
            return input.replace(/&/g, '& ').replace(/</g, '< ').replace(/"/g, '" ');
        }

        /**
         * init close button that effect the close button effecting area
         */
        self.initCloseButton = function () {
            var i,
                closeButton = document.getElementsByClassName('close-button'),
                contentBodyDetail = document.getElementsByClassName('close-button-effect-area'),
                contentBodyShowAll = document.getElementsByClassName('content-body-show-all');
            function CloseButtonEffectAreaHelper() {
                aDom.hideCloseButtonEffectArea(contentBodyDetail);
                aDom.showContactList(contentBodyShowAll);
            }
            for (i = 0; i < closeButton.length; i = i + 1) {
                if (closeButton && closeButton[i]) {
                    closeButton[i].addEventListener('click', CloseButtonEffectAreaHelper);
                }
            }
        };

        /**
         * init the done button whose job is to upload new contact
         * @param successCallback (body)
         * @param errorCallback (error)
         */
        self.initDoneButton = function (successCallback, errorCallback) {
            var addNewContactForm = document.getElementById('add-new-contact-form'),
                submitNewContact = document.getElementById('submitNewContact');
            if (addNewContactForm) {
                addNewContactForm.addEventListener('submit', function (event) {
                    self.submitNewContact(event, successCallback, errorCallback);
                });
                submitNewContact.disabled = true;
            }
        };

        /**
         *  init update button whose job is to update the contact
         * @param successCallback
         * @param errorCallback
         */
        self.initUpdateButton = function (successCallback, errorCallback) {
            var editContactForm = document.getElementById('edit-contact-form'),
                submitEditedContact = document.getElementById('submitEditedContact');
            if (editContactForm) {
                editContactForm.addEventListener('submit', function (event) {
                    self.updateCurrentContact(event, successCallback, errorCallback);
                    // disabled the button
                    submitEditedContact.disabled = true;
                });
            }
        };
        /**
         * retrieve all contacts from database
         * @param successCallback (response)
         * @param errorCallback (error)
         */
        self.getAllContacts = function (successCallback, errorCallback) {
            var aLoader = new Loader();
            aLoader.requestURL('GET', CONSTANT.API.ALL_CONTACTS, null, successCallback, errorCallback);
        };
        /**
         * populate contacts info on the DOM tree
         * @param contacts {Array} an array of contact objects
         * @param eventCallback (event)
         * @returns {boolean}
         */
        self.populate = function (contacts, eventCallback) {
            var aDom = new Dom(),
                contactItemWrap,
                contactItem,
                removeContactButtons,
                i,
                contactList;

            for (i = 0; i < contacts.length; i = i + 1) {
                try {
                    contactList = document.getElementById('contactList');
                    contactItemWrap = aDom.getContactItemWrap(contacts[i]);
                    contactItem = contactItemWrap.firstChild;
                    contactList.appendChild(contactItemWrap);

                    if (eventCallback && typeof eventCallback === 'function') {
                        contactItem.addEventListener('click', eventCallback);
                    }

                    // append to session storage
                    if (Storage === undefined) {
                        throw CONSTANT.ERROR.HTML5.STORAGE;
                    } else {
                        sessionStorage.setItem(contacts[i].id, JSON.stringify(contacts[i].value));
                    }
                } catch (e) {
                    console.log(e);
                    return false;
                }
            }
            removeContactButtons = document.getElementsByClassName('remove-contact-button');
            for (i = 0; i < removeContactButtons.length; i = i + 1) {
                removeContactButtons[i].addEventListener('click', removeCurrentContact);
            }
            return true;
        };
        /**
         * An event callback that reads contact detail from session storage and,
         * show the detail in the dom tree
         * @param event {Event} dom event such as click
         * @returns {boolean} return false in case of error
         */
        self.showContactDetail = function (event) {
            var i,
                aDom = new Dom(),
                contactID,
                contactDetail = {},
                contentBodyShowAll,
                contentBodyDetail,
                lastName,
                firstName,
                companyName,
                // use for phone
                contactDetailPhoneGroup,
                contactDetailPhoneItem,
                contactDetailFieldName,
                contactDetailPhoneNumber,
                newContactDetailPhoneItem,
                // use for email
                contactDetailEmailGroup,
                contactDetailEmailItem,
                contactDetailEmail,
                newContactDetailEmailItem,
                note;
            event.preventDefault();
            try {
                contactID = event.currentTarget.dataset.docId;
                // if the session storage is supported
                if (Storage === undefined) {
                    throw CONSTANT.ERROR.HTML5.STORAGE;
                    // FUTURE: query backend server and ask for data
                } else {
                    contactDetail = JSON.parse(sessionStorage.getItem(contactID));
                    contentBodyDetail = document.getElementsByClassName('content-body-detail');
                    contentBodyShowAll = document.getElementsByClassName('content-body-show-all');

                    lastName = document.getElementsByClassName('contact-detail-last-name');
                    lastName[0].innerHTML = contactDetail.last_name;

                    firstName = document.getElementsByClassName('contact-detail-first-name');
                    firstName[0].innerHTML = contactDetail.first_name;

                    companyName = document.getElementsByClassName('contact-detail-company');
                    companyName[0].innerHTML = contactDetail.company;

                    // create phone
                    contactDetailPhoneItem = document.getElementsByClassName('contact-detail-phone-item');
                    contactDetailPhoneGroup = document.getElementById('contact-detail-phone-group');
                    if (contactDetail && contactDetail.work_phone && H.is_array(contactDetail.work_phone)) {
                        for (i = 0; i < contactDetail.work_phone.length; i = i + 1) {
                            if (contactDetailPhoneItem[i]) {
                                contactDetailFieldName = document.getElementsByClassName('contact-detail-phone-field-name');
                                contactDetailFieldName[i].innerHTML = CONSTANT.NAME.PHONE;
                                contactDetailPhoneNumber = document.getElementsByClassName('contact-detail-phone');
                                contactDetailPhoneNumber[i].innerHTML = contactDetail.work_phone[i] || '';
                            } else {
                                newContactDetailPhoneItem = aDom.getNewXItem(CONSTANT.NAME.PHONE, CONSTANT.NAME.PHONE, contactDetail.work_phone[i]);
                                contactDetailPhoneGroup.appendChild(newContactDetailPhoneItem);
                            }
                        }
                    }

                    // create email
                    contactDetailEmailGroup = document.getElementById('contact-detail-email-group');
                    contactDetailEmailItem = document.getElementsByClassName('contact-detail-email-item');

                    if (contactDetail && contactDetail.work_email && H.is_array(contactDetail.work_email)) {
                        for (i = 0; i < contactDetail.work_email.length; i = i + 1) {
                            if (contactDetailEmailItem[i]) {
                                contactDetailFieldName = document.getElementsByClassName('contact-detail-email-field-name');
                                contactDetailFieldName[i].innerHTML = CONSTANT.NAME.EMAIL;
                                contactDetailEmail = document.getElementsByClassName('contact-detail-email');
                                contactDetailEmail[i].innerHTML = contactDetail.work_email[i] || '';
                            } else {
                                newContactDetailEmailItem = aDom.getNewXItem(CONSTANT.NAME.EMAIL, CONSTANT.NAME.EMAIL, contactDetail.work_email[i]);
                                contactDetailEmailGroup.appendChild(newContactDetailEmailItem);
                            }
                        }
                    }

                    note  = document.getElementsByClassName('contact-detail-note');
                    note[0].innerHTML = contactDetail.note;

                    aDom.showCloseButtonEffectArea(contentBodyDetail);
                    aDom.hideContactList(contentBodyShowAll);
                }
            } catch (e) {
                console.log(e);
                return false;
            }
            return true;
        };
        /**
         * An event callback that adds new contact into the database
         * @param event a dom event such as click
         * @param successCallback (response)
         * @param errorCallback (error)
         * @returns {*}
         */
        self.submitNewContact = function (event, successCallback, errorCallback) {
            var data = {},
                aLoader = new Loader();

            event.preventDefault();
            data.lastName = basicSanitise(document.getElementById('newLastName').value);
            data.firstName = basicSanitise(document.getElementById('newFirstName').value);
            data.company = basicSanitise(document.getElementById('newCompany').value);
            data.phone = basicSanitise(document.getElementById('newPhone').value);
            data.email = basicSanitise(document.getElementById('newEmail').value);
            data.note = basicSanitise(document.getElementById('newNote').value);
            function successCB(body) {
                if (successCallback && typeof successCallback === 'function') {
                    successCallback(body);
                }
            }
            function errorCB(err) {
                if (errorCallback && typeof errorCallback === 'function') {
                    errorCallback(err);
                } else {
                    throw CONSTANT.ERROR.ADD_NEW;
                }
            }
            aLoader.requestURL('post', CONSTANT.API.ADD_NEW, data, successCB, errorCB);
            return self;
        };
        /**
         * An event callback that shows the add new contact form
         * meanwhile, it will enable the 'done' button
         * @param event {Event} a dom event such as click
         * @returns {Contacts} return false in case of an error
         */
        self.displayAddNewContact = function (event) {
            var contentBodyAddNewContact = document.getElementsByClassName('content-body-add-new-contact'),
                contentBodyShowAll = document.getElementsByClassName('content-body-show-all'),
                submitNewContact = document.getElementById('submitNewContact');
            event.preventDefault();
            try {
                if (contentBodyAddNewContact && contentBodyAddNewContact[0]) {
                    contentBodyAddNewContact[0].style.display = 'block';
                    if (contentBodyAddNewContact[0].firstChild) {
                        // the first child is the form
                        contentBodyAddNewContact[0].firstChild.reset();
                    }
                }
                submitNewContact.disabled = false;
                aDom.hideContactList(contentBodyShowAll);
            } catch (e) {
                console.log(e);
                return null;
            }
            return self;
        };
        /**
         * An event callback that fills the contact information
         * into an form, the edit contact form
         * The form is not shown to user yet.
         * @param event {Event} a dom event such as click
         * @param event
         * @returns {Contacts} return false in case of an error
         */
        self.showEditContactDetail = function (event) {
            var contactID,
                contactDetail = {},
                editContactForm,
                lastNameNode,
                firstNameNode,
                companyNode,
                phoneNode,
                emailNode,
                noteNode;

            try {
                contactID = event.currentTarget.dataset.docId;
                editContactForm = document.getElementById('edit-contact-form');
                lastNameNode = document.getElementById('editedLastName');
                firstNameNode = document.getElementById('editedFirstName');
                companyNode = document.getElementById('editedCompany');
                phoneNode = document.getElementById('editedPhone');
                emailNode = document.getElementById('editedEmail');
                noteNode = document.getElementById('editedNote');

                editContactForm.reset();

                if (contactID) {
                    contactDetail = JSON.parse(sessionStorage.getItem(contactID));
                    lastNameNode.value = contactDetail.first_name;
                    firstNameNode.value = contactDetail.last_name;
                    companyNode.value = contactDetail.company;
                    phoneNode.value = contactDetail.work_phone;
                    emailNode.value = contactDetail.work_email;
                    noteNode.value = contactDetail.note;
                } else {
                    throw CONSTANT.ERROR.CONTACT_ID_NOT_FOUND;
                }
            } catch (e) {
                console.log(e);
                return null;
            }
            return self;
        };
        /**
         * it shows the edit form to the user
         * meanwhile release the 'update' button
         * @returns {Contacts} return false in case of an error
         */
        self.displayEditContact = function () {
            var editContactDetail,
                submitEditedContact;
            try {
                editContactDetail = document.getElementsByClassName('content-body-edit-contact');
                submitEditedContact = document.getElementById('submitEditedContact');
                if (editContactDetail && editContactDetail[0] && editContactDetail[0].style) {
                    editContactDetail[0].style.display = 'block';
                    submitEditedContact.disabled = false;
                } else {
                    throw CONSTANT.ERROR.DOM;
                }
            } catch (e) {
                console.log(e);
                return null;
            }
            return self;
        };
        /**
         * update contact information to the database
         * @param event {Event} a dom event such as click
         * @param successCallback (response)
         * @param errorCallback (error)
         * @returns {Contacts}
         */
        self.updateCurrentContact = function (event, successCallback, errorCallback) {
            var data = {},
                aLoader = new Loader();
            event.preventDefault();
            function successCB(body) {
                if (successCallback && typeof successCallback === 'function') {
                    successCallback(body);
                }
            }
            function errorCB(err) {
                if (errorCallback && typeof errorCallback === 'function') {
                    errorCallback(err);
                } else {
                    throw CONSTANT.ERROR.EDIT_CONTACT;
                }
            }
            try {
                data.contactId = basicSanitise(document.getElementById('editContact').dataset.docId);
                data.lastName = basicSanitise(document.getElementById('editedLastName').value);
                data.firstName = basicSanitise(document.getElementById('editedFirstName').value);
                data.company = basicSanitise(document.getElementById('editedCompany').value);
                data.phone = basicSanitise(document.getElementById('editedPhone').value);
                data.email = basicSanitise(document.getElementById('editedEmail').value);
                data.note = basicSanitise(document.getElementById('editedNote').value);

                aLoader.requestURL('put', CONSTANT.API.EDIT, data, successCB, errorCB);
            } catch (e) {
                console.log(e);
                return null;
            }
            return self;
        };
    }
    return Contacts;
});


text:
function AddFMODProjectDlg::show( %this )
{
   if( $platform $= "macos" )
   {
      %fmodex = "libfmodex.dylib";
      %fmodevent = "libfmodevent.dylib";
   }
   else
   {
      %fmodex = "fmodex.dll";
      %fmodevent = "fmod_event.dll";
   }

   // Make sure we have FMOD running.

   if( getField( sfxGetDeviceInfo(), $SFX::DEVICE_INFO_PROVIDER ) !$= "FMOD" )
   {
      MessageBoxOK( "Error",
         "You do not currently have FMOD selected as your sound system." NL
         "" NL
         "To install FMOD, place the FMOD DLLs (" @ %fmodex @ " and " @ %fmodevent @ ")" SPC
         "in your game/ folder alongside your game executable" SPC
         "and restart Torque." NL
         "" NL
         "To select FMOD as your sound system, choose it as the sound provider in" SPC
         "the audio tab of the Game Options dialog."
      );

      return;
   }

   // Make sure we have the FMOD Event DLL loaded.

   %deviceCaps = getField( sfxGetDeviceInfo(), $SFX::DEVICE_INFO_CAPS );
   if( !( %deviceCaps & $SFX::DEVICE_CAPS_FMODDESIGNER ) )
   {
      MessageBoxOK( "Error",
         "You do not have the requisite FMOD Event DLL in place." NL
         "" NL
         "Please copy " @ %fmodevent @ " into your game/ folder and restart Torque."
      );
      return;
   }

   // Show it.

   Canvas.pushDialog( %this, 0, true );
}

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

function AddFMODProjectDlg::onWake( %this )
{
   %this.persistenceMgr = new PersistenceManager();
}

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

function AddFMODProjectDlg::onSleep( %this )
{
   %this.persistenceMgr.delete();
}

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

function AddFMODProjectDlg::onCancel( %this )
{
   Canvas.popDialog( %this );
}

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

function AddFMODProjectDlg::onOK( %this )
{
   %objName    = %this-->projectNameField.getText();
   %fileName   = %this-->fileNameField.getText();
   %mediaPath  = %this-->mediaPathField.getText();

   // Make sure the object name is valid.
   if( !Editor::validateObjectName( %objName, true ))
      return;

   // Make sure the .fev file exists.

   if( %fileName $= "" )
   {
      MessageBoxOK( "Error",
         "Please enter a project file name."
      );
      return;
   }
   if( !isFile( %fileName ) )
   {
      MessageBoxOK( "Error",
         "'" @ %fileName @ "' is not a valid file."
      );
      return;
   }

   // Make sure the media path exists.

   if( !isDirectory( %mediaPath ) )
   {
      MessageBoxOK( "Error",
         "'" @ %mediaPath @ "' is not a valid directory."
      );
      return;
   }

   // If an event script exists from a previous instantiation,
   // delete it first.

   %eventFileName = %fileName @ ".cs";
   if( isFile( %eventFileName ) )
      fileDelete( %eventFileName );

   // Create the FMOD project object.

   pushInstantGroup();
   eval( "new SFXFMODProject( " @ %objName @ ") {" NL
      "fileName = \"" @ %fileName @ "\";" NL
      "mediaPath = \"" @ %mediaPath @ "\";" NL
   "};" );
   popInstantGroup();

   if( !isObject( %objName ) )
   {
      MessageBoxOK( "Error",
         "Failed to create the object.  Please take a look at the log for details."
      );
      return;
   }
   else
   {
      // Save the object.

      %objName.setFileName( "scripts/client/audioData.cs" );
      %this.persistenceMgr.setDirty( %objName );
      %this.persistenceMgr.saveDirty();
   }

   Canvas.popDialog( %this );

   // Trigger a reinit on the datablock editor, just in case.

   if( isObject( DatablockEditorPlugin ) )
      DatablockEditorPlugin.populateTrees();
}

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

function AddFMODProjectDlg::onSelectFile( %this )
{
   if( $pref::WorldEditor::AddFMODProjectDlg::lastPath $= "" )
      $pref::WorldEditor::AddFMODProjectDlg::lastPath = getMainDotCsDir();

   %dlg = new OpenFileDialog()
   {
      Title       = "Select Compiled FMOD Designer Event File...";
      Filters     = "Compiled Event Files (*.fev)|*.fev|All Files (*.*)|*.*|";
      DefaultPath = $pref::WorldEditor::AddFMODProjectDlg::lastPath;
      DefaultFile = fileName( %this-->fileNameField.getText() );
      MustExit    = true;
      ChangePath  = false;
   };

   %ret = %dlg.execute();
   if( %ret )
   {
      %file = %dlg.fileName;
      $pref::WorldEditor::AddFMODProjectDlg::lastPath = filePath( %file );
   }

   %dlg.delete();

   if( !%ret )
      return;

   %file = makeRelativePath( %file, getMainDotCsDir() );
   %this-->fileNameField.setText( %file );

   if( %this-->projectNameField.getText() $= "" )
   {
      %projectName = "fmod" @ fileBase( %file );
      if( isValidObjectName( %projectName ) )
         %this-->projectNameField.setText( %projectName );
   }
}

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

function AddFMODProjectDlg::onSelectMediaPath( %this )
{
   %defaultPath = %this-->mediaPathField.getText();
   if( %defaultPath $= "" )
   {
      %defaultPath = filePath( %this-->fileNameField.getText() );
      if( %defaultPath $= "" )
         %defaultPath = getMainDotCsDir();
      else
         %defaultPath = makeFullPath( %defaultPath );
   }

   %dlg = new OpenFolderDialog()
   {
      Title       = "Select Media Path...";
      DefaultPath = %defaultPath;
      MustExit    = true;
      ChangePath  = false;
   };

   %ret = %dlg.execute();
   if( %ret )
      %file = %dlg.fileName;

   %dlg.delete();

   if( !%ret )
      return;

   %file = makeRelativePath( %file, getMainDotCsDir() );
   %this-->mediaPathField.setText( %file );
}