<commit_before>/**
 * Created by michael on 24/07/15.
 */

define(['socket.io'],function(io){

    function ConnectionController(app,server){
        this.app = app;
        this.socket = io(server);
        this.id = -1;
        this.scanCallback = null;
        this.friendCallback = null;

        this.socket.on('sync',this.onConnect.bind(this));

        this.socket.on('loggedIn',this.onLoggedIn.bind(this));
        this.socket.on('scanResult',this.onScanResult.bind(this));
        this.socket.on('update',this.onUpdate.bind(this));
        this.socket.on('friendAdded',this.onFriendAdded.bind(this));
    }

    ConnectionController.prototype.onConnect = function(data){
        this.id = data.id;

        this.app.injectData('RobotPart',data.items);

        if(this.app.user === null){
            this.register();
        }else{
            this.login();
        }
    };

    ConnectionController.prototype.onLoggedIn = function(data){
        this.app.injectData('User',data.user);
        this.app.injectData('Robot',data.robot);
        this.app.injectData('Item',data.inventory);
        this.app.injectData('Friend',data.friends);

        this.app.saveUser(data.user.id);

        this.app.startState('Menu');
    };

    ConnectionController.prototype.onScanResult = function(data){
        if(this.scanCallback){
            this.scanCallback(data);
            this.scanCallback = null;
        }
    };

    ConnectionController.prototype.onUpdate = function(data){
        this.app.injectData('Item',data.inventory);
        this.app.injectData('Friend',data.friendlist);

        this.app.game.state.getCurrentState().onDataUpdate();
    };

    ConnectionController.prototype.register = function(){
        this.socket.emit('register');
    };

    ConnectionController.prototype.login = function(){
        this.socket.emit('login',{
            user: this.app.user
        });
    };

    ConnectionController.prototype.sendCode = function(code,callback){
        console.log(code);

        this.scanCallback = callback;
        this.socket.emit('scan',{
            code: code
        });
    };

    ConnectionController.prototype.onFriendAdded= function(data){
        if(this.friendCallback){
            this.friendCallback(data);
            this.friendCallback = null;
        }
    };

    ConnectionController.prototype.addFriend = function(user, callback){

        this.friendCallback = callback;
        this.socket.emit('addFriend', {
            username: user
        });
    };

    return ConnectionController;
});<commit_msg>Verhindert kaputte logintokens<commit_after>/**
 * Created by michael on 24/07/15.
 */

define(['socket.io'],function(io){

    function ConnectionController(app,server){
        this.app = app;
        this.socket = io(server);
        this.id = -1;
        this.scanCallback = null;
        this.friendCallback = null;

        this.socket.on('sync',this.onConnect.bind(this));

        this.socket.on('loggedIn',this.onLoggedIn.bind(this));
        this.socket.on('scanResult',this.onScanResult.bind(this));
        this.socket.on('update',this.onUpdate.bind(this));
        this.socket.on('friendAdded',this.onFriendAdded.bind(this));
    }

    ConnectionController.prototype.onConnect = function(data){
        this.id = data.id;

        this.app.injectData('RobotPart',data.items);

        if(this.app.user === null){
            this.register();
        }else{
            this.login();
        }
    };

    ConnectionController.prototype.onLoggedIn = function(data){
        this.app.saveUser(data.user.id);

        this.app.injectData('User',data.user);
        this.app.injectData('Robot',data.robot);
        this.app.injectData('Item',data.inventory);
        this.app.injectData('Friend',data.friends);

        this.app.startState('Menu');
    };

    ConnectionController.prototype.onScanResult = function(data){
        if(this.scanCallback){
            this.scanCallback(data);
            this.scanCallback = null;
        }
    };

    ConnectionController.prototype.onUpdate = function(data){
        this.app.injectData('Item',data.inventory);
        this.app.injectData('Friend',data.friendlist);

        this.app.game.state.getCurrentState().onDataUpdate();
    };

    ConnectionController.prototype.register = function(){
        this.socket.emit('register');
    };

    ConnectionController.prototype.login = function(){
        this.socket.emit('login',{
            user: this.app.user
        });
    };

    ConnectionController.prototype.sendCode = function(code,callback){
        console.log(code);

        this.scanCallback = callback;
        this.socket.emit('scan',{
            code: code
        });
    };

    ConnectionController.prototype.onFriendAdded= function(data){
        if(this.friendCallback){
            this.friendCallback(data);
            this.friendCallback = null;
        }
    };

    ConnectionController.prototype.addFriend = function(user, callback){

        this.friendCallback = callback;
        this.socket.emit('addFriend', {
            username: user
        });
    };

    return ConnectionController;
});<|endoftext|>


<commit_before>import {
  MAIN_BRICK,
  PRIMITIVE,
  SELECTABLE_PIPE
} from '../../utils/componentNames'

export const evaluate = (workspace, elementId) => {
  const element = workspace.entities[elementId]
  let newEntities = workspace.entities
  let newUnitTests = workspace.unitTests

  if(element.componentName == SELECTABLE_PIPE) {
    const { input, output } = element
    const inputElement = workspace.entities[input.elementId]

    if(inputElement.componentName == PRIMITIVE) {
      newEntities = Object.assign({}, workspace.entities, {
        [elementId]: {
          ...element,
          type: inputElement.type,
          value: inputElement.value
        }
      })
    }

    if(inputElement.componentName == MAIN_BRICK) {
      const slotIndex = inputElement.inputSlots.findIndex((inputSlot) =>
        inputSlot.id == input.slotId)

      newUnitTests = workspace.unitTests.map((unitTest) => {
        const testInputId = unitTest.testInputIds[slotIndex]
        const testInput = workspace.entities[testInputId]

        return {
          ...unitTest,
          values: {
            ...unitTest.values,
            [elementId]: {
              type: testInput.type,
              value: testInput.value
            }
          }
        }
      })
    }
  }

  return Object.assign({}, workspace, {
    ...workspace,
    entities: newEntities,
    unitTests: newUnitTests
  })
}
<commit_msg>Extract 'evalNewPipe' function<commit_after>import {
  MAIN_BRICK,
  PRIMITIVE,
  SELECTABLE_PIPE
} from '../../utils/componentNames'

export const evaluate = (workspace, elementId) => {
  const element = workspace.entities[elementId]
  let newEntities = {}
  let newUnitTests = {}

  switch (element.componentName) {
    case SELECTABLE_PIPE:
      const newWorkspace = evalNewPipe(workspace, element)
      newEntities = newWorkspace.newEntities
      newUnitTests = newWorkspace.newUnitTests

      break;
    default:
      newEntities = workspace.entities
      newUnitTests = workspace.newUnitTests
  }

  return Object.assign({}, workspace, {
    ...workspace,
    entities: newEntities,
    unitTests: newUnitTests
  })
}

const evalNewPipe = (workspace, element) => {
  const { input, output } = element
  const inputElement = workspace.entities[input.elementId]

  let newEntities = workspace.entities
  let newUnitTests = workspace.unitTests

  if(inputElement.componentName == PRIMITIVE) {
    newEntities = Object.assign({}, workspace.entities, {
      [element.id]: {
        ...element,
        type: inputElement.type,
        value: inputElement.value
      }
    })
  }

  if(inputElement.componentName == MAIN_BRICK) {
    const slotIndex = inputElement.inputSlots.findIndex((inputSlot) =>
      inputSlot.id == input.slotId)

    newUnitTests = workspace.unitTests.map((unitTest) => {
      const testInputId = unitTest.testInputIds[slotIndex]
      const testInput = workspace.entities[testInputId]

      return {
        ...unitTest,
        values: {
          ...unitTest.values,
          [element.id]: {
            type: testInput.type,
            value: testInput.value
          }
        }
      }
    })
  }

  return {
    newEntities,
    newUnitTests
  }
}
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
sap.ui.define(['jquery.sap.global', './InputBaseRenderer', 'sap/ui/core/Renderer'],
	function(jQuery, InputBaseRenderer, Renderer) {
		"use strict";

		/**
		 * ComboBoxBase renderer.
		 *
		 * @namespace
		 */
		var ComboBoxBaseRenderer = Renderer.extend(InputBaseRenderer);

		/**
		 * CSS class to be applied to the root element of the ComboBoxBase.
		 *
		 * @readonly
		 * @const {string}
		 */
		ComboBoxBaseRenderer.CSS_CLASS = "sapMComboBoxBase";

		/**
		 * Add attributes to the input element.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.writeInnerAttributes = function(oRm, oControl) {
			oRm.writeAttribute("autocomplete", "off");
			oRm.writeAttribute("autocorrect", "off");
			oRm.writeAttribute("autocapitalize", "off");
		};

		/**
		 * Retrieves the ARIA role for the control.
		 * To be overwritten by subclasses.
		 *
		 */
		ComboBoxBaseRenderer.getAriaRole = function() {
			return "combobox";
		};

		/**
		 * Retrieves the accessibility state of the control.
		 * To be overwritten by subclasses.
		 *
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.getAccessibilityState = function(oControl) {
			var mAccessibilityState = sap.m.InputBaseRenderer.getAccessibilityState.call(this, oControl);

			mAccessibilityState.expanded = oControl.isOpen();
			mAccessibilityState.autocomplete = "both";
			return mAccessibilityState;
		};

		/**
		 * Add extra styles for input container.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.addOuterStyles = function(oRm, oControl) {
			oRm.addStyle("max-width", oControl.getMaxWidth());
		};

		/**
		 * Add classes to the ComboBox.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.addOuterClasses = function(oRm, oControl) {
			var CSS_CLASS = ComboBoxBaseRenderer.CSS_CLASS;

			oRm.addClass(CSS_CLASS);
			oRm.addClass(CSS_CLASS + "Input");

			if (!oControl.getEnabled()) {
				oRm.addClass(CSS_CLASS + "Disabled");
			}

			if (!oControl.getEditable()) {
				oRm.addClass(CSS_CLASS + "Readonly");
			}
		};

		/**
		 * Add inner classes to the ComboBox's input element.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.addInnerClasses = function(oRm, oControl) {
			var CSS_CLASS = ComboBoxBaseRenderer.CSS_CLASS;
			oRm.addClass(CSS_CLASS + "InputInner");

			if (!oControl.getEditable()) {
				oRm.addClass(CSS_CLASS + "InputInnerReadonly");
			}
		};

		/**
		 * Renders the ComboBox's arrow, using the provided {@link sap.ui.core.RenderManager}.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.writeInnerContent = function(oRm, oControl) {
			this.renderButton(oRm, oControl);
		};

		/**
		 * Renders the combo box button, using the provided {@link sap.ui.core.RenderManager}.
		 * To be overwritten by subclasses.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.renderButton = function(oRm, oControl) {
			var sId = oControl.getId(),
				sButtonId = sId + "-arrow",
				sButtonLabelId = sId + "-buttonlabel",
				oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m");

			oRm.write('<button tabindex="-1"');
			oRm.writeAttribute("id", sButtonId);
			oRm.writeAttribute("aria-labelledby", sButtonLabelId);
			oRm.addClass(ComboBoxBaseRenderer.CSS_CLASS + "Arrow");
			oRm.writeClasses();
			oRm.write(">");
			oRm.write("");
			oRm.write(oRb.getText("COMBOBOX_BUTTON"));
			oRm.write("");
			oRm.write("</button>");
		};

		return ComboBoxBaseRenderer;

	}, /* bExport= */ true);
<commit_msg>[INTERNAL][FEATURE] sap.m.ComboBoxBaseRenderer: add a render hook to allow more customizations in subclasses<commit_after>/*!
 * ${copyright}
 */
sap.ui.define(['jquery.sap.global', './InputBaseRenderer', 'sap/ui/core/Renderer'],
	function(jQuery, InputBaseRenderer, Renderer) {
		"use strict";

		/**
		 * ComboBoxBase renderer.
		 *
		 * @namespace
		 */
		var ComboBoxBaseRenderer = Renderer.extend(InputBaseRenderer);

		/**
		 * CSS class to be applied to the root element of the ComboBoxBase.
		 *
		 * @readonly
		 * @const {string}
		 */
		ComboBoxBaseRenderer.CSS_CLASS = "sapMComboBoxBase";

		/**
		 * Add attributes to the input element.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.writeInnerAttributes = function(oRm, oControl) {
			oRm.writeAttribute("autocomplete", "off");
			oRm.writeAttribute("autocorrect", "off");
			oRm.writeAttribute("autocapitalize", "off");
		};

		/**
		 * Retrieves the ARIA role for the control.
		 * To be overwritten by subclasses.
		 *
		 */
		ComboBoxBaseRenderer.getAriaRole = function() {
			return "combobox";
		};

		/**
		 * Retrieves the accessibility state of the control.
		 * To be overwritten by subclasses.
		 *
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.getAccessibilityState = function(oControl) {
			var mAccessibilityState = sap.m.InputBaseRenderer.getAccessibilityState.call(this, oControl);

			mAccessibilityState.expanded = oControl.isOpen();
			mAccessibilityState.autocomplete = "both";
			return mAccessibilityState;
		};

		/**
		 * Add extra styles for input container.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.addOuterStyles = function(oRm, oControl) {
			oRm.addStyle("max-width", oControl.getMaxWidth());
		};

		/**
		 * Add classes to the ComboBox.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.addOuterClasses = function(oRm, oControl) {
			var CSS_CLASS = ComboBoxBaseRenderer.CSS_CLASS;

			oRm.addClass(CSS_CLASS);
			oRm.addClass(CSS_CLASS + "Input");

			if (!oControl.getEnabled()) {
				oRm.addClass(CSS_CLASS + "Disabled");
			}

			if (!oControl.getEditable()) {
				oRm.addClass(CSS_CLASS + "Readonly");
			}
		};

		/**
		 * Add inner classes to the ComboBox's input element.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.addInnerClasses = function(oRm, oControl) {
			var CSS_CLASS = ComboBoxBaseRenderer.CSS_CLASS;
			oRm.addClass(CSS_CLASS + "InputInner");

			if (!oControl.getEditable()) {
				oRm.addClass(CSS_CLASS + "InputInnerReadonly");
			}
		};

		/**
		 * Renders the ComboBox's arrow, using the provided {@link sap.ui.core.RenderManager}.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.writeInnerContent = function(oRm, oControl) {
			this.renderButton(oRm, oControl);
		};

		/**
		 * Renders the combo box button, using the provided {@link sap.ui.core.RenderManager}.
		 * To be overwritten by subclasses.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.renderButton = function(oRm, oControl) {
			var sId = oControl.getId(),
				sButtonId = sId + "-arrow",
				sButtonLabelId = sId + "-buttonlabel",
				oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m");

			oRm.write('<button tabindex="-1"');
			oRm.writeAttribute("id", sButtonId);
			oRm.writeAttribute("aria-labelledby", sButtonLabelId);
			this.addButtonClasses(oRm, oControl);
			oRm.writeClasses();
			oRm.write(">");
			oRm.write("");
			oRm.write(oRb.getText("COMBOBOX_BUTTON"));
			oRm.write("");
			oRm.write("</button>");
		};

		/**
		 * Add CSS classes to the combo box arrow button, using the provided {@link sap.ui.core.RenderManager}.
		 * To be overwritten by subclasses.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered.
		 */
		ComboBoxBaseRenderer.addButtonClasses = function(oRm, oControl) {
			oRm.addClass(ComboBoxBaseRenderer.CSS_CLASS + "Arrow");
		};

		return ComboBoxBaseRenderer;

	}, /* bExport= */ true);<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define([],
	function() {
		"use strict";

		/**
		 * PagingButton renderer
		 * @namespace
		 */
		var PagingButtonRenderer = {};

		PagingButtonRenderer.render = function (oRm, oControl) {
			var nextButton = oControl._getNextButton(),
				prevButton = oControl._getPreviousButton();

			oRm.write("<div");
			oRm.writeControlData(oControl);
			oRm.addClass("sapMPagingButton");
			oRm.writeClasses();
			oRm.write(">");
			oRm.renderControl(prevButton);
			oRm.renderControl(nextButton);
			oRm.write("</div>");
		};

		return PagingButtonRenderer;

	}, /* bExport= */ true);
<commit_msg>[INTERNAL] sap.m.PagingButton: Switched to semantic renderer<commit_after>/*!
 * ${copyright}
 */

sap.ui.define([],
	function() {
		"use strict";

		/**
		 * PagingButton renderer
		 * @namespace
		 */
		var PagingButtonRenderer = {
			apiVersion: 2
		};

		PagingButtonRenderer.render = function (oRm, oControl) {
			var nextButton = oControl._getNextButton(),
				prevButton = oControl._getPreviousButton();

			oRm.openStart("div", oControl);
			oRm.class("sapMPagingButton");
			oRm.openEnd();
			oRm.renderControl(prevButton);
			oRm.renderControl(nextButton);
			oRm.close("div");
		};

		return PagingButtonRenderer;

	}, /* bExport= */ true);
<|endoftext|>


<commit_before>/**
 * catharsis 0.0.1
 * A parser for Google Closure Compiler type expressions, powered by PEG.js.
 *
 * @author Jeff Williams <jeffrey.l.williams@gmail.com>
 * @license MIT License (http://opensource.org/licenses/mit-license.php/)
 */

'use strict';

var parse = require('./lib/parser').parse;

var cache = {};

function cachedParse(string) {
	if (!cache[string]) {
		cache[string] = parse(string);
	}

	return cache[string];
}

function Catharsis() {}

Catharsis.prototype.parse = function(string, callback) {
	process.nextTick(function() {
		try {
			callback(null, cachedParse(string));
		}
		catch(e) {
			callback('unable to parse the type ' + string + ': ' + e.message);
		}
	});
};

Catharsis.prototype.parseSync = function(string) {
	return cachedParse(string);
};

module.exports = new Catharsis();
<commit_msg>use a process.nextTick shim if necessary/possible<commit_after>/**
 * catharsis 0.0.1
 * A parser for Google Closure Compiler type expressions, powered by PEG.js.
 *
 * @author Jeff Williams <jeffrey.l.williams@gmail.com>
 * @license MIT License <http://opensource.org/licenses/mit-license.php/>
 */

'use strict';

var parse = require('./lib/parser').parse;

var cache = {};

function cachedParse(string) {
	if (!cache[string]) {
		cache[string] = parse(string);
	}

	return cache[string];
}

var nextTick = (function() {
	if (process && process.nextTick) {
		return process.nextTick;
	} else if (setTimeout) {
		return function(callback) {
			setTimeout(callback, 0);
		};
	} else {
		// better safe than sorry
		return function(callback) {
			callback('Your JavaScript environment does not support the parse() method. ' +
				'Please call parseSync() instead.');
		};
	}
})();

function Catharsis() {}

Catharsis.prototype.parse = function(string, callback) {
	nextTick(function() {
		try {
			callback(null, cachedParse(string));
		}
		catch(e) {
			callback('unable to parse the type ' + string + ': ' + e.message);
		}
	});
};

Catharsis.prototype.parseSync = function(string) {
	return cachedParse(string);
};

module.exports = new Catharsis();
<|endoftext|>


<commit_before>const hooks = require('feathers-hooks-common');
const auth = require('@feathersjs/authentication');
const globalHooks = require('../../../hooks');

exports.before = {
	all: [auth.hooks.authenticate('jwt')],
	find: [hooks.disallow()],
	get: [hooks.disallow()],
	create: [hooks.disallow()],
	update: [hooks.disallow()],
	patch: [
		globalHooks.restrictToCurrentSchool,
	],
	remove: [hooks.disallow()],
};

exports.after = {
	all: [],
	find: [],
	get: [],
	create: [],
	update: [],
	patch: [],
	remove: [],
};
<commit_msg>use post instead of patch<commit_after>const hooks = require('feathers-hooks-common');
const auth = require('@feathersjs/authentication');
const globalHooks = require('../../../hooks');

const testHook = (hook) => {
	return Promise.resolve(hook);
}

exports.before = {
	all: [auth.hooks.authenticate('jwt')],
	find: [hooks.disallow()],
	get: [hooks.disallow()],
	create: [testHook, globalHooks.restrictToCurrentSchool],
	update: [hooks.disallow()],
	patch: [hooks.disallow()],
	remove: [hooks.disallow()],
};

exports.after = {
	all: [],
	find: [],
	get: [],
	create: [],
	update: [],
	patch: [],
	remove: [],
};
<|endoftext|>


<commit_before>'use strict'

import { Router } from 'react-router'
import { sync, checkToken } from 'shared/actions/AuthActions'

export default function (nextState, transition) {
  this.redux.dispatch(sync())
  this.redux.dispatch(checkToken())
  const isAuthenticated = this.redux.getState().auth.isAuthenticated
  const verified = this.redux.getState().auth.verified

  //console.log('isAuthenticated', isAuthenticated)
  //console.log('verified', verified)

  if (!isAuthenticated)
    transition.to(
      '/login',
      null,
      { nextPathname: nextState.location.pathname }
    )

  if (!verified)
    transition.to(
      '/',
      null,
      {}
    )
}

function check (token) {
  return true
}

<commit_msg>clean up<commit_after>'use strict'

import { Router } from 'react-router'
import { sync, checkToken } from 'shared/actions/AuthActions'

export default function (nextState, transition) {
  this.redux.dispatch(sync())
  this.redux.dispatch(checkToken())
  const isAuthenticated = this.redux.getState().auth.isAuthenticated
  const verified = this.redux.getState().auth.verified

  //console.log('isAuthenticated', isAuthenticated)
  //console.log('verified', verified)

  if (!isAuthenticated)
    transition.to(
      '/login',
      null,
      { nextPathname: nextState.location.pathname }
    )

  if (!verified)
    transition.to(
      '/',
      null,
      {}
    )
}
<|endoftext|>


<commit_before>/* ==========================================================================
   jquery.cf_notifier
   ========================================================================== */

'use strict';

var $ = require( 'jquery' );
var handlebars = require( 'handlebars' );

var _notifierTemplate = '
' +
  '' +
  '
{{{ message }}}
' +
  '
';

var _notifier = {
  defaults: {
    message:        'There was an error with your submission',
    state:          'error',
    speed:          200,
    easing:         'swing',
    template:       _notifierTemplate,
    insertLocation: 'prependTo',
    insertTarget:   null,
    input:          null,
    onRender:       null,
    onClearAll:     null,
    onDestroy:      null
  },

  existing: false,

  /**
   * Generate a string of HTML from the plugin's settings
   * @returns {string} The expanded HTML string
  */
  _generateHTML: function() {
    var settings = _notifier.settings;
    var icon = {
      error:   'delete',
      success: 'approved',
      warning: 'error'
    };
    var data = {
      message: settings.message,
      state:   settings.state,
      icon:    icon[settings.state]
    };
    var template = handlebars.compile( settings.template );

    return template( data );
  },

  // Clear any previously created notifications
  _clearExisting: function( callback ) {
    $( _notifier.existing ).slideUp( {
        duration: _notifier.settings.speed,
        easing:   _notifier.settings.easing,
        complete: function() {
          $( this ).remove();
          _notifier.existing = false;
          if ( callback ) {
            callback();
          }
        }
    } );
  },

  // Create a notification
  _notify: function( elem ) {
    var html = _notifier._generateHTML();
    $( html )[_notifier.settings.insertLocation]( elem )
      .slideDown( {
        duration: _notifier.settings.speed,
        easing:   _notifier.settings.easing,
        complete: function() {
          _notifier.existing = this;
          if ( _notifier.settings.onRender ) {
            _notifier.settings.onRender.call( this );
          }
        }
      } );
  },

  // Listen for custom cf_notifier:notify event
  _initNotifyListener: function() {
    _notifier.elem.on( 'cf_notifier:notify', function( event, options ) {
      _notifier.settings = $.extend( {}, _notifier.settings, options );
      var $target = _notifier.settings.insertTarget || $( this );
      if ( _notifier.existing ) {
        _notifier._clearExisting( function() {
          _notifier._notify( $target );
        } );
      } else {
        _notifier._notify( $target );
      }
    } );
  },

  // Listen for custom cf_notifier:clear event
  _initClearListener: function() {
    _notifier.elem.on( 'cf_notifier:clear', function( event, options ) {
      _notifier.settings = $.extend( {}, _notifier.settings, options );
      if ( _notifier.existing ) {
        _notifier._clearExisting( function() {
          if ( _notifier.settings.onClearAll ) {
            _notifier.settings.onClearAll.call( this );
          }
        } );
      } else if ( _notifier.settings.onClearAll ) {
        _notifier.settings.onClearAll.call( this );
      }
    } );
  },

  // Remove all custom cf_notifier event listeners
  _rmCFNotifierListeners: function() {
    _notifier.elem.off( 'cf_notifier' );
  },

  init: function( options ) {
    return this.each( function() {
      _notifier.elem = $( this );
      _notifier.settings = $.extend( {}, _notifier.defaults, options );

      if ( _notifier.elem.length > 0 ) {
        _notifier._initNotifyListener();
        _notifier._initClearListener();
      }
    } );
  },

  destroy: function() {
    return this.each( function() {
      _notifier._rmCFNotifierListeners();

      if ( _notifier.existing ) {
        _notifier._clearExisting( function() {
          if ( _notifier.settings.onDestroy ) {
            _notifier.settings.onDestroy.call( this );
          }
          _notifier.settings = [];
        } );
      } else {
        if ( _notifier.settings.onDestroy ) {
          _notifier.settings.onDestroy.call( this );
        }
        _notifier.settings = [];
      }
    } );
  }
};

function init() {
  $.fn.cf_notifier = function() {
    var options;
    var method = arguments[0];

    if ( _notifier[method] ) {
      method = _notifier[method];
      options = Array.prototype.slice.call( arguments, 1 );
    } else if ( typeof method === 'object' || !method ) {
      method = _notifier.init;
      options = arguments;
    } else {
      $.error( 'Method "' + method + '"" does not exist in the cf__notifier plugin' );
      return this;
    }

    return method.apply( this, options );
  };
}

module.exports = { init: init };
<commit_msg>Review Edits<commit_after>/* ==========================================================================
   jquery.cf_notifier
   ========================================================================== */

'use strict';

var $ = require( 'jquery' );
var handlebars = require( 'handlebars' );

var _notifierTemplate = '
' +
  '' +
  '
{{{ message }}}
' +
  '
';

var _notifier = {
  defaults: {
    message:        'There was an error with your submission',
    state:          'error',
    duration:        200,
    easing:         'swing',
    template:       _notifierTemplate,
    insertLocation: 'prependTo',
    insertTarget:   null,
    input:          null,
    onRender:       null,
    onClearAll:     null,
    onDestroy:      null
  },

  existing: false,

  /**
   * Generate a string of HTML from the plugin's settings
   * @returns {string} The expanded HTML string
  */
  _generateHTML: function() {
    var settings = _notifier.settings;
    var icon = {
      error:   'delete',
      success: 'approved',
      warning: 'error'
    };
    var data = {
      message: settings.message,
      state:   settings.state,
      icon:    icon[settings.state]
    };
    var template = handlebars.compile( settings.template );

    return template( data );
  },

  // Clear any previously created notifications
  _clearExisting: function( callback ) {
    var settings = _notifier.settings;
    $( _notifier.existing ).slideUp( {
        duration: settings.duration,
        easing:   settings.easing,
        complete: function() {
          $( this ).remove();
          _notifier.existing = false;
          if ( callback ) {
            callback();
          }
        }
    } );
  },

  // Create a notification
  _notify: function( elem ) {
    var settings = _notifier.settings;
    var html = _notifier._generateHTML();
    $( html )[settings.insertLocation]( elem )
      .slideDown( {
        duration: settings.duration,
        easing:   settings.easing,
        complete: function() {
          _notifier.existing = this;
          if ( settings.onRender ) {
            settings.onRender.call( this );
          }
        }
      } );
  },

  // Listen for custom cf_notifier:notify event
  _initNotifyListener: function() {
    _notifier.elem.on( 'cf_notifier:notify', function( event, options ) {
      _notifier.settings = $.extend( {}, _notifier.settings, options );
      var $target = _notifier.settings.insertTarget || $( this );
      if ( _notifier.existing ) {
        _notifier._clearExisting( function() {
          _notifier._notify( $target );
        } );
      } else {
        _notifier._notify( $target );
      }
    } );
  },

  // Listen for custom cf_notifier:clear event
  _initClearListener: function() {
    _notifier.elem.on( 'cf_notifier:clear', function( event, options ) {
      _notifier.settings = $.extend( {}, _notifier.settings, options );
      if ( _notifier.existing ) {
        _notifier._clearExisting( function() {
          if ( _notifier.settings.onClearAll ) {
            _notifier.settings.onClearAll.call( this );
          }
        } );
      } else if ( _notifier.settings.onClearAll ) {
        _notifier.settings.onClearAll.call( this );
      }
    } );
  },

  // Remove all custom cf_notifier event listeners
  _rmCFNotifierListeners: function() {
    _notifier.elem.off( 'cf_notifier' );
  },

  init: function( options ) {
    return this.each( function() {
      _notifier.elem = $( this );
      _notifier.settings = $.extend( {}, _notifier.defaults, options );

      if ( _notifier.elem.length > 0 ) {
        _notifier._initNotifyListener();
        _notifier._initClearListener();
      }
    } );
  },

  destroy: function() {
    return this.each( function() {
      _notifier._rmCFNotifierListeners();

      if ( _notifier.existing ) {
        _notifier._clearExisting( function() {
          if ( _notifier.settings.onDestroy ) {
            _notifier.settings.onDestroy.call( this );
          }
          _notifier.settings = [];
        } );
      } else {
        if ( _notifier.settings.onDestroy ) {
          _notifier.settings.onDestroy.call( this );
        }
        _notifier.settings = [];
      }
    } );
  }
};

function init() {
  $.fn.cf_notifier = function() {
    var options;
    var method = arguments[0];

    if ( _notifier[method] ) {
      method = _notifier[method];
      options = Array.prototype.slice.call( arguments, 1 );
    } else if ( typeof method === 'object' || !method ) {
      method = _notifier.init;
      options = arguments;
    } else {
      $.error( 'Method "' + method + '"" does not exist in the cf__notifier plugin' );
      return this;
    }

    return method.apply( this, options );
  };
}

module.exports = { init: init };
<|endoftext|>


<commit_before>import React from 'react'

export default ({ fields: { password, confirm_password }, ...props}) => {
  return (
    <form onSubmit={props.handleSubmit}>

Enter new password

        <input type='password' className={password.touched && password.error ? 'red' : ''} {...password}></input>
        {password.touched && password.error &&
{password.error}
}

Confirm new password

        <input type='password' className={confirm_password.touched && confirm_password.error ? 'red' : ''} {...confirm_password}></input>
        {confirm_password.touched && confirm_password.error &&
{confirm_password.error}
}

      <button className='change-password-button' type='submit'>Submit</button>
    </form>
  )
}

// TODO: map inputs
// TODO: show succesful response to changing password
<commit_msg>Map inputs in password change form.<commit_after>import React from 'react'

const form_fields = [ 'password', 'confirm_password' ]

export default ({fields, handleSubmit}) => {
  return (
    <form onSubmit={handleSubmit}>

        {form_fields.map(input_maker(fields))}

      <button className='change-password-button' type='submit'>Submit</button>
    </form>
  )
}

const input_maker = fields => field =>

Enter new password

    <input type='password' className={fields[field].touched && fields[field].error ? 'red' : ''} {...fields[field]}></input>
    {fields[field].touched && fields[field].error &&
{fields[field].error}
}

// TODO: show succesful response to changing password
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'

import { fetchContentItem } from '~/actions'

import ContentPickerWidget from '~/components/Content/Select/Widget'

class RefWidget extends Component {
  state = {}

  handleChange = item => {
    this.props.onChange(item.id)
  }

  componentWillReceiveProps(newProps) {
    if (newProps.value) {
      this.props.fetchContentItem(newProps.value)
    }
  }

  render() {
    const { $category: categoryId, $subtype: subtype, type } = this.props.schema
    if (type !== 'string' || subtype !== 'ref') {
      return null
    }

    const itemId = this.props.value
    const contentItem = itemId && this.props.contentItems ? this.props.contentItems[itemId] : null
    if (itemId && !contentItem) {
      // item is not fetched yet, will rerender when it's done
      return null
    }

    return (
      <ContentPickerWidget
        inputId={this.props.id}
        itemId={itemId}
        contentItem={contentItem}
        categoryId={categoryId}
        onChange={this.handleChange}
        placeholder={this.props.placeholder || `Pick ${categoryId}`}
      />
    )
  }
}

const mapStateToProps = state => ({ contentItems: state.content.itemsById })
const mapDispatchToProps = { fetchContentItem }

export default connect(mapStateToProps, mapDispatchToProps)(RefWidget)
<commit_msg>fix unneeded fetches<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'

import { fetchContentItem } from '~/actions'

import ContentPickerWidget from '~/components/Content/Select/Widget'

class RefWidget extends Component {
  handleChange = item => {
    this.props.onChange(item.id)
  }

  componentWillReceiveProps(newProps) {
    if (newProps.value && newProps.value !== this.props.value) {
      this.props.fetchContentItem(newProps.value)
    }
  }

  render() {
    const { $category: categoryId, $subtype: subtype, type } = this.props.schema
    if (type !== 'string' || subtype !== 'ref') {
      return null
    }

    const itemId = this.props.value
    const contentItem = itemId && this.props.contentItems ? this.props.contentItems[itemId] : null
    if (itemId && !contentItem) {
      // item is not fetched yet, will rerender when it's done
      return null
    }

    return (
      <ContentPickerWidget
        inputId={this.props.id}
        itemId={itemId}
        contentItem={contentItem}
        categoryId={categoryId}
        onChange={this.handleChange}
        placeholder={this.props.placeholder || `Pick ${categoryId}`}
      />
    )
  }
}

const mapStateToProps = state => ({ contentItems: state.content.itemsById })
const mapDispatchToProps = { fetchContentItem }

export default connect(mapStateToProps, mapDispatchToProps)(RefWidget)
<|endoftext|>


<commit_before>
/**
  @class

  `XT.Model` is an abstract class designed to operate with `XT.DataSource`.
  It should be subclass for any specific implentation. Subtypes should
  include a `recordType` the data source will use retreive the record.

  To create a new model include 'insert' in the options like so:
    XM.Contact = XT.Model.extend({recordType: 'XM.Contact'});
    m = new XM.Contact({insert: true});

  To load an existing record include a guid in the options like so:
    XM.Contact = XT.Model.extend({recordType: 'XM.Contact'});
    m = new XM.Contact({guid: 1});
    m.fetch();

    OR

    XM.Contact = XT.Model.extend({recordType: 'XM.Contact'});
    m = XM.Contact();
    m.fetch({id: 1});

  @extends Backbone.RelationalModel
  @param {Object} attributes
  @param {Object} options
*/
XT.Model = Backbone.RelationalModel.extend(
  /** @scope XT.Model.prototype */ {

  idAttribute: "guid",

  /**
  Specify the name of a data source model here.
  */
  recordType: null,

  initialize: function() {
    var options = arguments[1];

    // initialize for inserted record
    if (options && options.insert) {
      this.attributes.dataState = 'inserted';
      this.fetchId();
    }

    this._dataSource = XT.dataSource;
  },

  /**
  Change dataState to 'updated'.
  */
  attributeChanged: function() {
    if (this.get('dataState') === 'read') {
      this.set('dataState', 'updated');
    }
  },

  /**
  Reimplemented. A model is new if the dataState is "inserted".
  */
  isNew: function() {
    return this.get('dataState') === 'inserted';
  },

  /**
  Returns true when dataState is 'inserted' or 'updated'.
  */
  isDirty: function() {
    return this.get('dataState') === 'inserted' || this.get('dataState') === 'updated';
  },

  /**
  Reimplemented to handle state change.
  */
  fetch: function(options) {
    // turn off state handling
    this.off('change', this.attributeChanged);
    this.set('dataState', 'busy');

    // add call back to turn state handling back on after fetch
    if (options === undefined) options = {};
    var that = this;
    var success = options.success;
    options.fetched = true;
    options.success = function(resp, status, xhr) {
      that.on('change', that.attributeChanged);
      if (success) success(model, resp, options);
    };

    return Backbone.Model.prototype.fetch.call(this, options);
  },

  /**
  Fetch a new guid from the server.
  */
  fetchId: function() {
    var that = this;
    var options = {};
    var success = options.success;

    // fetch id
    options.success = function(resp, status, xhr) {
      this.set('guid', resp);
    };
    this._dataSource.dispatch('XT.Record', 'fetchId', this.recordType, options);
  },

  /**
  Reimplemented.
  */
  set: function( key, value, options ) {
    if (_.isObject(key) && value.fetched) this.set('dataState', 'read');
    return Backbone.RelationalModel.prototype.set.call(this, key, value, options);
  },

  /**
  Reimplemented.
  */
  destroy: function(options) {
    this.set('dataState', 'deleted');
    return Backbone.Model.prototype.destroy.call(this, options);
  },

  /**
  Overload: sync to xtuple datasource.
  */
  sync: function(method, model, options) {
    var recordType = model.recordType;
    var id = options.id || this.id;
    var success = options.success;

    // read
    if (method === 'read' && recordType && id && success) {
      return this._dataSource.retrieveRecord(recordType, id, options);

    // write
    } else if (method == 'create' || method == 'update' || method === 'delete') {
      return this._dataSource.commitRecord(model, options);
    }

    return false;
  },

  /**
  Validate all required fields if no attributes specified.
  */
  validate: function(attributes, options) {
    // check state
    if (this.get('dataState') === 'busy' && !options.fetched) {
      return 'Record is busy';
    } else if (this.get('dataState') === 'deleted') {
      return 'Can not alter deleted record';
    }

    if (!attributes) {  // all
      // check required
      var required = this.required || [];
      var i;

      for (i = 0; i < required.length; i++) {
        if (!this.has(required[i])) {
          return "'" + required[i] + " is required.";
        }
      }
    }
  },

  /** @private */
  _dataSource: null,

});

<commit_msg>some work on state control on save.<commit_after>
/**
  @class

  `XT.Model` is an abstract class designed to operate with `XT.DataSource`.
  It should be subclass for any specific implentation. Subtypes should
  include a `recordType` the data source will use retreive the record.

  To create a new model include 'insert' in the options like so:
    XM.Contact = XT.Model.extend({recordType: 'XM.Contact'});
    m = new XM.Contact({insert: true});

  To load an existing record include a guid in the options like so:
    XM.Contact = XT.Model.extend({recordType: 'XM.Contact'});
    m = new XM.Contact({guid: 1});
    m.fetch();

    OR

    XM.Contact = XT.Model.extend({recordType: 'XM.Contact'});
    m = XM.Contact();
    m.fetch({id: 1});

  @extends Backbone.RelationalModel
  @param {Object} attributes
  @param {Object} options
*/
XT.Model = Backbone.RelationalModel.extend(
  /** @scope XT.Model.prototype */ {

  idAttribute: "guid",

  /**
  Specify the name of a data source model here.
  */
  recordType: null,

  initialize: function() {
    var options = arguments[1];

    // initialize for inserted record
    if (options && options.insert) {
      this.attributes.dataState = 'inserted';
      this.fetchId();
    }

    this._dataSource = XT.dataSource;
  },

  /**
  Change dataState to 'updated'.
  */
  attributeChanged: function() {
    if (this.get('dataState') === 'read') {
      this.set('dataState', 'updated');
    }
  },

  /**
  Reimplemented. A model is new if the dataState is "inserted".
  */
  isNew: function() {
    return this.get('dataState') === 'inserted';
  },

  /**
  Returns true when dataState is 'inserted' or 'updated'.
  */
  isDirty: function() {
    return this.get('dataState') === 'inserted' || this.get('dataState') === 'updated';
  },

  /**
  Reimplemented to handle state change.
  */
  fetch: function(options) {
    // turn off state handling
    this.off('change', this.attributeChanged);
    this.set('dataState', 'busy fetching');

    // add call back to turn state handling back on after fetch
    if (options === undefined) options = {};
    var that = this;
    var success = options.success;
    options.sync = true;
    options.success = function(resp, status, xhr) {
      that.on('change', that.attributeChanged);
      if (success) success(model, resp, options);
    };

    return Backbone.Model.prototype.fetch.call(this, options);
  },

  /**
  Fetch a new guid from the server.
  */
  fetchId: function() {
    var that = this;
    var options = {};
    var success = options.success;

    // fetch id
    options.success = function(resp, status, xhr) {
      this.set('guid', resp);
    };
    this._dataSource.dispatch('XT.Record', 'fetchId', this.recordType, options);
  },

  /**
  Reimplemented.
  */
  set: function( key, value, options ) {
    if (_.isObject(key) && value.fetched) this.set('dataState', 'read');
    return Backbone.RelationalModel.prototype.set.call(this, key, value, options);
  },

  /**
  Reimplemented.
  */
  save: function(key, value, options) {
    this.set('dataState', 'busy committing');
    if (options === undefined) options = {};
    var success = options.success;
    options.success = function(resp, status, xhr) {
      that.set('dataState', 'read');
      if (success) success(model, resp, options);
    };
    return Backbone.Model.prototype.save.call(this, options);
  },

  /**
  Reimplemented.
  */
  destroy: function(options) {
    this.set('dataState', 'deleted');
    return Backbone.Model.prototype.destroy.call(this, options);
  },

  /**
  Overload: sync to xtuple datasource.
  */
  sync: function(method, model, options) {
    var recordType = model.recordType;
    var id = options.id || this.id;
    var success = options.success;

    // read
    if (method === 'read' && recordType && id && success) {
      return this._dataSource.retrieveRecord(recordType, id, options);

    // write
    } else if (method == 'create' || method == 'update' || method === 'delete') {
      return this._dataSource.commitRecord(model, options);
    }

    return false;
  },

  /**
  Validate all required fields if no attributes specified.
  */
  validate: function(attributes, options) {
    // check state
    if (this.get('dataState') === 'busy' && !options.fetched) {
      return 'Record is busy';
    } else if (this.get('dataState') === 'deleted') {
      return 'Can not alter deleted record';
    }

    if (!attributes) {  // all
      // check required
      var required = this.required || [];
      var i;

      for (i = 0; i < required.length; i++) {
        if (!this.has(required[i])) {
          return "'" + required[i] + " is required.";
        }
      }
    }
  },

  /** @private */
  _dataSource: null,

});

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2019 The xterm.js authors. All rights reserved.
 * @license MIT
 */

const path = require('path');

/**
 * This webpack config does a production build for xterm.js. It works by taking the output from tsc
 * (via `yarn watch` or `yarn prebuild`) which are put into `out/` and webpacks them into a
 * production mode umd library module in `lib/`. The aliases are used fix up the absolute paths
 * output by tsc (because of `baseUrl` and `paths` in `tsconfig.json`.
 */
module.exports = {
  entry: './out/headless/public/Terminal.js',
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        use: ["source-map-loader"],
        enforce: "pre",
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    modules: ['./node_modules'],
    extensions: [ '.js' ],
    alias: {
      common: path.resolve('./out/common'),
      headless: path.resolve('./out/headless')
    }
  },
  output: {
    filename: 'xterm.js',
    path: path.resolve('./lib-headless'),
    libraryTarget: 'umd'
  },
  mode: 'production'
};
<commit_msg>Output commonjs for headless<commit_after>/**
 * Copyright (c) 2019 The xterm.js authors. All rights reserved.
 * @license MIT
 */

const path = require('path');

/**
 * This webpack config does a production build for xterm.js. It works by taking the output from tsc
 * (via `yarn watch` or `yarn prebuild`) which are put into `out/` and webpacks them into a
 * production mode umd library module in `lib/`. The aliases are used fix up the absolute paths
 * output by tsc (because of `baseUrl` and `paths` in `tsconfig.json`.
 */
module.exports = {
  entry: './out/headless/public/Terminal.js',
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        use: ["source-map-loader"],
        enforce: "pre",
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    modules: ['./node_modules'],
    extensions: [ '.js' ],
    alias: {
      common: path.resolve('./out/common'),
      headless: path.resolve('./out/headless')
    }
  },
  output: {
    filename: 'xterm.js',
    path: path.resolve('./lib-headless'),
    library: {
      type: 'commonjs'
    }
  },
  mode: 'production'
};
<|endoftext|>


<commit_before>/**
 * author: feifeiyu
 * verion: 1.5
 * Yupload is a image upload component base on form submit
 * @param url //image upload address
 * @param csrftoken  // csrftoken for POST Request
 * @param hideField // params submit with image
 * Yupload blog: https://feifeiyum.github.io/2016/12/24/front-yupload/
 */

var Yupload = (function() {
    var YU = function(opt, cb) {
        if(opt.url === undefined) {
            throw 'upload url can not be null'
        }
        if(opt.hideField && opt.hideField.constructor.toString().indexOf('Array') === -1) {
            throw 'type of hide field is array'
        }
        if(opt.csrftoken && typeof opt.csrftoken !== 'object') {
            throw 'type of csrftoken is object'
        }

        var self = this
        cb && (self.cb = cb)
        self.queue = []
        //生产 DOM
        let fakeIframe = self.genDom(opt)
        //注册事件
        self.fetchData(fakeIframe)
    }

    YU.prototype.fetchData = function(fakeIframe) {
        let self = this
        var fetchResp = function() {
            try {
                var data = JSON.parse(this.contentDocument.activeElement.childNodes[0].innerText)
                self.cb && self.cb(null, data)
            } catch(err) {
                self.cb && self.cb(err, null)
            }
            //clean queue
            self.queue.splice(0, 1)
            if(self.queue.length > 0) {
                self.upload()
            }
        }

        //get result
        if(fakeIframe.addEventListener) {
            fakeIframe.addEventListener('load', fetchResp)
        } else if(fakeIframe.attachEvent) {
            fakeIframe.attachEvent('load', fetchResp)
        } else {
            alert('current browser do not support Yupload')
        }

    }

    YU.prototype.genDom = function(opt) {
        let self = this

        if(document.getElementById('yupload-wrap')) {
            throw 'Yupload do not need to init multi-times'
        }

        var uploadWrap = document.createElement('div')
        uploadWrap.id = 'yupload-wrap'
        uploadWrap.style.display = 'none'
        //fake iframe for form
        var fakeIframe = document.createElement('iframe')
        fakeIframe.id = 'yupload-iframe'
        fakeIframe.name = 'yupload-iframe'
        fakeIframe.style.display = 'none'
        uploadWrap.appendChild(fakeIframe)

        //form element
        self.form = document.createElement('form')
        self.form.target = 'yupload-iframe'
        self.form.id = 'yupload-form'
        self.form.method = 'POST'
        self.form.enctype = 'multipart/form-data'
        self.form.action = opt.url
        //insert csrftoken
        if(opt.csrftoken) {
            var csrfElem =  '<input type="hidden" name="' + opt.csrftoken.name + '" value="' + opt.csrftoken.value + '">'
            self.form.innerHTML = csrfElem
        }
        // hidden fields to submit
        self.fields = document.createElement('div')
        self.fields.id = 'yupload-fields'
        //render fields
        if(opt.hideField) {
            var hideElem = ''
            for(let i = 0; i < opt.hideField.length; i++) {
                hideElem += '<input type="hidden" name="' + opt.hideField[i].name + '" value="' + opt.hideField[i].value + '" id="">'
            }
            self.fields.innerHTML = hideElem
        }
        self.form.appendChild(self.fields)
        uploadWrap.appendChild(self.form)
        document.body.appendChild(uploadWrap)

        return fakeIframe
    }

    //add request to queue
    YU.prototype.trigger = function(opt, cb) {
        let self = this
        opt.cb = cb
        //push queue

        if(self.queue.length === 0) {
            // if it is not busy
            self.queue.push(opt)
            self.upload()
        } else {
            self.queue.push(opt)
        }
    }
    //operate upload
    YU.prototype.upload = function() {
        var self = this
        var opt = self.queue[0]
        if(opt.url) {  //change post url
            self.form.action = opt.url
        }
        if(opt.hideField && opt.hideField.constructor.toString().indexOf('Array') === -1) {
            throw 'type of hide field is array'
        }
        opt.cb && (self.cb = opt.cb)
        //rerender fields
        if(opt.hideField) {
            var hideElem = ''
            for(let i = 0; i < opt.hideField.length; i++) {
                hideElem += '<input type="hidden" name="' + opt.hideField[i].name + '" value="' + opt.hideField[i].value + '">'
            }
            self.fields.innerHTML = hideElem
        }

        if(opt.target) {
            var inputFile = ''
            var cloneNode = ''
            //get input file element
            if(typeof opt.target === 'string') {
                inputFile = document.getElementById(opt.target)
            } else if(opt.target.constructor.toString().indexOf('HTMLInputElement') > -1) {
                inputFile = opt.target
            } else {
                throw 'type of file option is DOM(input) or input element\'s id and can not be null'
            }
            // clone and restore input element
            cloneNode = inputFile.cloneNode(true)
            inputFile.parentNode.replaceChild(cloneNode, inputFile)
            //append input with selected file to form
            inputFile.id = 'uploading-file'
            self.fields.appendChild(inputFile)
            //submit
            self.form.submit()
        }
    }

    return YU
}())

//采用 commonJs 模块导入时添加这句
//module.exports = Yupload<commit_msg>modified of multi init strategy<commit_after><|endoftext|>


<commit_before><commit_msg>use bar chart in showing drug prices<commit_after><|endoftext|>


<commit_before>/**
 * FoodCoopShop - The open source software for your foodcoop
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @since         FoodCoopShop 2.5.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 * @author        Mario Rothauer <office@foodcoopshop.com>
 * @copyright     Copyright (c) Mario Rothauer, https://www.rothauer-it.com
 * @link          https://www.foodcoopshop.com
 */
foodcoopshop.SelfService = {

    autoLogoutTimer : 180,
    currentLogoutTimer : 0,

    init : function() {
        foodcoopshop.ModalLogout.init(document.location.href);
        this.initWindowResize();
        if (!foodcoopshop.Helper.isMobile()) {
            this.initAutoLogout();
        }
        this.initSearchForm();
        this.initDepositPayment();
    },

    initMobileBarcodeScanningWithCamera : function(afterElementForLoader, afterElementForCamera, callback) {

        if (!this.isMobileBarcodeScanningSupported) {
            alert('mobile_barcode_scanning_not_supported');
            return;
        }

        if ($('#camera').length > 0) {
            Quagga.stop();
            $('#camera').remove();
            return;
        }

        $(afterElementForCamera).after($('
').attr('id', 'camera'));
        foodcoopshop.SelfService.hideLoader();
        foodcoopshop.SelfService.showLoader(afterElementForLoader);

        Quagga.init({
            inputStream : {
                name : "Live",
                type : "LiveStream",
                target: document.querySelector('#camera'),
            },
            numOfWorkers: navigator.hardwareConcurrency,
            decoder : {
                readers : ["code_39_reader"]
            },
          }, function(err) {
              if (err) {
                  console.log(err);
                  return;
              }

              Quagga.start();

              $('#camera').animate({
                  height: 'toggle'
              }, 150);
              foodcoopshop.SelfService.hideLoader();

          });
          Quagga.offDetected();
          Quagga.onDetected(function(result) {
              Quagga.stop();
              foodcoopshop.SelfService.hideLoader();
              foodcoopshop.SelfService.showLoader(afterElementForLoader);
              callback(result);
          });

    },

    mobileScannerCallbackForLogin : function(result) {
        var loginForm = $('#LoginForm');
        loginForm.find('#barcode').val(result.codeResult.code);
        foodcoopshop.SelfService.submitForm(loginForm, 'fa-sign-in-alt');
    },

    mobileScannerCallbackForProducts : function(result) {
          var redirectUrl = '/selbstbedienung?keyword=' + result.codeResult.code;
          document.location.href = redirectUrl;
    },

    showLoader : function(afterElementForLoader) {
        $('#responsive-header ' + afterElementForLoader).after($('').addClass('fa fa-circle-notch fa-spin fa-2x'));
    },

    hideLoader: function() {
        $('#responsive-header i.fa-circle-notch').remove();
    },

    isMobileBarcodeScanningSupported : function() {
        return navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function';
    },

    initLoginForm : function() {

        var barcodeInputField = $('#barcode');
        barcodeInputField.on('keyup focus', function (e) {
            $(this).prop('type', 'password'); // to avoid autocomplete
        });

        var loginForm = $('#LoginForm');
        var formIsSubmitted = false;
        loginForm.on('submit', function(e) {
            if (formIsSubmitted) {
                return false;
            }
            formIsSubmitted = true;
        });

        barcodeInputField.on('keypress', foodcoopshop.Helper.debounce(
            function() {
                foodcoopshop.SelfService.submitForm(loginForm, 'fa-sign-in-alt');
            }, 1000)
        );

        barcodeInputField.focus();

        var cameraButton = $('').
        addClass('btn').
        addClass('btn-camera').
        addClass('btn-success').
        attr('href', 'javascript:void(0);').
        html('').
        on('click', function() {
            foodcoopshop.SelfService.initMobileBarcodeScanningWithCamera('.btn-camera', '#login-form h1', foodcoopshop.SelfService.mobileScannerCallbackForLogin);
        });
        $('#responsive-header .sb-toggle-left').after(cameraButton);

    },

    initDepositPayment : function() {
        foodcoopshop.ModalPaymentAdd.initDepositSingle('.btn-add-deposit', $('#add-payment-deposit-form'));
    },

    initSearchForm : function() {

        var searchForm = $('#product-search');

        var formIsSubmitted = false;
        searchForm.on('submit', function(e) {
            if (formIsSubmitted) {
                return false;
            }
            formIsSubmitted = true;
        });

        if (!foodcoopshop.Helper.isMobile()) {
            foodcoopshop.Helper.initBootstrapSelect(searchForm);
        }
        searchForm.find('select, input[type="text"]').on('change', function() {
            foodcoopshop.SelfService.submitForm(searchForm, 'fa-search');
        });
        searchForm.find('select, input[type="text"]').on('keypress', foodcoopshop.Helper.debounce(
            function() {
                foodcoopshop.SelfService.submitForm(searchForm, 'fa-search');
            }, 1000)
        );

        searchForm.find('input[type="text"]').focus();
    },

    submitForm : function(searchForm, icon) {
        var submitButton = searchForm.find('.btn[type="submit"]');
        foodcoopshop.Helper.addSpinnerToButton(submitButton, icon);
        foodcoopshop.Helper.disableButton(submitButton);
        searchForm.submit();
    },

    initHighlightedProductIdForMobileBarcodeScanning: function(productId) {
        $('#products').show();
        $('.product-wrapper').hide();
        var rowId = '#product-wrapper-' + productId;
        $(rowId).show();
        this.initHighlightedProductId(productId);
    },

    initHighlightedProductId: function(productId) {
        var rowId = '#product-wrapper-' + productId;
        $.scrollTo(rowId, 1000, {
            offset: {
                top: -100
            }
        });
        $(rowId).css('background-color', '#f3515c');
        $(rowId).css('color', 'white');
        $(rowId).one('mouseover', function () {
            $(this).removeAttr('style');
        });
        $(rowId).find('.quantity-in-units-input-field-wrapper input').focus();
    },

    initCartErrors: function (cartErrors) {
        cartErrors = $.parseJSON(cartErrors);
        for (var key in cartErrors) {
            var productContainer = $('#cart .product.' + key);
            productContainer.addClass('error');
            productContainer.after('

' + cartErrors[key].join('

') + '

');
        }
    },

    initWindowResize: function () {
        $(window).on('resize', function () {
            foodcoopshop.SelfService.onWindowResize();
        });
        foodcoopshop.SelfService.onWindowResize();
    },

    setFocusToSearchInputField : function() {
        $('#product-search input[name="keyword"]').focus();
    },

    onWindowResize : function() {
        $('.right-box').css('max-height', parseInt($(window).height()));
    },

    initAutoLogout : function() {

        this.resetTimer();
        this.renderTimer();

        $(document).idle({
            startAtIdle : true,
            onActive: function(){
                foodcoopshop.SelfService.resetTimer();
                foodcoopshop.SelfService.renderTimer();
            },
            onIdle: function() {
                foodcoopshop.SelfService.currentLogoutTimer--;
                foodcoopshop.SelfService.renderTimer();
                if (foodcoopshop.SelfService.currentLogoutTimer == 0) {
                    document.location.href = '/' + foodcoopshop.LocalizedJs.helper.routeLogout + '?redirect=' + document.location.href;
                }
            },
            recurIdleCall : true,
            idle: 1000
        });

    },

    resetTimer : function() {
        this.currentLogoutTimer = this.autoLogoutTimer;
    },

    renderTimer : function() {
        $('.auto-logout-timer').html(this.currentLogoutTimer);
    }

};
<commit_msg>translate route<commit_after>/**
 * FoodCoopShop - The open source software for your foodcoop
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @since         FoodCoopShop 2.5.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 * @author        Mario Rothauer <office@foodcoopshop.com>
 * @copyright     Copyright (c) Mario Rothauer, https://www.rothauer-it.com
 * @link          https://www.foodcoopshop.com
 */
foodcoopshop.SelfService = {

    autoLogoutTimer : 180,
    currentLogoutTimer : 0,

    init : function() {
        foodcoopshop.ModalLogout.init(document.location.href);
        this.initWindowResize();
        if (!foodcoopshop.Helper.isMobile()) {
            this.initAutoLogout();
        }
        this.initSearchForm();
        this.initDepositPayment();
    },

    initMobileBarcodeScanningWithCamera : function(afterElementForLoader, afterElementForCamera, callback) {

        if (!this.isMobileBarcodeScanningSupported) {
            alert('mobile_barcode_scanning_not_supported');
            return;
        }

        if ($('#camera').length > 0) {
            Quagga.stop();
            $('#camera').remove();
            return;
        }

        $(afterElementForCamera).after($('
').attr('id', 'camera'));
        foodcoopshop.SelfService.hideLoader();
        foodcoopshop.SelfService.showLoader(afterElementForLoader);

        Quagga.init({
            inputStream : {
                name : "Live",
                type : "LiveStream",
                target: document.querySelector('#camera'),
            },
            numOfWorkers: navigator.hardwareConcurrency,
            decoder : {
                readers : ["code_39_reader"]
            },
          }, function(err) {
              if (err) {
                  console.log(err);
                  return;
              }

              Quagga.start();

              $('#camera').animate({
                  height: 'toggle'
              }, 150);
              foodcoopshop.SelfService.hideLoader();

          });
          Quagga.offDetected();
          Quagga.onDetected(function(result) {
              Quagga.stop();
              foodcoopshop.SelfService.hideLoader();
              foodcoopshop.SelfService.showLoader(afterElementForLoader);
              callback(result);
          });

    },

    mobileScannerCallbackForLogin : function(result) {
        var loginForm = $('#LoginForm');
        loginForm.find('#barcode').val(result.codeResult.code);
        foodcoopshop.SelfService.submitForm(loginForm, 'fa-sign-in-alt');
    },

    mobileScannerCallbackForProducts : function(result) {
          var redirectUrl = '/' + foodcoopshop.LocalizedJs.helper.routeSelfService + '?keyword=' + result.codeResult.code;
          document.location.href = redirectUrl;
    },

    showLoader : function(afterElementForLoader) {
        $('#responsive-header ' + afterElementForLoader).after($('').addClass('fa fa-circle-notch fa-spin fa-2x'));
    },

    hideLoader: function() {
        $('#responsive-header i.fa-circle-notch').remove();
    },

    isMobileBarcodeScanningSupported : function() {
        return navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function';
    },

    initLoginForm : function() {

        var barcodeInputField = $('#barcode');
        barcodeInputField.on('keyup focus', function (e) {
            $(this).prop('type', 'password'); // to avoid autocomplete
        });

        var loginForm = $('#LoginForm');
        var formIsSubmitted = false;
        loginForm.on('submit', function(e) {
            if (formIsSubmitted) {
                return false;
            }
            formIsSubmitted = true;
        });

        barcodeInputField.on('keypress', foodcoopshop.Helper.debounce(
            function() {
                foodcoopshop.SelfService.submitForm(loginForm, 'fa-sign-in-alt');
            }, 1000)
        );

        barcodeInputField.focus();

        var cameraButton = $('').
        addClass('btn').
        addClass('btn-camera').
        addClass('btn-success').
        attr('href', 'javascript:void(0);').
        html('').
        on('click', function() {
            foodcoopshop.SelfService.initMobileBarcodeScanningWithCamera('.btn-camera', '#login-form h1', foodcoopshop.SelfService.mobileScannerCallbackForLogin);
        });
        $('#responsive-header .sb-toggle-left').after(cameraButton);

    },

    initDepositPayment : function() {
        foodcoopshop.ModalPaymentAdd.initDepositSingle('.btn-add-deposit', $('#add-payment-deposit-form'));
    },

    initSearchForm : function() {

        var searchForm = $('#product-search');

        var formIsSubmitted = false;
        searchForm.on('submit', function(e) {
            if (formIsSubmitted) {
                return false;
            }
            formIsSubmitted = true;
        });

        if (!foodcoopshop.Helper.isMobile()) {
            foodcoopshop.Helper.initBootstrapSelect(searchForm);
        }
        searchForm.find('select, input[type="text"]').on('change', function() {
            foodcoopshop.SelfService.submitForm(searchForm, 'fa-search');
        });
        searchForm.find('select, input[type="text"]').on('keypress', foodcoopshop.Helper.debounce(
            function() {
                foodcoopshop.SelfService.submitForm(searchForm, 'fa-search');
            }, 1000)
        );

        searchForm.find('input[type="text"]').focus();
    },

    submitForm : function(searchForm, icon) {
        var submitButton = searchForm.find('.btn[type="submit"]');
        foodcoopshop.Helper.addSpinnerToButton(submitButton, icon);
        foodcoopshop.Helper.disableButton(submitButton);
        searchForm.submit();
    },

    initHighlightedProductIdForMobileBarcodeScanning: function(productId) {
        $('#products').show();
        $('.product-wrapper').hide();
        var rowId = '#product-wrapper-' + productId;
        $(rowId).show();
        this.initHighlightedProductId(productId);
    },

    initHighlightedProductId: function(productId) {
        var rowId = '#product-wrapper-' + productId;
        $.scrollTo(rowId, 1000, {
            offset: {
                top: -100
            }
        });
        $(rowId).css('background-color', '#f3515c');
        $(rowId).css('color', 'white');
        $(rowId).one('mouseover', function () {
            $(this).removeAttr('style');
        });
        $(rowId).find('.quantity-in-units-input-field-wrapper input').focus();
    },

    initCartErrors: function (cartErrors) {
        cartErrors = $.parseJSON(cartErrors);
        for (var key in cartErrors) {
            var productContainer = $('#cart .product.' + key);
            productContainer.addClass('error');
            productContainer.after('

' + cartErrors[key].join('

') + '

');
        }
    },

    initWindowResize: function () {
        $(window).on('resize', function () {
            foodcoopshop.SelfService.onWindowResize();
        });
        foodcoopshop.SelfService.onWindowResize();
    },

    setFocusToSearchInputField : function() {
        $('#product-search input[name="keyword"]').focus();
    },

    onWindowResize : function() {
        $('.right-box').css('max-height', parseInt($(window).height()));
    },

    initAutoLogout : function() {

        this.resetTimer();
        this.renderTimer();

        $(document).idle({
            startAtIdle : true,
            onActive: function(){
                foodcoopshop.SelfService.resetTimer();
                foodcoopshop.SelfService.renderTimer();
            },
            onIdle: function() {
                foodcoopshop.SelfService.currentLogoutTimer--;
                foodcoopshop.SelfService.renderTimer();
                if (foodcoopshop.SelfService.currentLogoutTimer == 0) {
                    document.location.href = '/' + foodcoopshop.LocalizedJs.helper.routeLogout + '?redirect=' + document.location.href;
                }
            },
            recurIdleCall : true,
            idle: 1000
        });

    },

    resetTimer : function() {
        this.currentLogoutTimer = this.autoLogoutTimer;
    },

    renderTimer : function() {
        $('.auto-logout-timer').html(this.currentLogoutTimer);
    }

};
<|endoftext|>


<commit_before>if("undefined"==typeof OGX)var OGX=function(){};OGX.prototype.MobileBaseView=function(i){"use strict";function e(i){var e=l.el.width(),n=l.el.height(),t=(e-i.width)/2,o=$(window).height()-l.el.position().top-(n/2-i.height/2),s='

';l.el.parent(0).append(s),c=l.el.parent(0).children(".ogx_view_loading:last")}function n(i){i?(r=new MutationObserver(function(i,e){i.forEach(function(i){l.el.trigger(OGX.MobileBaseView.RENDER)})}),r.observe(l.el[0],{childList:!0,subtree:!0})):(r.disconnect(),r=null)}function t(){for(var i in f)l.config.hasOwnProperty(i)||(l.config[i]=f[i]);l.el=s=$(l.config.container)}function o(){t(),n(!0),l.render()}var s,r,c,l=this,f={};this.config=i,this.el=null,this.constructor=function(){},this.scopes=function(){return l.config.scopes},this.focus=function(){},this.blur=function(){},this.destroyInternal=function(){n(!1),this.ux(!1),s.empty()},this.ux=function(i){},this.render=function(i){"undefined"==typeof i?l.config.hasOwnProperty("file")?s.load(l.config.file):l.config.hasOwnProperty("html")&&s.html(l.config.html):s.html(i)},this.showLoading=function(i,n){i?e(n):c&&(c.remove(),c=null)},o()},OGX.MobileBaseView=function(i){"use strict";return new OGX.prototype.MobileBaseView(i)},OGX.MobileBaseView.DESTROY="destroy",OGX.MobileBaseView.RENDER="render";<commit_msg>added auto kill loading on kill view<commit_after>if("undefined"==typeof OGX)var OGX=function(){};OGX.prototype.MobileBaseView=function(i){"use strict";function e(i){var e=h.el.width(),n=h.el.height(),t=(e-i.width)/2,o=$(window).height()-h.el.position().top-(n/2-i.height/2),s='

';h.el.parent(0).append(s),c=h.el.parent(0).children(".ogx_view_loading:last")}function n(i){i?(r=new MutationObserver(function(i,e){i.forEach(function(i){h.el.trigger(OGX.MobileBaseView.RENDER)})}),r.observe(h.el[0],{childList:!0,subtree:!0})):(r.disconnect(),r=null)}function t(){for(var i in l)h.config.hasOwnProperty(i)||(h.config[i]=l[i]);h.el=s=$(h.config.container)}function o(){t(),n(!0),h.render()}var s,r,c,h=this,l={};this.config=i,this.el=null,this.constructor=function(){},this.scopes=function(){return h.config.scopes},this.focus=function(){},this.blur=function(){},this.destroyInternal=function(){this.showLoading(!1),n(!1),this.ux(!1),s.empty()},this.ux=function(i){},this.render=function(i){"undefined"==typeof i?h.config.hasOwnProperty("file")?s.load(h.config.file):h.config.hasOwnProperty("html")&&s.html(h.config.html):s.html(i)},this.showLoading=function(i,n){i?e(n):c&&(c.remove(),c=null)},o()},OGX.MobileBaseView=function(i){"use strict";return new OGX.prototype.MobileBaseView(i)},OGX.MobileBaseView.DESTROY="destroy",OGX.MobileBaseView.RENDER="render";<|endoftext|>


<commit_before>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
            'moment': 'node_modules/moment/moment.js',
            'ng2-bootstrap/ng2-bootstrap': 'node_modules/ng2-bootstrap/bundles/ng2-bootstrap.umd.js',
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            }
        }
    });
})(this);

<commit_msg>Fix ng2-bootstrap file name to comply with name in the latest npm package.<commit_after>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
            'moment': 'node_modules/moment/moment.js',
            'ng2-bootstrap/ng2-bootstrap': 'node_modules/ng2-bootstrap/bundles/ngx-bootstrap.umd.js',
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            }
        }
    });
})(this);

<|endoftext|>


<commit_before>/**
 * Fusion.Widget.ZoomToSelection
 *
 * $Id: ZoomToSelection.js 1523 2008-09-11 19:30:43Z pagameba $
 *
 * Copyright (c) 2007, DM Solutions Group Inc.
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

 /********************************************************************
 * Class: Fusion.Widget.ZoomToSelection
 *
 * Zoom to the current selection, if any
 *
 * **********************************************************************/

Fusion.Widget.ZoomToSelection = OpenLayers.Class(Fusion.Widget, {
    uiClass: Jx.Button,

    initializeWidget: function(widgetTag) {

        var json = widgetTag.extension;
        this.maxDimension = json.MaximumZoomDimension ? json.MaximumZoomDimension[0] : -1;
        this.zoomFactor = json.ZoomFactor ? json.ZoomFactor[0] : 2;

        this.enable = Fusion.Widget.ZoomToSelection.prototype.enable;

        this.getMap().registerForEvent(Fusion.Event.MAP_SELECTION_ON, OpenLayers.Function.bind(this.enable, this));
        this.getMap().registerForEvent(Fusion.Event.MAP_SELECTION_OFF, OpenLayers.Function.bind(this.disable, this));
    },

    /**
     * get the selection from the map (which may not be loaded yet).
     * zoomToSelection is called when the selection is ready.
     */
    activate: function() {
        this.getMap().getSelection(OpenLayers.Function.bind(this.zoomToSelection, this));
    },

    /**
     * set the extents of the map based on the pixel coordinates
     * passed
     *
     * @param selection the active selection, or null if there is none
     */
    zoomToSelection : function(selection) {
        var map = this.oMap.aMaps[0]; //TODO: allow selection on multple maps
        var ll = selection[map.getMapName()].getLowerLeftCoord();
        var ur = selection[map.getMapName()].getUpperRightCoord();
        var zoom_size = this.zoomFactor * Math.max( Math.abs(ur.x - ll.x), Math.abs(ur.y - ll.y)) / 2;
        var cX = (ur.x + ll.x)/2;
        var cY = (ur.y + ll.y)/2;
        ll.x = cX - zoom_size;
        ur.x = cX + zoom_size;
        ll.y = cY - zoom_size;
        ur.y = cY + zoom_size;
        this.getMap().setExtents(new OpenLayers.Bounds(ll.x,ll.y,ur.x,ur.y));
    },

    enable: function() {
        if (this.oMap && this.oMap.hasSelection()) {
            Fusion.Widget.prototype.enable.apply(this, []);
        } else {
            this.disable();
        }
    }

});
<commit_msg>HPMS-83: Update ZoomToSelection.js to support multi-map configurations<commit_after>/**
 * Fusion.Widget.ZoomToSelection
 *
 * $Id: ZoomToSelection.js 1523 2008-09-11 19:30:43Z pagameba $
 *
 * Copyright (c) 2007, DM Solutions Group Inc.
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

 /********************************************************************
 * Class: Fusion.Widget.ZoomToSelection
 *
 * Zoom to the current selection, if any
 *
 * **********************************************************************/

Fusion.Widget.ZoomToSelection = OpenLayers.Class(Fusion.Widget, {
    uiClass: Jx.Button,

    initializeWidget: function(widgetTag) {

        var json = widgetTag.extension;
        this.maxDimension = json.MaximumZoomDimension ? json.MaximumZoomDimension[0] : -1;
        this.zoomFactor = json.ZoomFactor ? json.ZoomFactor[0] : 2;

        this.enable = Fusion.Widget.ZoomToSelection.prototype.enable;

        this.getMap().registerForEvent(Fusion.Event.MAP_SELECTION_ON, OpenLayers.Function.bind(this.enable, this));
        this.getMap().registerForEvent(Fusion.Event.MAP_SELECTION_OFF, OpenLayers.Function.bind(this.disable, this));
    },

    /**
     * get the selection from the map (which may not be loaded yet).
     * zoomToSelection is called when the selection is ready.
     */
    activate: function() {
        this.getMap().getSelection(OpenLayers.Function.bind(this.zoomToSelection, this));
    },

    /**
     * set the extents of the map based on the pixel coordinates
     * passed
     *
     * @param selection the active selection, or null if there is none
     */
    zoomToSelection : function(selection) {
        var bounds = new OpenLayers.Bounds();
        for (var i=0; i<this.oMap.aMaps.length; ++i) {
          var mapName = this.oMap.aMaps[i].getMapName()
          if (selection[mapName]) {
            var ll = selection[mapName].getLowerLeftCoord();//make this an OL Pixel
            bounds.extend(new OpenLayers.LonLat(ll.x,ll.y));
            var ur = selection[mapName].getUpperRightCoord();
            bounds.extend(new OpenLayers.LonLat(ur.x,ur.y));
          }
        }
        var zoom_size = this.zoomFactor * Math.max( Math.abs(bounds.getWidth()), Math.abs(bounds.getHeight())) / 2;
        var center = bounds.getCenterLonLat();
        llx = center.lon - zoom_size;
        urx = center.lon + zoom_size;
        lly = center.lat - zoom_size;
        ury = center.lat + zoom_size;
        this.getMap().setExtents(new OpenLayers.Bounds(llx,lly,urx,ury));
    },

    enable: function() {
        if (this.oMap && this.oMap.hasSelection()) {
            Fusion.Widget.prototype.enable.apply(this, []);
        } else {
            this.disable();
        }
    }

});
<|endoftext|>


<commit_before>/*
 * include base libraries
 */
lib("lib/json2.js");
lib("lib/underscore.js");
lib("lib/timers.js");
lib("lib/later.js");
lib("lib/wd.js");

/*
 * load core code
 */
lib("scheduler.js");
lib("cdv.js");
lib("cda.js");

// Wrap up console obj so that logging works
var console = {
    log: function(m){
        print(m)
    }

}

/*
 * boot up CDV
 */
cdv = wd.cdv.cdv();
/*
 * load core test types
 */
lib("tests/customTest.js");

/*
 * Load tests
 */
loadTests();

/*
 * set up request handlers
 */
registerHandler("GET", "/restartTimer", function(out){
    this.setOutputType(this.MIME_TEXT);
    timerUp = true;
    scheduler.restart();
    out.write(new java.lang.String("Timer turned on").getBytes("utf-8"));
});

registerHandler("GET", "/stopTimer", function(out){
    try {
        this.setOutputType(this.MIME_TEXT);
        timerUp = false;
        print("Turning timer off");
        scheduler.pause();
        out.write(new java.lang.String("Timer turned off").getBytes("utf-8"));
        print("Timer turned off");

    } catch(e) {
        print(e);
    }
});

registerHandler("GET", "/listTests", function(out){
    try {
        this.setOutputType(this.MIME_JSON);
        out.write(new java.lang.String(JSON.stringify(cdv.listTests())).getBytes("utf-8"));
    } catch(e) {
        print(e);
    }
});

registerHandler("GET", "/listTestsFlatten", function(out){
    try {
        this.setOutputType(this.MIME_JSON);
        var str = JSON.stringify(cdv.listTestsFlatten());
        out.write(new java.lang.String(str).getBytes("utf-8"));
    } catch(e) {
        print(e);
    }
});

registerHandler("GET", "/runTests", function(out){

    try {
      this.setOutputType(this.MIME_JSON);
      var groups = cdv.listTests();
      var g, t, group, test, results = [];

      var callback = function(r){
        var result = r.toJSON();
        results.push(result);
        var tr =  eventManager.createTestResult(JSON.stringify(result)), doc;
        if(tr) {
          doc = persistenceEngine.createDocument(tr.getPersistenceClass(), tr.toJSON().toString());
          persistenceEngine.store(null, tr.getPersistenceClass(), null, doc);
        }
      }

      for (g in groups) if (groups.hasOwnProperty(g)) {
          var group = groups[g];
          for (t in group) if (group.hasOwnProperty(t)) {
              var test = group[t];
              cdv.runTest(test, {
                  callback: callback
              });
          }
      }
      out.write(new java.lang.String(JSON.stringify(results)).getBytes("utf-8"));
    } catch (e) {
        print(e);
    }
});

registerHandler("GET", "/runTest", function(out,pathParams,requestParams){
    var myself = this;
    try {
      callWithDefaultSession(function(){
        myself.setOutputType(myself.MIME_JSON);
        var str = cdv.runTestById({group: requestParams.getStringParameter("group",""),name: requestParams.getStringParameter("name","")});
        str = JSON.stringify(str.toJSON());
        out.write(new java.lang.String(str).getBytes("utf-8"));
      });
    } catch(e) {
        print(e);
    }
});

registerHandler("GET", "/refreshNotifications", function(out){
  eventManager = eventManager.refresh();
  out.write(new java.lang.String('{"success": true}').getBytes("utf-8"));
});

registerHandler("GET", "/refreshTests", function(out){
  scheduler.reset();
  loadTests();
});

registerHandler("GET",'/foo',function(out){
  var klass = Packages.pt.webdetails.cpf.persistence.PersistenceEngine;

  var methods = persistenceEngine.getClass().getMethods()
  for(var m = 0; m < methods.length; m++) {
    print(methods[m].toString());
  }
});
lib("selftest.js");
lib("queries.js");

<commit_msg>Don't persist test results in /runTests (they're persisted further ahead)<commit_after>/*
 * include base libraries
 */
lib("lib/json2.js");
lib("lib/underscore.js");
lib("lib/timers.js");
lib("lib/later.js");
lib("lib/wd.js");

/*
 * load core code
 */
lib("scheduler.js");
lib("cdv.js");
lib("cda.js");

// Wrap up console obj so that logging works
var console = {
    log: function(m){
        print(m)
    }

}

/*
 * boot up CDV
 */
cdv = wd.cdv.cdv();
/*
 * load core test types
 */
lib("tests/customTest.js");

/*
 * Load tests
 */
loadTests();

/*
 * set up request handlers
 */
registerHandler("GET", "/restartTimer", function(out){
    this.setOutputType(this.MIME_TEXT);
    timerUp = true;
    scheduler.restart();
    out.write(new java.lang.String("Timer turned on").getBytes("utf-8"));
});

registerHandler("GET", "/stopTimer", function(out){
    try {
        this.setOutputType(this.MIME_TEXT);
        timerUp = false;
        print("Turning timer off");
        scheduler.pause();
        out.write(new java.lang.String("Timer turned off").getBytes("utf-8"));
        print("Timer turned off");

    } catch(e) {
        print(e);
    }
});

registerHandler("GET", "/listTests", function(out){
    try {
        this.setOutputType(this.MIME_JSON);
        out.write(new java.lang.String(JSON.stringify(cdv.listTests())).getBytes("utf-8"));
    } catch(e) {
        print(e);
    }
});

registerHandler("GET", "/listTestsFlatten", function(out){
    try {
        this.setOutputType(this.MIME_JSON);
        var str = JSON.stringify(cdv.listTestsFlatten());
        out.write(new java.lang.String(str).getBytes("utf-8"));
    } catch(e) {
        print(e);
    }
});

registerHandler("GET", "/runTests", function(out){

    try {
      this.setOutputType(this.MIME_JSON);
      var groups = cdv.listTests();
      var g, t, group, test, results = [];

      var callback = function(r){
        var result = r.toJSON();
        results.push(result);
      }

      for (g in groups) if (groups.hasOwnProperty(g)) {
          var group = groups[g];
          for (t in group) if (group.hasOwnProperty(t)) {
              var test = group[t];
              cdv.runTest(test, {
                  callback: callback
              });
          }
      }
      out.write(new java.lang.String(JSON.stringify(results)).getBytes("utf-8"));
    } catch (e) {
        print(e);
    }
});

registerHandler("GET", "/runTest", function(out,pathParams,requestParams){
    var myself = this;
    try {
      callWithDefaultSession(function(){
        myself.setOutputType(myself.MIME_JSON);
        var str = cdv.runTestById({group: requestParams.getStringParameter("group",""),name: requestParams.getStringParameter("name","")});
        str = JSON.stringify(str.toJSON());
        out.write(new java.lang.String(str).getBytes("utf-8"));
      });
    } catch(e) {
        print(e);
    }
});

registerHandler("GET", "/refreshNotifications", function(out){
  eventManager = eventManager.refresh();
  out.write(new java.lang.String('{"success": true}').getBytes("utf-8"));
});

registerHandler("GET", "/refreshTests", function(out){
  scheduler.reset();
  loadTests();
});

registerHandler("GET",'/foo',function(out){
  var klass = Packages.pt.webdetails.cpf.persistence.PersistenceEngine;

  var methods = persistenceEngine.getClass().getMethods()
  for(var m = 0; m < methods.length; m++) {
    print(methods[m].toString());
  }
});
lib("selftest.js");
lib("queries.js");

<|endoftext|>