text:
package control;

import data.*;
import gui.centerarea.CameraShotBlock;
import gui.centerarea.DirectorShotBlock;
import gui.centerarea.TimetableBlock;
import gui.headerarea.DirectorDetailView;
import gui.headerarea.DoubleTextField;
import gui.root.RootHeaderArea;
import gui.root.RootPane;
import gui.styling.StyledCheckbox;
import gui.styling.StyledMenuButton;
import gui.styling.StyledTextfield;
import javafx.beans.InvalidationListener;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.testfx.framework.junit.ApplicationTest;

import java.util.*;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

/**
 * Created by Bart on 12/05/2016.
 */
public class DetailViewControllerTest extends ApplicationTest {

    private ControllerManager manager;
    private DirectorDetailView detailView;
    private DetailViewController detailViewController;
    private DoubleTextField beginCountField, endCountField, paddingBeforeField, paddingAfterField;

    private Pane pane;

    @Before
    public void initialize() {
        manager = Mockito.mock(ControllerManager.class);
        RootPane rootPane = Mockito.mock(RootPane.class);
        RootHeaderArea rootHeaderArea = Mockito.mock(RootHeaderArea.class);

        detailView = Mockito.mock(DirectorDetailView.class);
        when(manager.getRootPane()).thenReturn(rootPane);
        when(rootPane.getRootHeaderArea()).thenReturn(rootHeaderArea);
        when(rootHeaderArea.getDetailView()).thenReturn(detailView);

        // Add necessary fields
        beginCountField = new DoubleTextField("0");
        endCountField = new DoubleTextField("0");
        paddingBeforeField = new DoubleTextField("0");
        paddingAfterField = new DoubleTextField("0");

        when(detailView.getDescriptionField()).thenReturn(new StyledTextfield());
        when(detailView.getNameField()).thenReturn(new StyledTextfield());
        when(detailView.getBeginCountField()).thenReturn(beginCountField);
        when(detailView.getEndCountField()).thenReturn(endCountField);
        when(detailView.getPaddingBeforeField()).thenReturn(paddingBeforeField);
        when(detailView.getPaddingAfterField()).thenReturn(paddingAfterField);
        when(detailView.getEndCountField()).thenReturn(endCountField);
        when(detailView.getEndCountField()).thenReturn(endCountField);
        when(detailView.getSelectCamerasButton()).thenReturn(new StyledMenuButton());

        detailViewController = spy(new DetailViewController(manager));
    }

    @Test
    public void camerasDropdownChangeListenerRemoved() {
        // Setup mocks
        ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class);
        DirectorShot shot = Mockito.mock(DirectorShot.class);
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(0));
        ScriptingProject project = Mockito.mock(ScriptingProject.class);
        TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class);
        TimelineController timelineController = Mockito.mock(TimelineController.class);
        CameraShot cameraShot1 = Mockito.mock(CameraShot.class);
        CameraShot cameraShot2 = Mockito.mock(CameraShot.class);
        Set<CameraShot> shotList = new HashSet<>(Arrays.asList(cameraShot1, cameraShot2));
        CameraShotBlock cameraShotBlock1 = Mockito.mock(CameraShotBlock.class);
        CameraShotBlock cameraShotBlock2 = Mockito.mock(CameraShotBlock.class);
        DirectorTimelineController directorTimelineController = Mockito.mock(DirectorTimelineController.class);

        // Mock all the methods
        when(manager.getActiveShotBlock()).thenReturn(shotBlock);
        when(manager.getScriptingProject()).thenReturn(project);
        when(shotBlock.getShot()).thenReturn(shot);
        when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock);
        when(change.getRemoved()).thenReturn(changeList);
        when(manager.getTimelineControl()).thenReturn(timelineController);
        when(manager.getDirectorTimelineControl()).thenReturn(directorTimelineController);
        when(shot.getCameraShots()).thenReturn(shotList);
        when(timelineController.getShotBlockForShot(cameraShot1)).thenReturn(cameraShotBlock1);
        when(timelineController.getShotBlockForShot(cameraShot2)).thenReturn(cameraShotBlock2);
        when(cameraShotBlock1.getTimetableNumber()).thenReturn(100);

        // Call method under testing
        detailViewController.camerasDropdownChangeListener(change);

        // verify
        Mockito.verify(shot, times(1)).getTimelineIndices();
        Mockito.verify(shot, times(2)).getCameraShots();
        assertEquals(1, shotList.size());
        assertTrue(shotList.contains(cameraShot1));
        assertFalse(shotList.contains(cameraShot2));
    }

    @Test
    public void camerasDropdownChangeListenerRemoved2() {
        // Setup mocks
        ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class);
        DirectorShot shot = Mockito.mock(DirectorShot.class);
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(5));
        ScriptingProject project = Mockito.mock(ScriptingProject.class);
        TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class);
        TimelineController timelineController = Mockito.mock(TimelineController.class);
        CameraShot cameraShot1 = Mockito.mock(CameraShot.class);
        Set<CameraShot> shotList = new HashSet<>(Arrays.asList(cameraShot1));
        CameraShotBlock cameraShotBlock1 = Mockito.mock(CameraShotBlock.class);
        DirectorTimelineController directorTimelineController = Mockito.mock(DirectorTimelineController.class);

        // Mock all the methods
        when(manager.getActiveShotBlock()).thenReturn(shotBlock);
        when(manager.getScriptingProject()).thenReturn(project);
        when(shotBlock.getShot()).thenReturn(shot);
        when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock);
        when(change.getRemoved()).thenReturn(changeList);
        when(manager.getTimelineControl()).thenReturn(timelineController);
        when(manager.getDirectorTimelineControl()).thenReturn(directorTimelineController);
        when(shot.getCameraShots()).thenReturn(shotList);
        when(timelineController.getShotBlockForShot(cameraShot1)).thenReturn(cameraShotBlock1);
        when(cameraShotBlock1.getTimetableNumber()).thenReturn(100);

        // Call method under testing
        detailViewController.camerasDropdownChangeListener(change);

        // verify
        Mockito.verify(shot, times(1)).getTimelineIndices();
        Mockito.verify(shot, times(2)).getCameraShots();
        assertEquals(1, shotList.size());
        assertTrue(shotList.contains(cameraShot1));
    }

    @Test
    public void camerasDropdownChangeListenerAdded() {
        // Setup mocks
        ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class);
        DirectorShot shot = Mockito.mock(DirectorShot.class);
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(0));
        ScriptingProject project = Mockito.mock(ScriptingProject.class);
        TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class);
        TimelineController timelineController = Mockito.mock(TimelineController.class);
        ArrayList<CameraTimeline> timelines = new ArrayList<>();
        CameraTimeline timeline = Mockito.mock(CameraTimeline.class);
        timelines.add(timeline);
        DirectorTimelineController directorTimelineController = Mockito.mock(DirectorTimelineController.class);

        // Mock all the methods
        when(manager.getActiveShotBlock()).thenReturn(shotBlock);
        when(manager.getScriptingProject()).thenReturn(project);
        when(shotBlock.getShot()).thenReturn(shot);
        when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock);
        when(change.getAddedSubList()).thenReturn(changeList);
        when(manager.getTimelineControl()).thenReturn(timelineController);
        when(manager.getDirectorTimelineControl()).thenReturn(directorTimelineController);
        when(change.wasAdded()).thenReturn(true);
        when(project.getCameraTimelines()).thenReturn(timelines);

        // Call method under testing
        detailViewController.camerasDropdownChangeListener(change);

        // verify
        Mockito.verify(timeline, times(1)).addShot(anyObject());
        Mockito.verify(manager, times(1)).setActiveShotBlock(shotBlock);
    }

    @Test
    public void instrumentsDropdownChangeListenerRemoved() {
        // Setup mocks
        ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class);
        DirectorShot shot = Mockito.mock(DirectorShot.class);
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(0));
        ArrayList<Instrument> instrumentList1 = new ArrayList<>(Arrays.asList(new Instrument("name", "description")));
        ArrayList<Instrument> instrumentList2 = new ArrayList<>(Arrays.asList(new Instrument("name", "description")));
        ArrayList<Instrument> instrumentList3 = new ArrayList<>(Arrays.asList(new Instrument("name", "description")));
        ScriptingProject project = Mockito.mock(ScriptingProject.class);
        TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class);

        // Mock all the methods
        when(manager.getActiveShotBlock()).thenReturn(shotBlock);
        when(project.getInstruments()).thenReturn(instrumentList1);
        when(manager.getScriptingProject()).thenReturn(project);
        when(shotBlock.getInstruments()).thenReturn(instrumentList2);
        when(shotBlock.getShot()).thenReturn(shot);
        when(shot.getInstruments()).thenReturn(instrumentList3);
        when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock);
        when(change.getRemoved()).thenReturn(changeList);

        // Call method under testing
        detailViewController.instrumentsDropdownChangeListener(change);

        // verify
        assertFalse(instrumentList1.isEmpty());
        assertTrue(instrumentList2.isEmpty());
        assertTrue(instrumentList3.isEmpty());
        Mockito.verify(shotBlock, times(1)).recompute();
        Mockito.verify(timetableBlock, times(1)).removeInstrument(anyObject());
    }

    @Test
    public void instrumentsDropdownChangeListenerAdded() {
        // Setup mocks
        ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class);
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(0));
        ArrayList<Instrument> instrumentList1 = new ArrayList<>();
        ArrayList<Instrument> instrumentList2 = new ArrayList<>(Arrays.asList(new Instrument("name", "description")));
        ScriptingProject project = Mockito.mock(ScriptingProject.class);
        TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class);

        // Mock all the methods
        when(manager.getActiveShotBlock()).thenReturn(shotBlock);
        when(project.getInstruments()).thenReturn(instrumentList2);
        when(manager.getScriptingProject()).thenReturn(project);
        when(shotBlock.getInstruments()).thenReturn(instrumentList1);
        when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock);
        when(change.getAddedSubList()).thenReturn(changeList);
        when(change.wasAdded()).thenReturn(true);

        // Call method under testing
        detailViewController.instrumentsDropdownChangeListener(change);

        // verify
        assertEquals(1, instrumentList1.size());
        assertEquals(1, instrumentList1.size());
        Mockito.verify(shotBlock, times(1)).recompute();
        Mockito.verify(timetableBlock, times(1)).addInstrument(anyObject());
    }

    private void setupPaddingUpdateHelperTests(DirectorShot shot, DirectorShotBlock shotBlock, TimelineController timelineController) {
        // Make mocks
        CameraShot cameraShot = Mockito.mock(CameraShot.class);
        CameraShotBlock cameraShotBlock = Mockito.mock(CameraShotBlock.class);

        // Mock all the methods
        when(shotBlock.getShot()).thenReturn(shot);
        when(manager.getActiveShotBlock()).thenReturn(shotBlock);
        when(manager.getTimelineControl()).thenReturn(timelineController);
        when(shot.getCameraShots()).thenReturn(new HashSet<CameraShot>(Arrays.asList(cameraShot)));
        when(shot.getBeginCount()).thenReturn(0.0);
        when(timelineController.getShotBlockForShot(anyObject())).thenReturn(cameraShotBlock);
    }

    @Test
    public void beforePaddingUpdateHelper() {
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        DirectorShot shot = Mockito.mock(DirectorShot.class);
        TimelineController timelineController = Mockito.mock(TimelineController.class);
        setupPaddingUpdateHelperTests(shot, shotBlock, timelineController);

        // Call method under testing
        detailViewController.beforePaddingFocusListener(null, true, false);

        // Verify
        assertEquals(0.0, shot.getFrontShotPadding(), 0);
        assertEquals(0.0, shotBlock.getPaddingBefore(), 0);
        Mockito.verify(timelineController, times(1)).recomputeAllCollisions();
    }

    @Test
    public void beforePaddingUpdateHelperFalse() {
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        DirectorShot shot = Mockito.mock(DirectorShot.class);
        TimelineController timelineController = Mockito.mock(TimelineController.class);
        setupPaddingUpdateHelperTests(shot, shotBlock, timelineController);

        // Call method under testing
        detailViewController.beforePaddingFocusListener(null, false, true);

        // Verify
        assertEquals(0.0, shot.getFrontShotPadding(), 0);
        assertEquals(0.0, shotBlock.getPaddingBefore(), 0);
        Mockito.verify(timelineController, times(0)).recomputeAllCollisions();
    }

    @Test
    public void beforePaddingUpdateHelperNull() {
        TimelineController timelineController = Mockito.mock(TimelineController.class);

        // Call method under testing
        detailViewController.beforePaddingFocusListener(null, true, false);

        // Verify
        Mockito.verify(timelineController, times(0)).recomputeAllCollisions();
    }

    @Test
    public void afterPaddingFocusListener() {
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        DirectorShot shot = Mockito.mock(DirectorShot.class);
        TimelineController timelineController = Mockito.mock(TimelineController.class);
        setupPaddingUpdateHelperTests(shot, shotBlock, timelineController);

        // Call method under testing
        detailViewController.afterPaddingFocusListener(null, true, false);

        // Verify
        assertEquals(0.0, shot.getEndShotPadding(), 0);
        assertEquals(0.0, shotBlock.getPaddingAfter(), 0);
        Mockito.verify(timelineController, times(1)).recomputeAllCollisions();
    }

    @Test
    public void afterPaddingFocusListenerFalse() {
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        DirectorShot shot = Mockito.mock(DirectorShot.class);
        TimelineController timelineController = Mockito.mock(TimelineController.class);
        setupPaddingUpdateHelperTests(shot, shotBlock, timelineController);

        // Call method under testing
        detailViewController.afterPaddingFocusListener(null, false, true);

        // Verify
        Mockito.verify(timelineController, times(0)).recomputeAllCollisions();
    }

    @Test
    public void afterPaddingFocusListenerNull() {
        TimelineController timelineController = Mockito.mock(TimelineController.class);

        // Call method under testing
        detailViewController.afterPaddingFocusListener(null, true, false);

        // Verify
        Mockito.verify(timelineController, times(0)).recomputeAllCollisions();
    }

    @Test
    public void reInitForCameraBlock() {
        StyledMenuButton menuButton = new StyledMenuButton();
        when(detailView.getSelectInstrumentsButton()).thenReturn(menuButton);

        detailViewController.reInitForCameraBlock();

        Mockito.verify(detailView, times(2)).getNameField();
        Mockito.verify(detailView, times(2)).getDescriptionField();
        Mockito.verify(detailView, times(4)).getBeginCountField();
        Mockito.verify(detailView, times(4)).getEndCountField();
    }

    @Test
    public void reInitForDirectorBlock() {
        StyledMenuButton menuButton = new StyledMenuButton();
        when(detailView.getSelectInstrumentsButton()).thenReturn(menuButton);
        detailViewController.reInitForDirectorBlock();

        Mockito.verify(detailView, times(2)).getPaddingBeforeField();
        Mockito.verify(detailView, times(2)).getPaddingAfterField();
    }

    @Test
    public void constructor() {
        assertNotNull(detailViewController);
    }

    @Test
    public void beginCountUpdateHelper() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(manager.getActiveShotBlock()).thenReturn(block);
        when(block.getShot()).thenReturn(shot);

        KeyEvent keyEvent = new KeyEvent(KeyEvent.ANY, "", "", KeyCode.ENTER,
                false, false, false, false);
        detailView.getBeginCountField().getOnKeyPressed().handle(keyEvent);

        verify(block, times(1)).setBeginCount(0);
        verify(shot, times(1)).setBeginCount(0);
    }

    @Test
    public void endCountUpdateHelper() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(manager.getActiveShotBlock()).thenReturn(block);
        when(block.getShot()).thenReturn(shot);

        KeyEvent keyEvent = new KeyEvent(KeyEvent.ANY, "", "", KeyCode.ENTER,
                false, false, false, false);
        detailView.getEndCountField().getOnKeyPressed().handle(keyEvent);

        verify(block, times(1)).setEndCount(0);
        verify(shot, times(1)).setEndCount(0);
    }

    @Test
    public void activeBlockChangedActiveBlockNull() {
        detailViewController.activeBlockChanged();
        verify(detailView, times(1)).resetDetails();
    }

    @Test
    public void beginCountFocusedProperty() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(manager.getActiveShotBlock()).thenReturn(block);
        when(block.getShot()).thenReturn(shot);

        detailViewController.beginCountFocusListener(new ObservableValue<Boolean>() {
            @Override
            public void addListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public Boolean getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, true, false);

        verify(block, times(1)).setBeginCount(0);
        verify(shot, times(1)).setBeginCount(0);
    }

    @Test
    public void beginCountFocusedPropertyNull() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(block.getShot()).thenReturn(shot);

        detailViewController.beginCountFocusListener(new ObservableValue<Boolean>() {
            @Override
            public void addListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public Boolean getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, true, false);

        verify(block, times(0)).setBeginCount(0);
        verify(shot, times(0)).setBeginCount(0);
    }

    @Test
    public void beginCountFocusedPropertyFalse() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(manager.getActiveShotBlock()).thenReturn(block);
        when(block.getShot()).thenReturn(shot);

        detailViewController.beginCountFocusListener(new ObservableValue<Boolean>() {
            @Override
            public void addListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public Boolean getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, false, true);

        verify(block, times(0)).setBeginCount(0);
        verify(shot, times(0)).setBeginCount(0);
    }

    @Test
    public void endCountFocusedProperty() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(manager.getActiveShotBlock()).thenReturn(block);
        when(block.getShot()).thenReturn(shot);

        detailViewController.endCountFocusListener(new ObservableValue<Boolean>() {
            @Override
            public void addListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public Boolean getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, true, false);

        verify(block, times(1)).setEndCount(0);
        verify(shot, times(1)).setEndCount(0);
    }

    @Test
    public void endCountFocusedPropertyNull() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(block.getShot()).thenReturn(shot);

        detailViewController.endCountFocusListener(new ObservableValue<Boolean>() {
            @Override
            public void addListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public Boolean getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, true, false);

        verify(block, times(0)).setEndCount(0);
        verify(shot, times(0)).setEndCount(0);
    }

    @Test
    public void endCountFocusedPropertyFalse() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(manager.getActiveShotBlock()).thenReturn(block);
        when(block.getShot()).thenReturn(shot);

        detailViewController.endCountFocusListener(new ObservableValue<Boolean>() {
            @Override
            public void addListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super Boolean> listener) {
            }

            @Override
            public Boolean getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, false, true);

        verify(block, times(0)).setEndCount(0);
        verify(shot, times(0)).setEndCount(0);
    }

    @Test
    public void nameFieldTextProperty() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(manager.getActiveShotBlock()).thenReturn(block);
        when(block.getShot()).thenReturn(shot);

        detailViewController.nameTextChangedListener(new ObservableValue<String>() {
            @Override
            public void addListener(ChangeListener<? super String> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super String> listener) {
            }

            @Override
            public String getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, "", "test newvalue");

        verify(block, times(1)).setName("test newvalue");
        verify(shot, times(1)).setName("test newvalue");
    }

    @Test
    public void nameFieldTextPropertyNull() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(block.getShot()).thenReturn(shot);

        detailViewController.nameTextChangedListener(new ObservableValue<String>() {
            @Override
            public void addListener(ChangeListener<? super String> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super String> listener) {
            }

            @Override
            public String getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, "", "test newvalue");

        verify(block, times(0)).setName("test newvalue");
        verify(shot, times(0)).setName("test newvalue");
    }

    @Test
    public void descriptionFieldTextProperty() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(manager.getActiveShotBlock()).thenReturn(block);
        when(block.getShot()).thenReturn(shot);

        detailViewController.descriptionTextChangedListener(new ObservableValue<String>() {
            @Override
            public void addListener(ChangeListener<? super String> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super String> listener) {
            }

            @Override
            public String getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, "", "test newvalue");

        verify(block, times(1)).setDescription("test newvalue");
        verify(shot, times(1)).setDescription("test newvalue");
    }

    @Test
    public void descriptionFieldTextPropertyNull() {
        CameraShotBlock block = Mockito.mock(CameraShotBlock.class);
        CameraShot shot = Mockito.mock(CameraShot.class);
        when(block.getShot()).thenReturn(shot);

        detailViewController.descriptionTextChangedListener(new ObservableValue<String>() {
            @Override
            public void addListener(ChangeListener<? super String> listener) {
            }

            @Override
            public void removeListener(ChangeListener<? super String> listener) {
            }

            @Override
            public String getValue() {
                return null;
            }

            @Override
            public void addListener(InvalidationListener listener) {
            }

            @Override
            public void removeListener(InvalidationListener listener) {
            }
        }, "", "test newvalue");

        verify(block, times(0)).setDescription("test newvalue");
        verify(shot, times(0)).setDescription("test newvalue");
    }

    @Test
    public void activeBlockChangedCamera() {
        // Setup mocks
        CameraShotBlock shotBlock = Mockito.mock(CameraShotBlock.class);
        RootPane rootPane = Mockito.mock(RootPane.class);
        RootHeaderArea rootHeaderArea = Mockito.mock(RootHeaderArea.class);

        // Mock all the methods
        when(manager.getActiveShotBlock()).thenReturn(shotBlock);
        when(manager.getRootPane()).thenReturn(rootPane);
        when(rootPane.getRootHeaderArea()).thenReturn(rootHeaderArea);

        // Call method under testing
        detailViewController.activeBlockChanged();

        // Verify all the things
        Mockito.verify(detailViewController, times(1)).reInitForCameraBlock();
        Mockito.verify(rootHeaderArea, times(1)).reInitHeaderBar(anyObject());
    }

    @Test
    public void activeBlockChangedDirector() {
        // Setup mocks
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        RootPane rootPane = Mockito.mock(RootPane.class);
        RootHeaderArea rootHeaderArea = Mockito.mock(RootHeaderArea.class);

        // Mock all the methods
        when(manager.getActiveShotBlock()).thenReturn(shotBlock);
        when(manager.getRootPane()).thenReturn(rootPane);
        when(rootPane.getRootHeaderArea()).thenReturn(rootHeaderArea);

        // Call method under testing
        detailViewController.activeBlockChanged();

        // Verify all the things
        Mockito.verify(detailViewController, times(1)).reInitForDirectorBlock();
        Mockito.verify(rootHeaderArea, times(1)).reInitHeaderBar(anyObject());
    }

    @Test
    public void instrumentsDropdownListener() {
        // Setup mocks
        StyledMenuButton menuButton = new StyledMenuButton();
        CameraShotBlock shotBlock = Mockito.mock(CameraShotBlock.class);
        Instrument instrument = Mockito.mock(Instrument.class);
        ArrayList<Instrument> instrumentList = new ArrayList<>(Arrays.asList(instrument));
        ScriptingProject project = Mockito.mock(ScriptingProject.class);
        List<StyledCheckbox> list = Mockito.mock(List.class);
        StyledCheckbox checkbox = Mockito.mock(StyledCheckbox.class);

        // Mock all the methods
        when(shotBlock.getInstruments()).thenReturn(instrumentList);
        detailViewController.setActiveCameraBlock(shotBlock);
        detailViewController.setActiveInstrumentBoxes(list);
        when(manager.getScriptingProject()).thenReturn(project);
        when(project.getInstruments()).thenReturn(instrumentList);
        doReturn(checkbox).when(detailViewController).getStyledCheckbox(anyString(), anyBoolean());

        // Call method under testing
        detailViewController.instrumentsDropdownListener(null, false, true, menuButton);

        // Verify all the things
        assertEquals(1, menuButton.getItems().size());
        Mockito.verify(list, times(1)).add(checkbox);
    }

    @Test
    public void instrumentsDropdownListenerFalse() {
        // Setup mocks
        StyledMenuButton menuButton = new StyledMenuButton();
        List<StyledCheckbox> list = Mockito.mock(List.class);

        // Mock all the methods
        detailViewController.setActiveInstrumentBoxes(list);

        // Call method under testing
        detailViewController.instrumentsDropdownListener(null, true, false, menuButton);

        // Verify all the things
        Mockito.verify(list, times(1)).clear();
    }

    @Test
    public void cameraDropdownListenerFalse() {
        // Setup mocks
        StyledMenuButton menuButton = new StyledMenuButton();
        List<StyledCheckbox> list = Mockito.mock(List.class);

        // Mock all the methods
        detailViewController.setActiveCameraBoxes(list);

        // Call method under testing
        detailViewController.cameraDropdownListener(null, true, false, menuButton);

        // Verify all the things
        Mockito.verify(list, times(1)).clear();
    }

    @Test
    public void camerasDropdownListener() {
        // Setup mocks
        StyledMenuButton menuButton = new StyledMenuButton();
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        Camera camera = Mockito.mock(Camera.class);
        ArrayList<Camera> cameraList = new ArrayList<>(Arrays.asList(camera));
        ScriptingProject project = Mockito.mock(ScriptingProject.class);
        List<StyledCheckbox> list = Mockito.mock(List.class);
        StyledCheckbox checkbox = Mockito.mock(StyledCheckbox.class);

        // Mock all the methods
        detailViewController.setActiveDirectorBlock(shotBlock);
        detailViewController.setActiveCameraBoxes(list);
        when(manager.getScriptingProject()).thenReturn(project);
        when(project.getCameras()).thenReturn(cameraList);
        doReturn(checkbox).when(detailViewController).getStyledCheckbox(anyString(), anyBoolean());

        // Call method under testing
        detailViewController.cameraDropdownListener(null, false, true, menuButton);

        // Verify all the things
        assertEquals(1, menuButton.getItems().size());
        Mockito.verify(list, times(1)).add(checkbox);
    }

    @Test
    public void getDetailView() {
        assertEquals(detailView, detailViewController.getDetailView());
    }

    @Test
    public void getActiveDirectorBlock() {
        DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class);
        detailViewController.setActiveDirectorBlock(shotBlock);
        assertEquals(shotBlock, detailViewController.getActiveDirectorBlock());
    }

    @Test
    public void getActiveCameraBlock() {
        CameraShotBlock shotBlock = Mockito.mock(CameraShotBlock.class);
        detailViewController.setActiveCameraBlock(shotBlock);
        assertEquals(shotBlock, detailViewController.getActiveCameraBlock());
    }

    @Test
    public void getActiveCameraBoxes() {
        List<StyledCheckbox> list = Mockito.mock(List.class);
        detailViewController.setActiveCameraBoxes(list);
        assertEquals(list, detailViewController.getActiveCameraBoxes());
    }

    @Test
    public void getActiveInstrumentBoxes() {
        List<StyledCheckbox> list = Mockito.mock(List.class);
        detailViewController.setActiveInstrumentBoxes(list);
        assertEquals(list, detailViewController.getActiveInstrumentBoxes());
    }

    @Override
    public void start(Stage stage) throws Exception {

    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />

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

    <link href="//fonts.googleapis.com/css?family=Open+Sans:300italic,300,400italic,400,600italic,600,700italic,700,800italic,800" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <title>{{pageTitle}} - kosamari</title>
    <meta name="title" content="{{pageTitle}}" />
    <meta name="description" content="{{description}}" />
    <meta name="author" content="Mariko Kosaka" />

        back to top
        {{title}}
        posted on <time datetime="{{date}}" pubdate>{{date}}</time>

        {{content}}

        {{> footer}}

  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.7/styles/github-gist.min.css">

    {{#if ga}}
      {{> ga }}
    {{/if}}

redpajama_set_name: RedPajamaGithub


text:
import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';

import {HomeComponent} from '../home/home.component';
import {HelloComponent} from '../hello/hello.component';

@Component({
    selector: 'jrocket',
    templateUrl: './components/app/app.html',
    styleUrls: ['./components/app/app.css'],
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
    {path: '/', name: 'Home', component: HomeComponent},
    {path: '/hello', name: 'Hello', component: HelloComponent}
])
export class AppComponent {
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace SharpGenetics.BaseClasses
{
    [DataContract]
    public class DefaultDoubleFitnessComparer : FitnessComparer
    {
        public override int Compare<T>(T A, T B)
        {
            return A.GetFitness().CompareTo(B.GetFitness());
        }
    }
}


text:
typedef NTL::ZZ lint;

namespace ZZHelper
{
    enum EQuantileValue
    {
        weak,//0.1
        medium,//0.05
        strong//0.01
    };
    lint LintFromHex(char value);
    lint LintFromHex(const std::string& hexValue);
    lint Merge3ValuesOfLint(const lint& value9, const lint& value10, const lint& value11 );//create seed for geffe
    lint CycleBitShift(const lint& number, bool isLeftShift);
    std::deque<int> ParseDequeFromLint(lint number, int numberOfDigits);
    float GetQuantileValue(EQuantileValue quantile);
}


text:
using System;
using Microsoft.AspNet.SignalR;

namespace RElmah.Host.Services
{
    class Registry : IRegistry
    {
        public T Resolve<T>()
        {
            return GlobalHost.DependencyResolver.Resolve<T>();
        }

        public void Register<T>(Func<T> supplier)
        {
            Register(typeof (T), () => supplier());
        }

        public void Register(Type type, Func<object> supplier)
        {
            GlobalHost.DependencyResolver.Register(type, supplier);
        }
    }
}


text:
<?php

$_SERVER['APP_RUNTIME_OPTIONS'] = [
    'env_var_name' => 'ENV_MODE',
    'debug_var_name' => 'DEBUG_MODE',
];
require __DIR__.'/autoload.php';

return function (array $context): void {
    if (isset($context['APP_ENV']) || isset($context['APP_DEBUG'])) {
        echo 'An error occurred on the variable name options.';
    } else {
        echo 'Env mode ', $context['ENV_MODE'], ', debug mode ', $context['DEBUG_MODE'];
    }
};


text:
package me.manage.domain.model.bianwu.manuscript;

import me.manage.infrastructure.persistence.hibernate.generic.IHibernateGenericRepository;

import java.io.Serializable;

/**
 * Created by savion on 2015/4/28.
 */
public interface IManuscriptRepository<T, ID extends Serializable> extends IHibernateGenericRepository<T, ID> {
}


text:
module.exports = function (promises) {
  return Promise.all(promises.map(function (promise) {
    return promise.then(function (value) {
      return { state: 'fulfilled', value };
    }).catch(function (reason) {
      return { state: 'rejected', reason };
    });
  }));
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace ODataValidator.Rule
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.XPath;
    using ODataValidator.Rule.Helper;
    using ODataValidator.RuleEngine;
    using ODataValidator.RuleEngine.Common;

    /// <summary>
    /// Class of code rule applying to entry payload
    /// </summary>
    [Export(typeof(ExtensionRule))]
    public class IndividualPropertyCore4633 : CommonCore4633
    {
        /// <summary>
        /// Gets the payload type to which the rule applies.
        /// </summary>
        public override PayloadType? PayloadType
        {
            get
            {
                return RuleEngine.PayloadType.IndividualProperty;
            }
        }
    }

    /// <summary>
    /// Class of entension rule for Common.Core.4633
    /// </summary>
    public abstract class CommonCore4633 : ExtensionRule
    {
        /// <summary>
        /// Gets Category property
        /// </summary>
        public override string Category
        {
            get
            {
                return "core";
            }
        }

        /// <summary>
        /// Gets rule name
        /// </summary>
        public override string Name
        {
            get
            {
                return "Common.Core.4633";
            }
        }

        /// <summary>
        /// Gets rule description
        /// </summary>
        public override string Description
        {
            get
            {
                return @"When annotating an instance of a complex type, the annotation element MUST be a direct child of the metadata:value element.";
            }
        }

        /// <summary>
        /// Gets rule specification in OData document
        /// </summary>
        public override string V4SpecificationSection
        {
            get
            {
                return "18.3.4";
            }
        }

        /// <summary>
        /// Gets the version.
        /// </summary>
        public override ODataVersion? Version
        {
            get
            {
                return ODataVersion.V4;
            }
        }

        /// <summary>
        /// Gets location of help information of the rule
        /// </summary>
        public override string HelpLink
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the error message for validation failure
        /// </summary>
        public override string ErrorMessage
        {
            get
            {
                return this.Description;
            }
        }

        /// <summary>
        /// Gets the requriement level.
        /// </summary>
        public override RequirementLevel RequirementLevel
        {
            get
            {
                return RequirementLevel.Must;
            }
        }

        /// <summary>
        /// Gets the payload format to which the rule applies.
        /// </summary>
        public override PayloadFormat? PayloadFormat
        {
            get
            {
                return RuleEngine.PayloadFormat.Xml;
            }
        }

        /// <summary>
        /// Gets the RequireMetadata property to which the rule applies.
        /// </summary>
        public override bool? RequireMetadata
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Gets the IsOfflineContext property to which the rule applies.
        /// </summary>
        public override bool? IsOfflineContext
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Verify Common.Core.4633
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;

            // Single primitive individual property is not allowed to have instance annotation.
            if (VerificationHelper.IsIndividualPropertySinglePrimitiveType(context.ResponsePayload, context.PayloadType))
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                return null;
            }

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(context.ResponsePayload);
            XmlElement root = xmlDoc.DocumentElement;
            string type = string.Empty;

            if (root.LocalName.Equals("value") && root.NamespaceURI.Equals(Constants.NSMetadata))
            {
                if (root.Attributes["type", Constants.NSMetadata] != null)
                {
                    type = root.Attributes["type", Constants.NSMetadata].Value;

                    if (type.Contains("Collection("))
                    {
                        type = type.Substring(type.IndexOf('(') + 1, type.Length - 12);
                    }

                    type = type.Substring(type.LastIndexOf('.') + 1);

                    List<string> complexTypeNames = MetadataHelper.GetAllComplexNameFromMetadata(context.MetadataDocument);

                    if (complexTypeNames.Contains(type))
                    {
                        string annotation = @"//*[local-name()='value']/*[local-name()='annotation']";
                        XmlNodeList annoations = xmlDoc.SelectNodes(annotation, ODataNamespaceManager.Instance);
                        if (annoations !=null && annoations.Count > 0)
                        {
                            foreach (XmlNode anno in annoations)
                            {
                                if(anno.Attributes["target"] == null || anno.Attributes["target"].Value.Contains(type))
                                {
                                    passed = true;
                                }
                                else
                                {
                                    passed = false;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            info = new ExtensionRuleViolationInfo(passed == true ? null : this.ErrorMessage, context.Destination, context.ResponsePayload);

            return passed;
        }
    }
}


text:
<!DOCTYPE html>

    <title>IGListCollectionScrollingTraits Structure Reference</title>
    <link rel="stylesheet" type="text/css" href="../../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../../css/highlight.css" />
    <meta charset='utf-8'>

IGListKit Docs (98% documented)

View on GitHub

        IGListKit Reference

        IGListCollectionScrollingTraits Structure Reference

            Guides

                Best Practices and FAQ

                Generating your models using remodel

                Getting Started

                IGListDiffable and Equality

                Installation

                Migration

                Modeling and Binding

                VISION

                Working with Core Data

                Working with UICollectionView

            Classes

                IGListAdapter

                IGListAdapterUpdater

                IGListBatchUpdateData

                IGListBindingSectionController

                IGListCollectionView

                IGListCollectionViewLayout

                IGListGenericSectionController

                IGListIndexPathResult

                IGListIndexSetResult

                IGListMoveIndex

                IGListMoveIndexPath

                IGListReloadDataUpdater

                IGListSectionController

                IGListSingleSectionController

            Constants

                IGListKitVersionNumber

                IGListKitVersionString

            Enumerations

                IGListAdapterUpdateType

                IGListDiffOption

                IGListExperiment

            Protocols

                IGListAdapterDataSource

                IGListAdapterDelegate

                IGListAdapterMoveDelegate

                IGListAdapterPerformanceDelegate

                IGListAdapterUpdateListener

                IGListAdapterUpdaterDelegate

                IGListBatchContext

                IGListBindable

                IGListBindingSectionControllerDataSource

                IGListBindingSectionControllerSelectionDelegate

                IGListCollectionContext

                IGListCollectionViewDelegateLayout

                IGListCollectionViewLayoutCompatible

                IGListDiffable

                IGListDisplayDelegate

                IGListScrollDelegate

                IGListSingleSectionControllerDelegate

                IGListSupplementaryViewSource

                IGListTransitionDelegate

                IGListUpdatingDelegate

                IGListWorkingRangeDelegate

            Type Definitions

                IGListCollectionScrollingTraits

                IGListCollectionViewBlock

                IGListItemUpdateBlock

                IGListObjectTransitionBlock

                IGListReloadUpdateBlock

                IGListSingleSectionCellConfigureBlock

                IGListSingleSectionCellSizeBlock

                IGListToObjectBlock

                IGListUpdaterCompletion

                IGListUpdatingCompletion

            Functions

                IGListDiff

                IGListDiffExperiment

                IGListDiffPaths

                IGListDiffPathsExperiment

                IGListExperimentEnabled

            Structures

                IGListCollectionScrollingTraits

IGListCollectionScrollingTraits

struct IGListCollectionScrollingTraits {}

The current scrolling traits of the underlying collection view.
The attributes are always equal to their corresponding properties on the underlying collection view.

                    isTracking

returns YES if user has touched. may not yet have started dragging.

Declaration

Objective-C

_Bool isTracking

Swift

var isTracking: Bool

                    isDragging

returns YES if user has started scrolling. this may require some time and or distance to move to initiate dragging

Declaration

Objective-C

_Bool isDragging

Swift

var isDragging: Bool

                    isDecelerating

returns YES if user isn’t dragging (touch up) but scroll view is still moving.

Declaration

Objective-C

_Bool isDecelerating

Swift

var isDecelerating: Bool

© 2019 Instagram. All rights reserved. (Last updated: 2019-11-20)

Generated by jazzy ♪♫ v0.12.0, a Realm project.


text:
package com.docd.purefm.commandline;

import com.docd.purefm.file.GenericFile;

import org.apache.commons.io.FileUtils;
import android.support.annotation.NonNull;

import java.util.List;

/**
 * du - estimate file space usage
 * -s  display only a total for each argument
 */
public final class CommandDu extends BusyboxCommand {

    public CommandDu(@NonNull final GenericFile file) {
        super("du -s " + file.getAbsolutePath());
    }

    public static long du_s(@NonNull final GenericFile file) {
        final List<String> result = CommandLine.executeForResult(new CommandDu(file));
        if (result == null || result.isEmpty()) {
            return 0L;
        }
        final String res = result.get(0);
        final int resLength = res.length();
        final StringBuilder lengthString = new StringBuilder(resLength);
        for (int i = 0; i < resLength; i++) {
            final char character = res.charAt(i);
            if (Character.isDigit(character)) {
                lengthString.append(character);
            } else {
                break;
            }
        }
        try {
            return Long.parseLong(lengthString.toString()) * FileUtils.ONE_KB;
        } catch (NumberFormatException e) {
            return 0L;
        }
    }
}


text:
/*
Change Log:
     Added package protection and console debugging support.
*/
// add ';' to seperate from previous code clips.
// w,d, c, u refers to window, document, console and undefined, respectively.
;(function (w, d, c, u) {
	// function wrapped inside
	// fall-back for console
	if (c === u) {
		c = {
			log: function () {},
			warn: function () {}
		};
	}
	function microtime(get_as_float) {
		var now = new Date().getTime() / 1000;
		var s = parseInt(now, 10);
		return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
	}
	var startTime = microtime(true);
	function elapsedTime() {
		return microtime(true) - startTime;
	}
	function log(msg) {
		c.log('@' + elapsedTime().toString(10).substr(0,16) + ', PQUEUE_2: ' + msg);
	}
	function warn(msg) {
		c.warn('@' + elapsedTime().toString(10).substr(0,16) + ', PQUEUE_2: ' + msg);
	}
	function PQUEUE_2(parent, processArray, initialProcessID, queueName) {
		"use strict";
		log('Instantiating new process queue.');
		if (typeof processArray !== 'object') {
			warn('Invalid argument[1]. Expecting an Object.');
			warn('Returning NULL.');
			return;
		}
		log('Generating new process queue object.');
		return new function () {
			// make a backup reference to this.
			var pqueue = this;
			// connect with parent queue
			var _parent = (typeof parent === 'object') ? parent : null;
			// private variables
			var status = {
				calling: false,
				ticking: false,
				error: false,
				errorMessage: [],
				autoProceed: false,
				// name of queue
				name: String(queueName ? queueName : (new Date()).getTime()),
				// array of processes
				processes: [],
				processIndex: [],
				// process counter
				pc: 0,
			};
			// for temporary storage for processes
			var sharedHeap = {};
			// helper functions
			function pcOverflow() {
				return status.pc >= status.processes.length;
			}

			function fireError(message) {
				status.error = true;
				status.errorMessage.push((typeof message === 'string') ? message : '');
			}
			function throwError() {
				while (status.errorMessage.length > 0) {
					warn(status.errorMessage.shift());
				}
			}

			function is_function(object) {
				return typeof object === 'function';
			}

			function is_HALT(process) {
				return process === PQUEUE_HALT;
			}

			function is_BARRIER(process) {
				return process === PQUEUE_BARRIER;
			}
			// start running
			this.tick = function () {
				// if already ticking, halt.
				if (status.ticking) {
					warn('Already ticking.');
					return;
				}
				status.ticking = true;
				log('[' + status.name + '].tick');
				// don't autoProceed by default
				status.autoProceed = false;

				if (status.error !== false) {
					// cant process with error
					throwError();
				} else {
					log('PC = ' + status.pc);
					if (pcOverflow()) {
						fireError('PC overflow');
					} else {
						var currentProcess = status.processes[status.pc];
						if (!is_function(currentProcess)) {
							fireError('invalid process');
						} else if (is_HALT(currentProcess)) {
							log('halt');
						} else if (is_BARRIER(currentProcess)) {
							log('barrier');
						} else {
							// now can proceed
							++status.pc;
							status.autoProceed = true;
							log('>>' + currentProcess.name);
							/**
							 * pass _api over so client script
							 * can only harm _api
							 */
							var _api = {
								heap: sharedHeap,
								heap_dump: function () {
									var result = '';
									for (var key in sharedHeap) {
										if (result !== '') result += ', \n';
										result += key + ':' + sharedHeap[key];
									}
									return '{\n' + result + '\n}';
								},
								wait: function (time) {
									if (status.calling === true && status.autoProceed === true) {
										switch (typeof time) {
											case 'number':
												w.setTimeout(_api.walk, time);
											case 'undefined':
												status.autoProceed = false;
												break;
											default:
										}
									}
								},
								walk: function () {
									if (status.calling === false && status.autoProceed === false) {
										status.autoProceed = true;
										pqueue.tick();
									}
								},
								pc: {
									increment: function () {
										++status.pc;
									},
									decrement: function () {
										--status.pc;
									},
									offset: function (value) {
										status.pc += Number(value) || 0;
									},
									goto: function (value) {
										status.pc = Number(value) || -1;
									},
									locate: function (funcName) {
										return status.processIndex[String(funcName)] || -1;
									}
								},
								parent: _parent
							};
							status.calling = true;
							try {
								currentProcess.call(_api, _api);
							} catch (e) {
								fireError(e.message);
							}
							status.calling = false;
						}
					}
				}
				status.ticking = false;
				if (status.autoProceed === true) w.setTimeout(function () {
					pqueue.tick()
				}, 0);
			};
			for (var key in processArray) {
				var process = processArray[key];
				var index = status.processes.length;
				var name = process.name;
				status.processes.push(process);
				if (name !== '') status.processIndex[name] = index;
			}
			status.pc = parseInt(initialProcessID, 10) || 0;
		};
	}

	function PQUEUE_HALT(q) {}

	function PQUEUE_BARRIER(q) {
		q.wait();
	}
	if (w.PQUEUE === u) {
		w.PQUEUE = PQUEUE_2;
		w.PQUEUE_HALT = PQUEUE_HALT;
		w.PQUEUE_BARRIER = PQUEUE_BARRIER;
	}
})(window, document, console);


text:
package org.chronix.cli;

import java.util.ArrayList;
import java.util.List;

import javax.jms.JMSException;

import org.slf4j.Logger;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.oxymores.chronix.engine.helpers.SenderHelpers;
import org.slf4j.LoggerFactory;

/**
 * Hello world!
 *
 */
public class ChronixCli
{
    private static Logger log = LoggerFactory.getLogger(ChronixCli.class);

    public static void main(String[] args)
    {
        new ChronixCli().doMain(args);
    }

    @Option(name = "-n", aliases = { "--name", "--eventsource" }, usage = "for sending events from this source", required = true)
    private String source;

    @Option(name = "-p", aliases = { "--port" }, usage = "port of the Chronix server to connect to. Default is 1789. ", required = false)
    private Integer port = 1789;

    @Option(name = "-s", aliases = { "--server",
            "--broker" }, usage = "Chronix server to connect to. Default is localhost", required = false)
    private String server = "localhost";

    @Option(name = "-d", aliases = { "--data", "--eventdata" }, usage = "data associated to the event", required = false)
    private String filepath = "";

    @Argument
    private List<String> arguments = new ArrayList<String>();

    private void doMain(String[] args)
    {
        log.info("Starting Chronix CLI");
        CmdLineParser parser = new CmdLineParser(this);

        try
        {
            parser.parseArgument(args);

            if (!arguments.isEmpty())
            {
                throw new CmdLineException(parser, "Weird options given");
            }
        }
        catch (CmdLineException e)
        {
            System.err.println(e.getMessage());
            parser.printUsage(System.err);
            System.err.println();

            return;
        }

        // TODO: OSGi CLI
        /*try
        {
            SenderHelpers.sendOrderExternalEvent(source, filepath, server.toUpperCase());
        }
        catch (JMSException e)
        {
            log.error("An error occurred during message sending: " + e.getMessage());
            System.exit(1);
        }*/
    }
}


text:
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, caption, table, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
	margin:0;
	padding:0;
	border:0;
	font-size:100%;
	font:inherit;
	vertical-align:baseline
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
	display:block
}
body {
	line-height:1
}
ol, ul {
	list-style:none
}
blockquote, q {
	quotes:none
}
blockquote:before, blockquote:after, q:before, q:after {
	content:'';
	content:none
}
table {
	border-collapse:collapse;
	border-spacing:0
}
table {
	vertical-align:middle
}
tbody, tfoot, thead, tr, th, td {
	vertical-align:inherit
}
h1, h2, h3, h4, h5, h6 {
	font-weight:bold
}
th {
	font-weight:bold
}
strong {
	font-weight:bold
}
p {
	margin:1em 0
}
h3 {
  font-size:18px;
  color: #69717E;
  margin: 10px auto;
  text-shadow: 1px 1px 1px #fff;
}
a {
	outline:0
}
/* Fancy Box here */
.mpbutton, .mpbutton-small, .mpbutton-smaller, .mpbutton-medium, .mpbutton-yans, .mpbutton-jr {
	background:url(../images/buttons.png) 0 0 no-repeat;
	border:0 none;
	cursor:pointer;
	outline:0;
	display:inline-block;
	text-indent:-7000px;
	white-space:nowrap
}
.mpbutton {
	width:95px;
	height:33px
}
.mpbutton-small {
	width:54px;
	height:23px
}
.mpbutton-smaller {
	width:44px;
	height:23px
}
.mpbutton-medium {
	width:72px;
	height:25px
}
.mpbutton-yans {
	width:69px;
	height:27px
}
.mpbutton-jr {
	width:82px;
	height:32px;
	position:relative;
	top:-1px
}
.mpbutton-grey, .mpbutton-grey.disabled:hover, .mpbutton-grey.disabled:active {
	padding:3px 8px;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#E0E0E0');
	background:-webkit-gradient(linear, left top, left bottom, from(#fff), to(#e0e0e0));
	background:-moz-linear-gradient(top, #fff, #e0e0e0);
	border:1px solid #acacac;
	color:#898989;
	border-radius:2px;
	-moz-border-radius:2px;
	-webkit-border-radius:2px
}
.mpbutton-grey:hover {
	color:#767676;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#c7c7c7');
	background:-webkit-gradient(linear, left top, left bottom, from(#fff), to(#c7c7c7));
	background:-moz-linear-gradient(top, #fff, #c7c7c7);
	border:1px solid #9c9c9c
}
.mpbutton-grey:active {
	color:#767676;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#c7c7c7', endColorstr='#ffffff');
	background:-webkit-gradient(linear, left top, left bottom, from(#c7c7c7), to(#fff));
	background:-moz-linear-gradient(top, #c7c7c7, #fff);
	border:1px solid #9c9c9c
}
.mpbutton-grey.disabled, .mpbutton-grey.disabled * {
	opacity:.6
}
.mpbutton-grey.disabled {
	cursor:default
}
.mpbutton.cancel {
	background-position:0 0
}
.mpbutton.cancel:hover {
	background-position:-95px 0
}
.mpbutton.cancel:active {
	background-position:-190px 0
}
.mpbutton.reset {
	background-position:0 -33px
}
.mpbutton.reset:hover {
	background-position:-95px -33px
}
.mpbutton.reset:active {
	background-position:-190px -33px
}
.mpbutton.delete {
	background-position:0 -66px
}
.mpbutton.delete:hover {
	background-position:-95px -66px
}
.mpbutton.delete:active {
	background-position:-190px -66px
}
.mpbutton.okay-green {
	background-position:0 -99px
}
.mpbutton.okay-green:hover {
	background-position:-95px -99px
}
.mpbutton.okay-green:active {
	background-position:-190px -99px
}
.mpbutton.upgrade {
	background-position:0 -132px
}
.mpbutton.upgrade:hover {
	background-position:-95px -132px
}
.mpbutton.upgrade:active {
	background-position:-190px -132px
}
.mpbutton.upgrade.disabled, .mpbutton.upgrade.disabled * {
	background-position:0 -132px;
	opacity:.6;
	-moz-opacity:.6;
	-khtml-opacity:.6;
	filter:alpha(opacity=60);
	cursor:default
}
.mpbutton.login {
	background-position:0 -165px
}
.mpbutton.login:hover {
	background-position:-95px -165px
}
.mpbutton.login:active {
	background-position:-190px -165px
}
.mpbutton.okay-blue {
	background-position:0 -198px
}
.mpbutton.okay-blue:hover {
	background-position:-95px -198px
}
.mpbutton.okay-blue:active {
	background-position:-190px -198px
}
.mpbutton.edit {
	background-position:0 -231px
}
.mpbutton.edit:hover {
	background-position:-95px -231px
}
.mpbutton.edit:active {
	background-position:-190px -231px
}
.mpbutton.save-green {
	background-position:0 -264px
}
.mpbutton.save-green:hover {
	background-position:-95px -264px
}
.mpbutton.save-green:active {
	background-position:-190px -264px
}
.mpbutton.save {
	background-position:0 -264px
}
.mpbutton.save:hover {
	background-position:-95px -264px
}
.mpbutton.save:active {
	background-position:-190px -264px
}
.mpbutton.sign-up-blue {
	background-position:0 -297px
}
.mpbutton.sign-up-blue:hover {
	background-position:-95px -297px
}
.mpbutton.sign-up-blue:active {
	background-position:-190px -297px
}
.mpbutton.continue {
	background-position:0 -330px
}
.mpbutton.continue:hover {
	background-position:-95px -330px
}
.mpbutton.continue:active {
	background-position:-190px -330px
}
.mpbutton.sign-up-green {
	background-position:0 -363px
}
.mpbutton.sign-up-green:hover {
	background-position:-95px -363px
}
.mpbutton.sign-up-green:active {
	background-position:-190px -363px
}
.mpbutton.purchase {
	background-position:0 -396px
}
.mpbutton.purchase:hover {
	background-position:-95px -396px
}
.mpbutton.purchase:active {
	background-position:-190px -396px
}
.mpbutton.purchased.disabled, .mpbutton.purchased.disabled * {
	background-position:0 -396px;
	opacity:.6;
	-moz-opacity:.6;
	-khtml-opacity:.6;
	filter:alpha(opacity=60);
	cursor:default
}
.mpbutton.contact {
	background-position:0 -429px
}
.mpbutton.contact:hover {
	background-position:-95px -429px
}
.mpbutton.contact:active {
	background-position:-190px -429px
}
.mpbutton.preview {
	background-position:0 -462px
}
.mpbutton.preview:hover {
	background-position:-95px -462px
}
.mpbutton.preview:active {
	background-position:-190px -462px
}
.mpbutton.learn-more {
	background-position:0 -495px
}
.mpbutton.learn-more:hover {
	background-position:-95px -495px
}
.mpbutton.learn-more:active {
	background-position:-190px -495px
}
.mpbutton.previous {
	background-position:0 -528px
}
.mpbutton.previous:hover {
	background-position:-95px -528px
}
.mpbutton.previous:active {
	background-position:-190px -528px
}
.mpbutton.next-grey {
	background-position:0 -561px
}
.mpbutton.next-grey:hover {
	background-position:-95px -561px
}
.mpbutton.next-grey:active {
	background-position:-190px -561px
}
.mpbutton.signup-arrow {
	background-position:0 -594px
}
.mpbutton.signup-arrow:hover {
	background-position:-95px -594px
}
.mpbutton.signup-arrow:active {
	background-position:-190px -594px
}
.mpbutton.close {
	background-position:0 -627px
}
.mpbutton.close:hover {
	background-position:-95px -627px
}
.mpbutton.close:active {
	background-position:-190px -627px
}
.mpbutton.show {
	background-position:0 -660px
}
.mpbutton.show:hover {
	background-position:-95px -660px
}
.mpbutton.show:active {
	background-position:-190px -660px
}
.mpbutton.save-gray {
	background-position:0 -693px
}
.mpbutton.save-gray:hover {
	background-position:-95px -693px
}
.mpbutton.save-gray:active {
	background-position:-190px -693px
}
.mpbutton.update {
	background-position:0 -726px
}
.mpbutton.update:hover {
	background-position:-95px -726px
}
.mpbutton.update:active {
	background-position:-190px -726px
}
.mpbutton.continue-blue {
	background-position:0 -759px
}
.mpbutton.continue-blue:hover {
	background-position:-95px -759px
}
.mpbutton.continue-blue:active {
	background-position:-190px -759px
}
.mpbutton.create {
	background-position:0 -891px
}
.mpbutton.create:hover {
	background-position:-95px -891px
}
.mpbutton.create:active {
	background-position:-190px -891px
}
.mpbutton.create.disabled, .mpbutton.create.disabled * {
	background-position:0 -891px;
	opacity:.6;
	-moz-opacity:.6;
	-khtml-opacity:.6;
	filter:alpha(opacity=60);
	cursor:default
}
.mpbutton.previous {
	background-position:0 -825px
}
.mpbutton.previous:hover {
	background-position:-95px -825px
}
.mpbutton.previous:active {
	background-position:-190px -825px
}
.mpbutton.previous.disabled, .mpbutton.previous.disabled * {
	background-position:0 -825px;
	opacity:.6;
	-moz-opacity:.6;
	-khtml-opacity:.6;
	filter:alpha(opacity=60);
	cursor:default;
	position:relative;
	top:-1px
}
.mpbutton.next {
	background-position:0 -858px
}
.mpbutton.next:hover {
	background-position:-95px -858px
}
.mpbutton.next:active {
	background-position:-190px -858px
}
.mpbutton.next.disabled, .mpbutton.next.disabled * {
	background-position:0 -858px;
	opacity:.6;
	-moz-opacity:.6;
	-khtml-opacity:.6;
	filter:alpha(opacity=60);
	cursor:default;
	position:relative;
	top:-1px
}
.mpbutton.skip {
	background-position:0 -1023px
}
.mpbutton.skip:hover {
	background-position:-95px -1023px
}
.mpbutton.skip:active {
	background-position:-190px -1023px
}
.mpbutton.invite {
	background-position:0 -1056px
}
.mpbutton.invite:hover {
	background-position:-95px -1056px
}
.mpbutton.invite:active {
	background-position:-190px -1056px
}
.mpbutton.setup {
	background-position:0 -1089px
}
.mpbutton.setup:hover {
	background-position:-95px -1089px
}
.mpbutton.setup:active {
	background-position:-190px -1089px
}
.mpbutton-small.view-gray {
	background-position:-285px 0
}
.mpbutton-small.view-gray:hover {
	background-position:-339px 0
}
.mpbutton-small.view-gray:active {
	background-position:-393px 0
}
.mpbutton-small.view-blue {
	background-position:-285px -23px
}
.mpbutton-small.view-blue:hover {
	background-position:-339px -23px
}
.mpbutton-small.view-blue:active {
	background-position:-393px -23px
}
.mpbutton-small.save {
	background-position:-285px -46px
}
.mpbutton-small.save:hover {
	background-position:-339px -46px
}
.mpbutton-small.save:active {
	background-position:-393px -46px
}
.mpbutton-small.delete {
	background-position:-285px -69px
}
.mpbutton-small.delete:hover {
	background-position:-339px -69px
}
.mpbutton-small.delete:active {
	background-position:-393px -69px
}
.mpbutton-small.create {
	background-position:-285px -92px
}
.mpbutton-small.create:hover {
	background-position:-339px -92px
}
.mpbutton-small.create:active {
	background-position:-393px -92px
}
.mpbutton-small.invite {
	background-position:-285px -115px
}
.mpbutton-small.invite:hover {
	background-position:-339px -115px
}
.mpbutton-small.invite:active {
	background-position:-393px -115px
}
.mpbutton-small.sign-up {
	background-position:-285px -138px
}
.mpbutton-small.sign-up:hover {
	background-position:-339px -138px
}
.mpbutton-small.sign-up:active {
	background-position:-393px -138px
}
.mpbutton-small.edit {
	background-position:-285px -161px
}
.mpbutton-small.edit:hover {
	background-position:-339px -161px
}
.mpbutton-small.edit:active {
	background-position:-393px -161px
}
.mpbutton-small.save-grey {
	background-position:-285px -184px
}
.mpbutton-small.save-grey:hover {
	background-position:-339px -184px
}
.mpbutton-small.save-grey:active {
	background-position:-393px -184px
}
.mpbutton-small.hide {
	background-position:-285px -207px
}
.mpbutton-small.hide:hover {
	background-position:-339px -207px
}
.mpbutton-small.hide:active {
	background-position:-393px -207px
}
.mpbutton-small.cancel {
	background-position:-285px -230px
}
.mpbutton-small.cancel:hover {
	background-position:-339px -230px
}
.mpbutton-small.cancel:active {
	background-position:-393px -230px
}
.mpbutton-small.next {
	background-position:-285px -253px
}
.mpbutton-small.next:hover {
	background-position:-339px -253px
}
.mpbutton-small.next:active {
	background-position:-393px -253px
}
.mpbutton-small.remove {
	background-position:-285px -276px
}
.mpbutton-small.remove:hover {
	background-position:-339px -276px
}
.mpbutton-small.remove:active {
	background-position:-393px -276px
}
.mpbutton-medium.login {
	background-position:-447px 0
}
.mpbutton-medium.login:hover {
	background-position:-519px 0
}
.mpbutton-medium.login:active {
	background-position:-591px 0
}
.mpbutton-medium.sign-up {
	background-position:-447px -25px
}
.mpbutton-medium.sign-up:hover {
	background-position:-519px -25px
}
.mpbutton-medium.sign-up:active {
	background-position:-591px -25px
}
.mpbutton-medium.skip {
	background-position:-447px -50px
}
.mpbutton-medium.skip:hover {
	background-position:-519px -50px
}
.mpbutton-medium.skip:active {
	background-position:-591px -50px
}
.mpbutton-medium.show {
	background-position:-447px -75px
}
.mpbutton-medium.show:hover {
	background-position:-519px -75px
}
.mpbutton-medium.show:active {
	background-position:-591px -75px
}
.mpbutton-medium.sign-up-green {
	background-position:-447px -100px
}
.mpbutton-medium.sign-up-green:hover {
	background-position:-519px -100px
}
.mpbutton-medium.sign-up-green:active {
	background-position:-591px -100px
}
.mpbutton-medium.check {
	background-position:-447px -125px
}
.mpbutton-medium.check:hover {
	background-position:-519px -125px
}
.mpbutton-medium.check:active {
	background-position:-591px -125px
}
.mpbutton-smaller.hide {
	background-position:-663px 0
}
.mpbutton-smaller.hide:hover {
	background-position:-707px 0
}
.mpbutton-smaller.hide:active {
	background-position:-751px 0
}
.mpbutton-yans.done {
	background-position:-795px 0
}
.mpbutton-yans.done:hover {
	background-position:-864px 0
}
.mpbutton-yans.done:active {
	background-position:-933px 0
}
.mpbutton-jr.change {
	background-position:-1002px 0
}
.mpbutton-jr.change:hover {
	background-position:-1084px 0
}
.mpbutton-jr.change:active {
	background-position:-1166px 0
}
.mpbutton-jr.change.disabled, .mpbutton-jr.change.disabled * {
	background-position:-1002px 0;
	opacity:.6;
	-moz-opacity:.6;
	-khtml-opacity:.6;
	filter:alpha(opacity=60);
	cursor:default
}
.mpbutton-jr.invite {
	background-position:-1002px -32px
}
.mpbutton-jr.invite:hover {
	background-position:-1084px -32px
}
.mpbutton-jr.invite:active {
	background-position:-1166px -32px
}
.mpbutton-jr.create {
	background-position:-1002px -64px
}
.mpbutton-jr.create:hover {
	background-position:-1084px -64px
}
.mpbutton-jr.create:active {
	background-position:-1166px -64px
}
.mpbutton-jr.create.disabled, .mpbutton-jr.create.disabled * {
	background-position:-1002px -64px;
	opacity:.6;
	-moz-opacity:.6;
	-khtml-opacity:.6;
	filter:alpha(opacity=60);
	cursor:default
}

table {
  border-top-left-radius: 2px;
  -moz-border-top-left-radius: 2px;
  -webkit-border-top-left-radius: 2px;
  -khtml-border-top-left-radius: 2px;
  -o-border-top-left-radius: 2px;
  border-top-right-radius: 0px;
  -moz-border-top-right-radius: 0px;
  -webkit-border-top-right-radius: 0px;
  -khtml-border-top-right-radius: 0px;
  -o-border-top-right-radius: 0px;
}

table, th, td {
  border-collapse: collapse;
  border-spacing: 0;
}

table thead th {
  max-width: 320px;
  border-left: 1px solid #1E304D;
  overflow-x: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  border-bottom-right-radius: 0px;
  -moz-border-bottom-right-radius: 0px;
  -webkit-border-bottom-right-radius: 0px;
  -khtml-border-bottom-right-radius: 0px;
  -o-border-bottom-right-radius: 0px;
  border-bottom-left-radius: 0px;
  -moz-border-bottom-left-radius: 0px;
  -webkit-border-bottom-left-radius: 0px;
  -khtml-border-bottom-left-radius: 0px;
  -o-border-bottom-left-radius: 0px;
  padding: 10px 15px;
  color: white;
  text-shadow: 0px 1px 1px #555;
  font-weight: bold;
  border-width: 1px 0px;
  border-color: #1E304D;
  border-style: solid;
  white-space: nowrap;
  background: -webkit-gradient(linear, left top, left bottom, from(#5D80AA), to(#416491));
  background: -moz-linear-gradient(top, #5D80AA, #416491);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#5d80aa", endColorstr="#416491");
  box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset;
  -moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset;
  -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset;
  -khtml-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset;
  -o-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset;
}

table tbody td,
table tbody th {
  padding: 5px 15px;
  background-color: white;
  border-bottom: 1px solid gainsboro;
  border-right: 1px solid gainsboro;
  color: #555;
}

table tbody th {
  background: #eaeaea;
}

.align-center {
  text-align: center;
}

.align-right {
  text-align: right;
}

.float-left {
  float: left;
}

.float-right {
  float: right;
}


text:
/* jshint maxdepth:3 */
'use strict';

var _ = require('lodash'),
    db = require('../../db')(),
    converters = require('../../utils/typeConverters'),
    foundField;

module.exports = function convertType(kontx, next){

    if( !_.isUndefined(kontx.args.meta) && !_.isUndefined(kontx.args.meta.type) ) {
        queryContentTypes();
    }
    else {
       createError('Malformed incoming data. No meta or meta type.');
    }

    function queryContentTypes() {
        db.contentTypes.getById(kontx.args.meta.type.toString())
            .then(
                parseContentType,
                createError
            );
    }

    function parseContentType(contentType) {
        _.each(kontx.args.fields, function(value, key){

            foundField = findField(contentType, key);
            if(foundField) {
                distributeType(key);
            }
        });
        convertAnyTextToDate();
        next();
    }

    function findField(contentType, key) {
        return _.find(contentType.fields, function(field) {
            return field._id == key;
        });
    }

    function distributeType(key) {
        switch(foundField.type) {
        case 'textarea':
        case 'textbox':
        case 'password':
        case 'readonly':
        case 'richtext':
        case 'slug':
            applyConverter(key, converters.string);
            break;
        case 'boolean':
            applyConverter(key, converters.boolean);
            break;
        case 'checkbox':
            applyConverter(key, converters.checkbox);
            break;
        case 'editorialwindow':
            applyConverter(key, converters.editorial);
            break;
        case 'number' :
            applyConverter(key, converters.number);
            break;
        case 'date':
        case 'datetime':
            applyConverter(key, converters.date);
            break;
        }
    }

    function convertAnyTextToDate() {
        kontx.args = converters.anyStringsToDates(kontx.args);
    }

    function applyConverter(key, converter) {
        var field = kontx.args.fields[key];

        if(_.isArray(field)) {
            field = _.map(field, converter);
        } else {
            field = converter(field);
        }

        kontx.args.fields[key] = field;
    }

    function createError(error) {
        if (error) {
            console.log(error);
        }
        next();
    }

};


text:
define([
    '../views/base/EditableTextCell',
    'jquery',
    'underscore',
    'backbone'
], function (EditableTextCellView, $, _, Backbone) {

    return EditableTextCellView.extend({

        tagName: "div",

        className: "app_config_column_right",

        templateText:
            "<ul id='<%= id %>' class='app_config_radio_button_area'>" +
            "<% _.each(options, function(optionInfo) { %>" +
                "
" +
                    "<input class='app_config_radio_button' " +
                    "<% if(selectedValue === optionInfo.value) { %>" +
                    " checked='checked' " +
                    "<% } %>" +
                    "type='radio' id='<%= optionInfo.value %>' name='inside_outside_behaviors' value='<%= optionInfo.value %>'><label for='<%= optionInfo.value %>' class='app_config_radio_button_label'><%= optionInfo.description %>
" +
                "<% }); %>" +
                "
" +
            "
",

        events: {
            "click input.app_config_radio_button": "clickReact"
        },

        initialize: function(options){
            this.dispatcher = options.dispatcher;
            options.model.capturePriorValue();
        },

        clickReact: function(e){
            var me = this;
            var newValue = e.currentTarget.value;
            var lastValue = me.model.get('priorValue');

            var confirmationHandler = function(id) {
                if (id === 'yes' || id === 'ok') {
                       changeConfirmed();
                } else if (id === 'no' || id === 'cancel') {
                       changeRejected();
                }
            };

            var changeSuccess = function() {
                me.model.capturePriorValue();
            };

            var changeConfirmed = function() {
                me._saveStringApplicationConfig(e, newValue, null, changeSuccess);
            };

            var changeRejected = function() {
                $('input#' + lastValue).prop('checked', true);
            };

            if (newValue !== lastValue) {
                var confirmMsg = '';

                if (newValue === 'ALL_INSIDE') {
                    confirmMsg = 'All listings will have their visibility attribute set to Inside. '
                        + 'Continue?';
                } else if (newValue === 'ALL_OUTSIDE') {
                    confirmMsg = 'All listings will have their visibility attribute set to Outside. '
                        + 'Continue?';
                } else {
                    confirmMsg = 'Enable administrators to individually set the '
                        + 'Inside/Outside visibility attribute for each listing?';
                }

                $(e.target).confirm({
                    trigger: 'manual',
                    placement: 'bottom',
                    container: $(document.body).children('.modal-container'),
                    title: 'Changing Inside/Outside Behavior',
                    content: confirmMsg,
                    ok: changeConfirmed,
                    cancel: changeRejected
                }).confirm('toggle');
            }
        },

        //This renders the description in the text area and also in a read only div
        render: function(){
            var optionsInfo = [
                {value:'ALL_INSIDE', description:'Make All Listings Inside'},
                {value:'ALL_OUTSIDE', description:'Make All Listings Outside'},
                {value:'ADMIN_SELECTED', description:'Manual Selection by Listing'}
            ];

            var value = this.model.get('value');
            var html = _.template(this.templateText, {id: this.model.get("id"), selectedValue: value, options : optionsInfo});

            this.$el.append(html);
        }
    });
});


text:
/*! circular-progress - v0.2.3 - https://github.com/neoziro/circular-progress - © 2016 Greg Bergé MIT License */

(function () {

  // List of 2D context properties
  var ctxProperties = ['fillStyle', 'font', 'globalAlpha', 'globalCompositeOperation',
        'lineCap', 'lineDashOffset', 'lineJoin', 'lineWidth',
        'miterLimit', 'shadowBlur', 'shadowColor', 'shadowOffsetX',
        'shadowOffsetY', 'strokeStyle', 'textAlign', 'textBaseLine'];

  // Autoscale function from https://github.com/component/autoscale-canvas
  var autoscale = function (canvas) {
    var ctx = canvas.getContext('2d'),
    ratio = window.devicePixelRatio || 1;

    if (1 !== ratio) {
      canvas.style.width = canvas.width + 'px';
      canvas.style.height = canvas.height + 'px';
      canvas.width *= ratio;
      canvas.height *= ratio;
      ctx.scale(ratio, ratio);
    }

    return canvas;
  };

  // Utility function to extend a 2D context with some options
  var extendCtx = function (ctx, options) {
    for (var i in options) {
      if (ctxProperties.indexOf(i) === -1) continue;

      ctx[i] = options[i];
    }
  };

  // Main CircularProgress object exposes on global context
  var CircularProgress = this.CircularProgress = function (options) {
    var ctx, i, property;

    options = options || {};
    this.el = document.createElement('canvas');

    this.options = options;

    options.text = options.text || {};
    options.text.value = options.text.value || null;

    ctx = this.el.getContext('2d');

    for (i in ctxProperties) {
      property = ctxProperties[i];
      options[property]= typeof options[property] !== 'undefined' ? options[property] : ctx[property];
    }

    if (options.radius) this.radius(options.radius);
  };

  // Update with a new `percent` value and redraw the canvas
  CircularProgress.prototype.update = function (value) {
    this._percent = value;
    this.draw();
    return this;
  };

  // Specify a new `radius` for the circle
  CircularProgress.prototype.radius = function (value) {
    var size = value * 2;
    this.el.width = size;
    this.el.height = size;
    autoscale(this.el);
    return this;
  };

  // Draw the canvas
  CircularProgress.prototype.draw = function () {
    var tw, text, fontSize,
        options = this.options,
        ctx = this.el.getContext('2d'),
        percent = Math.min(this._percent, 100),
        ratio = window.devicePixelRatio || 1,
        angle = Math.PI * 2 * percent / 100,
        size = this.el.width / ratio,
        half = size / 2,
        x = half,
        y = half;

    ctx.clearRect(0, 0, size, size);

    // Initial circle
    if (options.initial) {
      extendCtx(ctx, options);
      extendCtx(ctx, options.initial);

      ctx.beginPath();
      ctx.arc(x, y, half - ctx.lineWidth, 0, 2 * Math.PI, false);
      ctx.stroke();
    }

    // Progress circle
    extendCtx(ctx, options);

    ctx.beginPath();
    ctx.arc(x, y, half - ctx.lineWidth, 0, angle, false);
    ctx.stroke();

    // Text
    if (options.text) {
      extendCtx(ctx, options);
      extendCtx(ctx, options.text);
    }

    text = options.text.value === null ? (percent | 0) + '%' : options.text.value;
    tw = ctx.measureText(text).width;
    fontSize = ctx.font.match(/(\d+)px/);
    fontSize = fontSize ? fontSize[1] : 0;

    ctx.fillText(text, x - tw / 2 + 1, y + fontSize / 2 - 1);

    return this;
  };

}).call(this);