<commit_before>/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"D9C45892-D610-4019-AB9A-09E6EAF488BE"}
 */
var _loginLink = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"65E9004B-1EC5-4F28-B456-8223965BAA5D"}
 */
var _loginObjName = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"4C3EECF0-46D8-47C7-9B9F-56E4405731AC",variableType:4}
 */
var _loginRequired = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"F5A86BA7-FC8F-448E-B31F-2A787207A97B"}
 */
var _license_dsa_mosaic_WEB_cms_blocks = 'Module: _dsa_mosaic_WEB_cms_blocks \
									Copyright (C) 2011-2013 Data Mosaic \
									MIT Licensed';

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"D0E1184A-C03A-4F5D-A2C5-D023B469A350"}
 */
var _module = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"339695F3-4B5B-4B4B-979D-AFB3C827D5C0"}
 */
var _form = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"9495B9C2-7483-4D34-95EC-4D1421BC7681",variableType:4}
 */
var _height = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"A5CA0FEC-57FD-4947-8B03-48C50608177B",variableType:4}
 */
var _width = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"B2570C0E-8077-4812-95C0-903D4A57EFE1",variableType:4}
 */
var _transparent = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"4077BE6B-B900-4C25-AB33-B0C2764299DD"}
 */
var _cssClass = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"FFA48B49-8645-4C42-8B43-96E81DF8D4E0"}
 */
var _cssId = null;

/**
 * @param	{Object}	obj Data object passed to all markup methods
 *
 * @properties={typeid:24,uuid:"399C16F5-0026-4B84-A2B5-01231434CB1A"}
 */
function CONTROLLER_default(obj, results) {

	var configuration = globals.CMS.data.block_configure

	// check login
	if ( configuration.loginRequired ) {

		//get login
		var login = globals.WEBc_session_getData(obj.session_server.record.session_id, configuration.loginObjName)

		if ( login ) {
			//make sure that login knows the id of this webclient
			if (!login.swcID) {
				login.swcID = plugins.sutra.getClientID()
				globals.CMS.session.setData(obj.session_server.record.session_id,configuration.loginObjName,login)
			}

			// show swc view
			return _VIEW_swc(obj, results, login)
		}
		else {
			// show no login view
			return _VIEW_no_login(configuration.loginLink)
		}
	}
	else {
		// show swc view
		return _VIEW_swc(obj, results, login)
	}

}

/**
 * Update display as needed when block selected.
 *
 * @properties={typeid:24,uuid:"7ABCE520-07F0-4ED3-B01B-EB3348DAEE3B"}
 */
function INIT_data() {
	//get data
	var data = globals.CMS.ui.getData(controller.getName())
	var dataConfig = globals.CMS.ui.getConfig(controller.getName())

	//save down form variables so records can be changed
	_module = data.module
	_form = data.form
	_width = dataConfig.width
	_height = dataConfig.height
	_transparent = dataConfig.transparent
	_cssId = dataConfig.cssId
	_cssClass = dataConfig.cssClass
	_loginRequired = dataConfig.loginRequired
	_loginObjName = dataConfig.loginObjName
	_loginLink = dataConfig.loginLink

	//set status of variables
	var editMode = globals.CMS.ui.getEdit()

	elements.var_module.visible = editMode
	elements.var_module__display.visible = !editMode
	elements.var_form.visible = editMode
	elements.var_form__display.visible = !editMode
	elements.var_width.transparent = editMode
	elements.var_width.editable = editMode
	elements.var_height.transparent = editMode
	elements.var_height.editable = editMode
	elements.var_transparent.readOnly = !editMode
	elements.var_cssId.transparent = editMode
	elements.var_cssId.editable = editMode
	elements.var_cssClass.transparent = editMode
	elements.var_cssClass.editable = editMode
	elements.var_loginRequired.readOnly = !editMode
	elements.var_loginObjName.transparent = editMode
	elements.var_loginObjName.editable = editMode

	//fill valuelist appropriately
	SET_forms()
}

/**
 * @properties={typeid:24,uuid:"0829A6D7-6C0C-4C82-92B7-6BB50829DD5F"}
 */
function SET_forms() {
	//only show forms from selected module when in top level form
	if (application.__parent__.solutionPrefs && _module) {
		//get from repository via queries way
		if (!solutionPrefs.repository.api) {
			//load formNames for report module
			var moduleForms = solutionPrefs.repository.allForms[_module]
			var formNames = new Array()
			var j = 0

			//check to make sure that there are forms in the report module
			if (moduleForms) {
				for (var i in moduleForms) {
					formNames[j++] = moduleForms[i].formName
				}
			}
		}
		//get from the workspace
		else if (solutionPrefs.repository.workspace) {
			var moduleForms = solutionPrefs.repository.workspace[_module]

			var formNames = new Array()
			var j = 0

			if (moduleForms) { //check to make sure module_filter has a loaded value (they chose something)
				for (var i in moduleForms) {
					formNames[j++] = i
				}
			}
		}
	}
	//when in reporting module, show forms anyway
	else {
		var formNames = forms.allnames
	}

	formNames = formNames.sort()

	//set valuelist
	application.setValueListItems('WEB_webclient_forms', formNames)
}

/**
 * Build a data object that defines this block. Called when creating a new block.
 * Used to create all meta data associated with this block (register a block in the CMS)
 *
 * @returns {Object} Data object that is used to register a block
 *
 * @properties={typeid:24,uuid:"EB40FAF9-1C53-4828-91FF-2087CBDF39BE"}
 */
function INIT_block() {

	// main data object to build
	var block = {}

	// block record data
	block.record = {
	        block_name			: 'Servoy Web Client',
			block_description	: "Integrates Servoy's web client",
			form_name			: 'WEB_0F__servoy_webclient'
		}

	// block views
	block.views = globals.WEBc_block_type_getMethods(controller.getName(),"VIEW")

	// block client actions - Block
	block.clientActionsBlock = globals.WEBc_block_type_getMethods(controller.getName(),"BLOCK")

	// block client actions - Page
	block.clientActionsPage = globals.WEBc_block_type_getMethods(controller.getName(),"PAGE")

	// block web actions
	block.webActions = globals.WEBc_block_type_getMethods(controller.getName(),"WEB")

	// block data points
	block.data = {
		module : 'TEXT',
		form : 'TEXT'
	}

	// block configure data points
	block.blockConfigure = {
		width : 'INTEGER',
		height : 'INTEGER',
		transparent : 'INTEGER',
		cssId : 'TEXT',
		cssClass : 'TEXT',
		loginRequired : 'INTEGER',
		loginObjName : 'TEXT',
		loginLink : 'TEXT'
	}

	// block response data points
	block.blockResponse = {

	}

	return block
}

/**
 * Handle changed data.
 *
 * @param {Object} oldValue old value
 * @param {Object} newValue new value
 * @param {JSEvent} event the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"EAF1F56A-8C93-4502-BDA4-BB78E2FFB658"}
 */
function FLD_module__data_change(oldValue, newValue, event) {
	//save data
	globals.WEBc_block_fld_data_change__data(oldValue, newValue, event)

	//refresh form valuelist
	SET_forms()
}

/**
 * @properties={typeid:24,uuid:"18FF2C5F-9F17-4AE7-BBF8-C6DD844A92C7"}
 */
function _VIEW_swc(obj, results, login) {

		//get solution model form
	var smForm = solutionModel.getForm(obj.block_data.form)
	//for width
	var defaultWidth = (smForm) ? smForm.width : 0
	//for height
	var totalHeight = 0
	if (smForm) {
		for (var i in smForm.getParts()) {
			totalHeight += smForm.getParts()[i].height
		}
	}
	var defaultHeight = totalHeight

	//TODO: abstract the passing in of record
	var record		= (login && login.customer && login.customer.loginID) ? login.customer.loginID : ''

	var url 		= globals.WEBc_markup_link_servlet(obj)
	var module		= '_dsa_mosaic_WEB_cms'
	var method		= 'WEB_servoy_wc_controller'
	var template	= '\n\
							Servoy Web Client cannot load\n\
						'
	var html = template.replace(/\t/g, '')
	html = utils.stringReplace(html, "{{url}}", url)
	html = utils.stringReplace(html, "{{module}}", module)
	html = utils.stringReplace(html, "{{method}}", method)
	html = utils.stringReplace(html, "{{form}}", obj.block_data.form)
	html = utils.stringReplace(html, "{{record}}", record)
	html = utils.stringReplace(html, "{{width}}", obj.block_configure.width || defaultWidth)
	html = utils.stringReplace(html, "{{height}}", obj.block_configure.height || defaultHeight)
	html = utils.stringReplace(html, "{{id}}", obj.block_configure.cssId || 'swc')
	html = utils.stringReplace(html, "{{class}}", obj.block_configure.cssClass)
	html = utils.stringReplace(html, "{{transparent}}", (obj.block_configure.transparent ? 'true' : 'false'))

	return html

}

/**
 * @properties={typeid:24,uuid:"1EF67102-5F99-4C5A-A20D-1A98EABC3A8C"}
 */
function _VIEW_no_login(pageID) {

	// get page link token
	var pageLink = globals.CMS.token.getPage(pageID)

	// return markup to login page
	return '
Your session has expired. Please login again.
'
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"B206DA14-241E-41A0-946A-FCB31366D1DE"}
 */
function PICK_page(input,pageRec,event) {
	//show page picker when in edit mode
	if (input instanceof JSEvent && globals.WEBc_block_getEdit()) {
		globals.WEBc_page_picker(PICK_page,input)
	}
	//page picked
	else if (pageRec) {
		if (event) {
			switch (event.getElementName().substr(4)) {
				case 'loginLink':
					_loginLink = pageRec.page_name
					globals.WEBc_block_setConfig(event,'loginLink',pageRec.id_page.toString())
					break
			}
		}
	}
}
<commit_msg>kill webclient session on logout (https://trello.com/c/iXog8cnV)<commit_after>/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"D9C45892-D610-4019-AB9A-09E6EAF488BE"}
 */
var _loginLink = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"65E9004B-1EC5-4F28-B456-8223965BAA5D"}
 */
var _loginObjName = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"4C3EECF0-46D8-47C7-9B9F-56E4405731AC",variableType:4}
 */
var _loginRequired = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"F5A86BA7-FC8F-448E-B31F-2A787207A97B"}
 */
var _license_dsa_mosaic_WEB_cms_blocks = 'Module: _dsa_mosaic_WEB_cms_blocks \
									Copyright (C) 2011-2013 Data Mosaic \
									MIT Licensed';

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"D0E1184A-C03A-4F5D-A2C5-D023B469A350"}
 */
var _module = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"339695F3-4B5B-4B4B-979D-AFB3C827D5C0"}
 */
var _form = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"9495B9C2-7483-4D34-95EC-4D1421BC7681",variableType:4}
 */
var _height = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"A5CA0FEC-57FD-4947-8B03-48C50608177B",variableType:4}
 */
var _width = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"B2570C0E-8077-4812-95C0-903D4A57EFE1",variableType:4}
 */
var _transparent = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"4077BE6B-B900-4C25-AB33-B0C2764299DD"}
 */
var _cssClass = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"FFA48B49-8645-4C42-8B43-96E81DF8D4E0"}
 */
var _cssId = null;

/**
 * @param	{Object}	obj Data object passed to all markup methods
 *
 * @properties={typeid:24,uuid:"399C16F5-0026-4B84-A2B5-01231434CB1A"}
 */
function CONTROLLER_default(obj, results) {

	var configuration = globals.CMS.data.block_configure

	// check login
	if ( configuration.loginRequired ) {

		//get login
		var login = globals.WEBc_session_getData(obj.session_server.record.session_id, configuration.loginObjName)

		if ( login ) {
			// show swc view
			return _VIEW_swc(obj, results, login)
		}
		else {
			// show no login view
			return _VIEW_no_login(configuration.loginLink)
		}
	}
	else {
		// show swc view
		return _VIEW_swc(obj, results, login)
	}

}

/**
 * Update display as needed when block selected.
 *
 * @properties={typeid:24,uuid:"7ABCE520-07F0-4ED3-B01B-EB3348DAEE3B"}
 */
function INIT_data() {
	//get data
	var data = globals.CMS.ui.getData(controller.getName())
	var dataConfig = globals.CMS.ui.getConfig(controller.getName())

	//save down form variables so records can be changed
	_module = data.module
	_form = data.form
	_width = dataConfig.width
	_height = dataConfig.height
	_transparent = dataConfig.transparent
	_cssId = dataConfig.cssId
	_cssClass = dataConfig.cssClass
	_loginRequired = dataConfig.loginRequired
	_loginObjName = dataConfig.loginObjName
	_loginLink = dataConfig.loginLink

	//set status of variables
	var editMode = globals.CMS.ui.getEdit()

	elements.var_module.visible = editMode
	elements.var_module__display.visible = !editMode
	elements.var_form.visible = editMode
	elements.var_form__display.visible = !editMode
	elements.var_width.transparent = editMode
	elements.var_width.editable = editMode
	elements.var_height.transparent = editMode
	elements.var_height.editable = editMode
	elements.var_transparent.readOnly = !editMode
	elements.var_cssId.transparent = editMode
	elements.var_cssId.editable = editMode
	elements.var_cssClass.transparent = editMode
	elements.var_cssClass.editable = editMode
	elements.var_loginRequired.readOnly = !editMode
	elements.var_loginObjName.transparent = editMode
	elements.var_loginObjName.editable = editMode

	//fill valuelist appropriately
	SET_forms()
}

/**
 * @properties={typeid:24,uuid:"0829A6D7-6C0C-4C82-92B7-6BB50829DD5F"}
 */
function SET_forms() {
	//only show forms from selected module when in top level form
	if (application.__parent__.solutionPrefs && _module) {
		//get from repository via queries way
		if (!solutionPrefs.repository.api) {
			//load formNames for report module
			var moduleForms = solutionPrefs.repository.allForms[_module]
			var formNames = new Array()
			var j = 0

			//check to make sure that there are forms in the report module
			if (moduleForms) {
				for (var i in moduleForms) {
					formNames[j++] = moduleForms[i].formName
				}
			}
		}
		//get from the workspace
		else if (solutionPrefs.repository.workspace) {
			var moduleForms = solutionPrefs.repository.workspace[_module]

			var formNames = new Array()
			var j = 0

			if (moduleForms) { //check to make sure module_filter has a loaded value (they chose something)
				for (var i in moduleForms) {
					formNames[j++] = i
				}
			}
		}
	}
	//when in reporting module, show forms anyway
	else {
		var formNames = forms.allnames
	}

	formNames = formNames.sort()

	//set valuelist
	application.setValueListItems('WEB_webclient_forms', formNames)
}

/**
 * Build a data object that defines this block. Called when creating a new block.
 * Used to create all meta data associated with this block (register a block in the CMS)
 *
 * @returns {Object} Data object that is used to register a block
 *
 * @properties={typeid:24,uuid:"EB40FAF9-1C53-4828-91FF-2087CBDF39BE"}
 */
function INIT_block() {

	// main data object to build
	var block = {}

	// block record data
	block.record = {
	        block_name			: 'Servoy Web Client',
			block_description	: "Integrates Servoy's web client",
			form_name			: 'WEB_0F__servoy_webclient'
		}

	// block views
	block.views = globals.WEBc_block_type_getMethods(controller.getName(),"VIEW")

	// block client actions - Block
	block.clientActionsBlock = globals.WEBc_block_type_getMethods(controller.getName(),"BLOCK")

	// block client actions - Page
	block.clientActionsPage = globals.WEBc_block_type_getMethods(controller.getName(),"PAGE")

	// block web actions
	block.webActions = globals.WEBc_block_type_getMethods(controller.getName(),"WEB")

	// block data points
	block.data = {
		module : 'TEXT',
		form : 'TEXT'
	}

	// block configure data points
	block.blockConfigure = {
		width : 'INTEGER',
		height : 'INTEGER',
		transparent : 'INTEGER',
		cssId : 'TEXT',
		cssClass : 'TEXT',
		loginRequired : 'INTEGER',
		loginObjName : 'TEXT',
		loginLink : 'TEXT'
	}

	// block response data points
	block.blockResponse = {

	}

	return block
}

/**
 * Handle changed data.
 *
 * @param {Object} oldValue old value
 * @param {Object} newValue new value
 * @param {JSEvent} event the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"EAF1F56A-8C93-4502-BDA4-BB78E2FFB658"}
 */
function FLD_module__data_change(oldValue, newValue, event) {
	//save data
	globals.WEBc_block_fld_data_change__data(oldValue, newValue, event)

	//refresh form valuelist
	SET_forms()
}

/**
 * @properties={typeid:24,uuid:"18FF2C5F-9F17-4AE7-BBF8-C6DD844A92C7"}
 */
function _VIEW_swc(obj, results, login) {

		//get solution model form
	var smForm = solutionModel.getForm(obj.block_data.form)
	//for width
	var defaultWidth = (smForm) ? smForm.width : 0
	//for height
	var totalHeight = 0
	if (smForm) {
		for (var i in smForm.getParts()) {
			totalHeight += smForm.getParts()[i].height
		}
	}
	var defaultHeight = totalHeight

	//TODO: abstract the passing in of record
	var record		= (login && login.customer && login.customer.loginID) ? login.customer.loginID : ''

	var url 		= globals.WEBc_markup_link_servlet(obj)
	var module		= '_dsa_mosaic_WEB_cms'
	var method		= 'WEB_servoy_wc_controller'
	var template	= '\n\
							Servoy Web Client cannot load\n\
						'
	var html = template.replace(/\t/g, '')
	html = utils.stringReplace(html, "{{url}}", url)
	html = utils.stringReplace(html, "{{module}}", module)
	html = utils.stringReplace(html, "{{method}}", method)
	html = utils.stringReplace(html, "{{form}}", obj.block_data.form)
	html = utils.stringReplace(html, "{{session}}", obj.session_server.record.session_id)
	html = utils.stringReplace(html, "{{login}}", obj.block_configure.loginObjName)
	html = utils.stringReplace(html, "{{record}}", record)
	html = utils.stringReplace(html, "{{width}}", obj.block_configure.width || defaultWidth)
	html = utils.stringReplace(html, "{{height}}", obj.block_configure.height || defaultHeight)
	html = utils.stringReplace(html, "{{id}}", obj.block_configure.cssId || 'swc')
	html = utils.stringReplace(html, "{{class}}", obj.block_configure.cssClass)
	html = utils.stringReplace(html, "{{transparent}}", (obj.block_configure.transparent ? 'true' : 'false'))

	return html
}

/**
 * @properties={typeid:24,uuid:"1EF67102-5F99-4C5A-A20D-1A98EABC3A8C"}
 */
function _VIEW_no_login(pageID) {

	// get page link token
	var pageLink = globals.CMS.token.getPage(pageID)

	// return markup to login page
	return '
Your session has expired. Please login again.
'
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"B206DA14-241E-41A0-946A-FCB31366D1DE"}
 */
function PICK_page(input,pageRec,event) {
	//show page picker when in edit mode
	if (input instanceof JSEvent && globals.WEBc_block_getEdit()) {
		globals.WEBc_page_picker(PICK_page,input)
	}
	//page picked
	else if (pageRec) {
		if (event) {
			switch (event.getElementName().substr(4)) {
				case 'loginLink':
					_loginLink = pageRec.page_name
					globals.WEBc_block_setConfig(event,'loginLink',pageRec.id_page.toString())
					break
			}
		}
	}
}
<|endoftext|>


<commit_before>/*global define*/
define([
    'oro/datagrid/action/ajaxdelete-action',
    'oroui/js/delete-confirmation',
    'oroui/js/mediator'
], function (AjaxdeleteAction, DeleteConfirmation, mediator) {
    'use strict';

    var AjaxdeletefieldAction;

    /**
     * Ajax delete field action, shows confirmation dialogue, triggers REST AJAX request
     * and on success - refresh current page
     *
     * @export  oro/datagrid/action/ajaxdeletefield-action
     * @class   oro.datagrid.action.AjaxdeleteAction
     * @extends oro.datagrid.action.AjaxdeleteAction
     */
    AjaxdeletefieldAction = AjaxdeleteAction.extend({
        confirmation: true,

        /** @property {Function} */
        confirmModalConstructor: DeleteConfirmation,

        defaultMessages: {
            confirm_title: 'Delete Confirmation',
            confirm_content: 'oro.entityextend.delete_field.confirm_content',
            confirm_ok: 'Yes',
            confirm_cancel: 'Cancel',
            success: 'Removed.',
            error: 'Not removed.',
            empty_selection: 'Please, select item to remove.'
        },

        _onAjaxSuccess: function (data) {
            mediator.execute('refreshPage');

            AjaxdeleteAction.__super__._onAjaxSuccess.apply(this, arguments);
        }
    });

    return AjaxdeletefieldAction;
});

<commit_msg>BAP-5774: Ability to delete serialized fields<commit_after>/*global define*/
define([
    'oro/datagrid/action/ajaxdelete-action',
    'oroui/js/delete-confirmation',
    'oroui/js/mediator'
], function (AjaxdeleteAction, DeleteConfirmation, mediator) {
    'use strict';

    var AjaxdeletefieldAction;

    /**
     * Ajax delete field action, shows confirmation dialogue, triggers REST AJAX request
     * and on success - refresh current page
     *
     * @export  oro/datagrid/action/ajaxdeletefield-action
     * @class   oro.datagrid.action.AjaxdeletefieldAction
     * @extends oro.datagrid.action.AjaxdeleteAction
     */
    AjaxdeletefieldAction = AjaxdeleteAction.extend({
        confirmation: true,

        /** @property {Function} */
        confirmModalConstructor: DeleteConfirmation,

        defaultMessages: {
            confirm_title: 'Delete Confirmation',
            confirm_content: 'oro.entityextend.delete_field.confirm_content',
            confirm_ok: 'Yes',
            confirm_cancel: 'Cancel',
            success: 'Removed.',
            error: 'Not removed.',
            empty_selection: 'Please, select item to remove.'
        },

        _onAjaxSuccess: function (data) {
            mediator.execute('refreshPage');

            AjaxdeleteAction.__super__._onAjaxSuccess.apply(this, arguments);
        }
    });

    return AjaxdeletefieldAction;
});

<|endoftext|>


<commit_before>function Hero(nameHero, health) {
    this.nameHero = nameHero;
    this.health = health || 150;
    this.shotDamages = 15;
    this.kickDamages = 5;
}

Hero.prototype = {
    shot(otherHero){
        otherHero.health -= this.shotDamages;

    },
    kick(otherHero){
        otherHero.health -= this.kickDamages;

    },
    getLifeValue(){
        return this.health;
    }
};

function SuperHero (nameHero, health) {
    Hero.call(this, nameHero, health);
    this.shotDamages = 25;
    this.kickDamages = 10;
}

SuperHero.prototype.__proto__ = Hero.prototype;

let hero1 = {},
    hero2 = {};

function getRandomHeroHealth() {
    return Math.floor(Math.random() * (50) + 100);
}

function getRandomHero(nameHero) {
    let variable;
    let randomHero = Math.floor(Math.random() * (2) + 1);
    if (randomHero === 1) {
        variable = new Hero(nameHero,getRandomHeroHealth());
        variable.type = 'Hero';
    } else {
        variable = new SuperHero(nameHero,getRandomHeroHealth());
        variable.type = 'SuperHero';
    }
    return variable;
}

function newGame() {
    hero1 = getRandomHero('hero1');
    hero2 = getRandomHero('hero2');
    console.log(hero1);
    console.log(hero2);
}

function heroWin() {
    if (hero1.health <= 0){
        console.log('victory the secondary hero');
        process.exit(0);
    } else if (hero2.health <= 0){
        console.log('victory the first hero');
        process.exit(0);
    }
}

function control() {
    console.log('Welcome n - newGame, q - kick hero1, w - shot hero1, ' +
        'o - kick hero2, p - shot hero2,e e - exit.');
    process.stdin.setRawMode(true);
    newGame();
    process.stdin.on('readable', () => {
        const key = process.stdin.read();

        if (!key) return;
        const strKey = String(key).toLowerCase();
        heroWin();

        switch (strKey) {
            case 'n':
                newGame();
                break;
            case 'q':
                hero1.kick(hero2);
                console.log(`${hero1.nameHero}, kick, ${hero1.kickDamages}, from, ${hero2.nameHero}, ${hero2.health}`);
                break;
            case 'w':
                hero1.shot(hero2);
                console.log(`${hero1.nameHero}, shot, ${hero1.shotDamages}, from, ${hero2.nameHero}, ${hero2.health}`);
                break;
            case 'o':
                hero2.kick(hero1);
                console.log(`${hero2.nameHero}, kick, ${hero2.kickDamages}, from, ${hero1.nameHero}, ${hero1.health}`);
                break;
            case 'p':
                hero2.shot(hero1);
                console.log(`${hero2.nameHero}, shot, ${hero2.shotDamages}, from, ${hero1.nameHero}, ${hero1.health}`);
                break;
            case 'e':
                process.exit(0);
        }
    });
}

control();

<commit_msg>Homework_6 fix<commit_after>function Hero(nameHero, health) {
    this.nameHero = nameHero;
    this.health = health || 150;
    this.shotDamages = 15;
    this.kickDamages = 5;
}

Hero.prototype = {
    shot(otherHero){
        otherHero.health -= this.shotDamages;

    },
    kick(otherHero){
        otherHero.health -= this.kickDamages;

    },
    getLifeValue(){
        return this.health;
    }
};

function SuperHero (nameHero, health) {
    Hero.call(this, nameHero, health);
    this.shotDamages = 25;
    this.kickDamages = 10;
}

SuperHero.prototype.__proto__ = Hero.prototype;

let hero1 = {},
    hero2 = {};

function getRandomHeroHealth() {
    return Math.floor(Math.random() * (50) + 100);
}

function getRandomHero(nameHero) {
    let variable;
    let randomHero = Math.floor(Math.random() * (2) + 1);
    if (randomHero === 1) {
        variable = new Hero(nameHero,getRandomHeroHealth());
        variable.type = 'Hero';
    } else {
        variable = new SuperHero(nameHero,getRandomHeroHealth());
        variable.type = 'SuperHero';
    }
    return variable;
}

function newGame() {
    hero1 = getRandomHero('hero1');
    hero2 = getRandomHero('hero2');
    console.log(hero1);
    console.log(hero2);
}

function heroWin() {
    if (hero1.health <= 0){
        console.log('victory the secondary hero');
        process.exit(0);
    } else if (hero2.health <= 0){
        console.log('victory the first hero');
        process.exit(0);
    }
}

function control() {
    console.log('Welcome n - newGame, q - kick hero1, w - shot hero1, o - kick hero2, p - shot hero2,e e - exit.');
    process.stdin.setRawMode(true);
    newGame();
    process.stdin.on('readable', () => {
        const key = process.stdin.read();

        if (!key) return;
        const strKey = String(key).toLowerCase();
        heroWin();

        switch (strKey) {
            case 'n':
                newGame();
                break;
            case 'q':
                hero1.kick(hero2);
                console.log(`${hero1.nameHero}, kick, ${hero1.kickDamages}, from, ${hero2.nameHero}, ${hero2.health}`);
                break;
            case 'w':
                hero1.shot(hero2);
                console.log(`${hero1.nameHero}, shot, ${hero1.shotDamages}, from, ${hero2.nameHero}, ${hero2.health}`);
                break;
            case 'o':
                hero2.kick(hero1);
                console.log(`${hero2.nameHero}, kick, ${hero2.kickDamages}, from, ${hero1.nameHero}, ${hero1.health}`);
                break;
            case 'p':
                hero2.shot(hero1);
                console.log(`${hero2.nameHero}, shot, ${hero2.shotDamages}, from, ${hero1.nameHero}, ${hero1.health}`);
                break;
            case 'e':
                process.exit(0);
        }
    });
}

control();

<|endoftext|>


<commit_before>import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';
import sinon from 'sinon';

const { run } = Ember;

const SELECTORS = {
  passingComponent: '[data-test-selector="violations-page__passing-component"]'
};

let application;
let sandbox;

module('Acceptance | auto-run', {
  beforeEach: function() {
    application = startApp();
    sandbox = sinon.sandbox.create();
  },

  afterEach: function() {
    sandbox.restore();
    Ember.run(application, 'destroy');
  }
});

test('should run the function when visiting a new route', function(assert) {
  const callbackStub = sandbox.stub(run.backburner.options.render, 'after');

  visit('/');

  andThen(() => {
    assert.ok(callbackStub.calledOnce);
    assert.equal(currentPath(), 'violations');
  });
});

test('should run the function whenever a render occurs', function(assert) {
  const callbackStub = sandbox.stub(run.backburner.options.render, 'after');

  visit('/').then(() => {

    assert.ok(callbackStub.calledOnce);
    assert.equal(currentPath(), 'violations');

    click(`${SELECTORS.passingComponent}`);

    andThen(() => {
      assert.ok(callbackStub.calledTwice);
    });
  });
});
<commit_msg>Reduce flakiness in auto-run test<commit_after>import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';
import sinon from 'sinon';

const { run } = Ember;

const SELECTORS = {
  passingComponent: '[data-test-selector="violations-page__passing-component"]'
};

let application;
let sandbox;

module('Acceptance | auto-run', {
  beforeEach: function() {
    application = startApp();
    sandbox = sinon.sandbox.create();
  },

  afterEach: function() {
    sandbox.restore();
    Ember.run(application, 'destroy');
  }
});

test('should run the function when visiting a new route', function(assert) {
  const callbackStub = sandbox.stub(run.backburner.options.render, 'after');

  visit('/');

  andThen(() => {
    assert.ok(callbackStub.calledOnce);
    assert.equal(currentPath(), 'violations');
  });
});

test('should run the function whenever a render occurs', function(assert) {
  const callbackStub = sandbox.stub(run.backburner.options.render, 'after');
  let callCount = 0;

  visit('/');

  andThen(() => {
    callCount = callbackStub.callCount;
    assert.ok(callCount > 0, 'afterRender called at least once for initial visit');
    assert.equal(currentPath(), 'violations');
  });

  click(SELECTORS.passingComponent);

  andThen(() => {
    assert.ok(callbackStub.callCount > callCount, 'afterRender called more than before');
  });
});
<|endoftext|>


<commit_before>// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
// TODO: does 'arguments.callee.caller' work?

var Dispatcher = (function($, window, undefined) {
    var Dispatcher = function() {
      var that = this;

      var table = {};

      var ajaxUrl = 'ajax.cgi';

      var on = function(message, host, handler) {
        if (handler === undefined) {
          handler = host;
          host = arguments.callee.caller;
        }
        if (table[message] === undefined) {
          table[message] = [];
        }
        table[message].push([host, handler]);
        return this;
      };

      // Notify listeners that we encountered an error in an asynch call
      var inAsynchError = false; // To avoid error avalanches
      var handleAsynchError = function(e) {
        if (!inAsynchError) {
          inAsynchError = true;
          // TODO: Hook printout into dispatch elsewhere?
          console.warn('Handled async error:', e);
          that.post('dispatchAsynchError', [e]);
          inAsynchError = false;
        } else {
          console.warn('Dropped asynch error:', e);
        }
      };

      var post = function(asynch, message, args, returnType) {
        if (typeof(asynch) !== 'number') {
          // no asynch parameter
          returnType = args;
          args = message;
          message = asynch;
          asynch = null;
        }
        if (args === undefined) {
          args = [];
        }
        var results = [];
        // DEBUG: if (typeof(message) != "string" || !(message.match(/mouse/) || message == "hideComment")) console.log(message, args);

        if (typeof(message) === 'function') {
          // someone was lazy and sent a simple function
          var host = arguments.callee.caller;
          if (asynch !== null) {
            result = setTimeout(function() {
              try {
                message.apply(host, args);
              } catch(e) {
                that.handleAsynchError(e);
              }
            }, asynch);
          } else {
            result = message.apply(host, args);
          }
          results.push(result);
        } else {
          // a proper message, propagate to all interested parties
          var todo = table[message];
          if (todo !== undefined) {
            $.each(todo, function(itemNo, item) {
              var result;
              if (asynch !== null) {
                result = setTimeout(function() {
                  try {
                    item[1].apply(item[0], args);
                  } catch (e) {
                    that.handleAsynchError(e);
                  }
                }, asynch);
              } else {
                result = item[1].apply(item[0], args);
              }
              results.push(result);
            });
/* DEBUG
          } else {
            console.warn('Message ' + message + ' has no subscribers.'); // DEBUG
*/
          }
        }
        if (returnType == 'any') {
          var i = results.length;
          while (i--) {
            if (results[i] !== false) return results[i];
          }
          return false;
        }
        if (returnType == 'all') {
          var i = results.length;
          while (i--) {
            if (results[i] === false) return results[i];
          }
        }
        return results;
      };

      var proxy = function(destination, message) {
        this.on(message, function() {
          destination.post(message, Array.prototype.slice.call(arguments));
        });
      };

      var dispatcher = {
        on: on,
        post: post,
        proxy: proxy,
      };
      Dispatcher.dispatchers.push(dispatcher);
      return dispatcher;
    };

    Dispatcher.dispatchers = [];
    Dispatcher.post = function(asynch, message, args, returnType) {
      $.each(Dispatcher.dispatchers, function(dispatcherNo, dispatcher) {
        dispatcher.post(asynch, message, args, returnType);
      });
    };

    return Dispatcher;
})(jQuery, window);
<commit_msg>#1053 - Clean up brat UI integration - Added markers where it seems we made changes to the brat JS (might not cover all our modifications).<commit_after>// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
// TODO: does 'arguments.callee.caller' work?

var Dispatcher = (function($, window, undefined) {
    var Dispatcher = function() {
      var that = this;

      var table = {};

// WEBANNO EXTENSION BEGIN
      var ajaxUrl = 'ajax.cgi';
// WEBANNO EXTENSION END

      var on = function(message, host, handler) {
        if (handler === undefined) {
          handler = host;
          host = arguments.callee.caller;
        }
        if (table[message] === undefined) {
          table[message] = [];
        }
        table[message].push([host, handler]);
        return this;
      };

      // Notify listeners that we encountered an error in an asynch call
      var inAsynchError = false; // To avoid error avalanches
      var handleAsynchError = function(e) {
        if (!inAsynchError) {
          inAsynchError = true;
          // TODO: Hook printout into dispatch elsewhere?
          console.warn('Handled async error:', e);
          that.post('dispatchAsynchError', [e]);
          inAsynchError = false;
        } else {
          console.warn('Dropped asynch error:', e);
        }
      };

      var post = function(asynch, message, args, returnType) {
        if (typeof(asynch) !== 'number') {
          // no asynch parameter
          returnType = args;
          args = message;
          message = asynch;
          asynch = null;
        }
        if (args === undefined) {
          args = [];
        }
        var results = [];
        // DEBUG: if (typeof(message) != "string" || !(message.match(/mouse/) || message == "hideComment")) console.log(message, args);

        if (typeof(message) === 'function') {
          // someone was lazy and sent a simple function
          var host = arguments.callee.caller;
          if (asynch !== null) {
            result = setTimeout(function() {
              try {
                message.apply(host, args);
              } catch(e) {
                that.handleAsynchError(e);
              }
            }, asynch);
          } else {
            result = message.apply(host, args);
          }
          results.push(result);
        } else {
          // a proper message, propagate to all interested parties
          var todo = table[message];
          if (todo !== undefined) {
            $.each(todo, function(itemNo, item) {
              var result;
              if (asynch !== null) {
                result = setTimeout(function() {
                  try {
                    item[1].apply(item[0], args);
                  } catch (e) {
                    that.handleAsynchError(e);
                  }
                }, asynch);
              } else {
                result = item[1].apply(item[0], args);
              }
              results.push(result);
            });
/* DEBUG
          } else {
            console.warn('Message ' + message + ' has no subscribers.'); // DEBUG
*/
          }
        }
        if (returnType == 'any') {
          var i = results.length;
          while (i--) {
            if (results[i] !== false) return results[i];
          }
          return false;
        }
        if (returnType == 'all') {
          var i = results.length;
          while (i--) {
            if (results[i] === false) return results[i];
          }
        }
        return results;
      };

      var proxy = function(destination, message) {
        this.on(message, function() {
          destination.post(message, Array.prototype.slice.call(arguments));
        });
      };

      var dispatcher = {
        on: on,
        post: post,
        proxy: proxy,
      };
      Dispatcher.dispatchers.push(dispatcher);
      return dispatcher;
    };

    Dispatcher.dispatchers = [];
    Dispatcher.post = function(asynch, message, args, returnType) {
      $.each(Dispatcher.dispatchers, function(dispatcherNo, dispatcher) {
        dispatcher.post(asynch, message, args, returnType);
      });
    };

    return Dispatcher;
})(jQuery, window);
<|endoftext|>


<commit_before>/* jslint asi:true, browser:true */

if (Lexis === undefined) var Lexis = {};

Lexis.normalize = function(lexis_document) {
    var words = lexis_document.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "word");
    var metas = lexis_document.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "meta");
    var iterator = lexis_document.createNodeIterator(lexis_document.documentElement, NodeFilter.SHOW_ELEMENT, null);
    var i;
    if (words.length) {
        for (i = 0; i < metas.length; i++) {
            lexis_document.documentElement.insertBefore(metas.item(i), words.item(0));
        }
    }
    var current_node;
    while (current_node = iterator.nextNode()) {  // jshint ignore:line
        switch (current_node.tagName) {
            case "words":
                if (!words.item(i).hasAttributeNS("http://leaf.faint.xyz/lexisml", "lemma")) {
                    var forms = words.item(i).getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "form");
                    if (forms.length) words.item(i).setAttributeNS("http://leaf.faint.xyz/lexisml", "lemma", forms.item(0).textContent);
                    else words.item(i).setAttributeNS("http://leaf.faint.xyz/lexisml", "lemma", "");
                }
                /* falls through */
            case "lexis":
                for (i = current_node.childNodes.length - 1; i >= 0; i--) {
                    if (current_node.childNodes.item(i).nodeType !== Node.ELEMENT_NODE) current_node.removeChild(current_node.childNodes.item(i));
                }
                break;
            case "meta":
                while (current_node.firstChild) {
                    current_node.removeChild(current_node.firstChild);
                }

        }
    }
}
<commit_msg>fixed word stuff; added affix<commit_after>/* jslint asi:true, browser:true */

if (Lexis === undefined) var Lexis = {};

Lexis.normalize = function(lexis_document) {
    var words = lexis_document.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "word");
    var metas = lexis_document.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "meta");
    var iterator = lexis_document.createNodeIterator(lexis_document.documentElement, NodeFilter.SHOW_ELEMENT, null);
    var i;
    if (words.length) {
        for (i = 0; i < metas.length; i++) {
            lexis_document.documentElement.insertBefore(metas.item(i), words.item(0));
        }
    }
    var current_node;
    while (current_node = iterator.nextNode()) {  // jshint ignore:line
        switch (current_node.tagName) {
            case "word":
            case "affix":
                if (!current_node.hasAttributeNS("http://leaf.faint.xyz/lexisml", "lemma")) {
                    var forms = current_node.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "form");
                    if (forms.length) current_node.setAttributeNS("http://leaf.faint.xyz/lexisml", "lemma", forms.item(0).textContent);
                    else current_node.setAttributeNS("http://leaf.faint.xyz/lexisml", "lemma", "");
                }
                /* falls through */
            case "lexis":
                for (i = current_node.childNodes.length - 1; i >= 0; i--) {
                    if (current_node.childNodes.item(i).nodeType !== Node.ELEMENT_NODE) current_node.removeChild(current_node.childNodes.item(i));
                }
                break;
            case "meta":
                while (current_node.firstChild) {
                    current_node.removeChild(current_node.firstChild);
                }

        }
    }
}
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'dummy',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<commit_msg>setup production baseURL<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'dummy',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
    ENV.baseURL = '/ember-mb-menu';
  }

  return ENV;
};
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'dummy',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<commit_msg>Prod config updates<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'dummy',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
    ENV.locationType = 'hash';
    ENV.baseURL = '/ember-cli-transformicons'
  }

  return ENV;
};
<|endoftext|>


<commit_before>const expect = require("chai").expect;
const fs = require("fs");
const _ = require("lodash");
const moment = require("moment");
const wdajaxstub = require("webdriverajaxstub");

const helpers = require("../global-setup");

describe("Weather module", function() {
	let app;

	helpers.setupTimeout(this);

	async function setup(responses) {
		app = await helpers.startApplication({
			args: ["js/electron.js"]
		});

		wdajaxstub.init(app.client, responses);

		app.client.setupStub();
	}

	afterEach(function() {
		return helpers.stopApplication(app);
	});

	describe("Current weather", function() {
		function generateWeather(extendedData = {}) {
			return JSON.stringify(_.merge({}, {
				coord:{
					lon: 11.58,
					lat: 48.14
				},
				weather:[
					{
						id: 615,
						main: "Snow",
						description: "light rain and snow",
						icon: "13d"
					},
					{
						id: 500,
						main: "Rain",
						description: "light rain",
						icon: "10d"
					}
				],
				base: "stations",
				main:{
					temp: 1.49,
					pressure: 1005,
					humidity: 93.7,
					temp_min: 1,
					temp_max: 2
				},
				visibility: 7000,
				wind:{
					speed: 11.8,
					deg: 250
				},
				clouds:{
					all: 75
				},
				dt: 1547387400,
				sys:{
					type: 1,
					id: 1267,
					message: 0.0031,
					country: "DE",
					sunrise: 1547362817,
					sunset: 1547394301
				},
				id: 2867714,
				name: "Munich",
				cod: 200
			}, extendedData));
		}

		let template;

		before(function() {
			template = fs.readFileSync(__dirname + '../../../../modules/default/weather/current.njk', 'utf8');
		});

		describe("Default configuration", function() {
			before(function() {
				process.env.MM_CONFIG_FILE = "tests/configs/modules/weather/currentweather_default.js";
			});

			it("should render wind speed and wind direction", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				return app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(2)', '6 WSW', 10000);
			});

			it("should render sunrise", async function() {
				const sunrise = moment().startOf('day').unix();
				const sunset = moment().startOf('day').unix();

				const weather = generateWeather({sys: {sunrise, sunset}});
				await setup([weather, template]);

				await app.client.waitForExist(".weather .normal.medium span.wi.dimmed.wi-sunrise", 10000);

				return app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(4)', '12:00 am', 10000);
			});

			it("should render sunset", async function() {
				const sunrise = moment().startOf('day').unix();
				const sunset = moment().endOf('day').unix();

				const weather = generateWeather({sys: {sunrise, sunset}});
				await setup([weather, template]);

				await app.client.waitForExist(".weather .normal.medium span.wi.dimmed.wi-sunset", 10000);

				return app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(4)', '11:59 pm', 10000);
			});

			it("should render temperature with icon", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				await app.client.waitForExist(".weather .large.light span.wi.weathericon.wi-snow", 10000);

				return app.client.waitUntilTextExists('.weather .large.light span.bright', '1.5°', 10000);
			});

			it("should render feels like temperature", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				return app.client.waitUntilTextExists('.weather .normal.medium span.dimmed', 'Feels -5.6°', 10000);
			});
		});

		const wait = () => new Promise(res => setTimeout(res, 3000));

		describe("Configuration Options", function() {
			before(function() {
				process.env.MM_CONFIG_FILE = "tests/configs/modules/weather/currentweather_options.js";
			});

			it("should render useBeaufort = false", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				return app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(2)', '12', 10000);
			});

			it("should render showWindDirectionAsArrow = true", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				await app.client.waitForExist('.weather .normal.medium sup i.fa-long-arrow-up', 10000);
				const element = await app.client.getHTML('.weather .normal.medium sup i.fa-long-arrow-up');

				expect(element).to.include("transform:rotate(250deg);");
			});

			it("should render showHumidity = true", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				await app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(3)', '93', 10000);
				return app.client.waitForExist('.weather .normal.medium sup i.wi-humidity', 10000);
			});

			it("should render degreeLabel = true", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				await app.client.waitUntilTextExists('.weather .large.light span.bright', '1°C', 10000);

				return app.client.waitUntilTextExists('.weather .normal.medium span.dimmed', 'Feels -6°C', 10000);
			});
		});

		describe("Current weather units", function() {
			before(function() {
				process.env.MM_CONFIG_FILE = "tests/configs/modules/weather/currentweather_units.js";
			});

			it("should render imperial units", async function() {
				const weather = generateWeather({
					main:{
						temp: 1.49 * 9 / 5 + 32,
						temp_min: 1 * 9 / 5 + 32,
						temp_max: 2 * 9 / 5 + 32
					},
					wind:{
						speed: 11.8 * 2.23694
					},
				});
				await setup([weather, template]);

				await app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(2)', '6 WSW', 10000);
				await app.client.waitUntilTextExists('.weather .large.light span.bright', '34,7°', 10000);
				return app.client.waitUntilTextExists('.weather .normal.medium span.dimmed', '22,0°', 10000);
			});

			it("should render decimalSymbol = ','", async function() {
				const weather = generateWeather({
					main:{
						temp: 1.49 * 9 / 5 + 32,
						temp_min: 1 * 9 / 5 + 32,
						temp_max: 2 * 9 / 5 + 32
					},
					wind:{
						speed: 11.8 * 2.23694
					},
				});
				await setup([weather, template]);

				await app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(3)', '93,7', 10000);
				await app.client.waitUntilTextExists('.weather .large.light span.bright', '34,7°', 10000);
				return app.client.waitUntilTextExists('.weather .normal.medium span.dimmed', '22,0°', 10000);
			});
		});
	});
});
<commit_msg>adjust tests to new translations<commit_after>const expect = require("chai").expect;
const fs = require("fs");
const _ = require("lodash");
const moment = require("moment");
const wdajaxstub = require("webdriverajaxstub");

const helpers = require("../global-setup");

describe("Weather module", function() {
	let app;

	helpers.setupTimeout(this);

	async function setup(responses) {
		app = await helpers.startApplication({
			args: ["js/electron.js"]
		});

		wdajaxstub.init(app.client, responses);

		app.client.setupStub();
	}

	afterEach(function() {
		return helpers.stopApplication(app);
	});

	describe("Current weather", function() {
		function generateWeather(extendedData = {}) {
			return JSON.stringify(_.merge({}, {
				coord:{
					lon: 11.58,
					lat: 48.14
				},
				weather:[
					{
						id: 615,
						main: "Snow",
						description: "light rain and snow",
						icon: "13d"
					},
					{
						id: 500,
						main: "Rain",
						description: "light rain",
						icon: "10d"
					}
				],
				base: "stations",
				main:{
					temp: 1.49,
					pressure: 1005,
					humidity: 93.7,
					temp_min: 1,
					temp_max: 2
				},
				visibility: 7000,
				wind:{
					speed: 11.8,
					deg: 250
				},
				clouds:{
					all: 75
				},
				dt: 1547387400,
				sys:{
					type: 1,
					id: 1267,
					message: 0.0031,
					country: "DE",
					sunrise: 1547362817,
					sunset: 1547394301
				},
				id: 2867714,
				name: "Munich",
				cod: 200
			}, extendedData));
		}

		let template;

		before(function() {
			template = fs.readFileSync(__dirname + '../../../../modules/default/weather/current.njk', 'utf8');
		});

		describe("Default configuration", function() {
			before(function() {
				process.env.MM_CONFIG_FILE = "tests/configs/modules/weather/currentweather_default.js";
			});

			it("should render wind speed and wind direction", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				return app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(2)', '6 WSW', 10000);
			});

			it("should render sunrise", async function() {
				const sunrise = moment().startOf('day').unix();
				const sunset = moment().startOf('day').unix();

				const weather = generateWeather({sys: {sunrise, sunset}});
				await setup([weather, template]);

				await app.client.waitForExist(".weather .normal.medium span.wi.dimmed.wi-sunrise", 10000);

				return app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(4)', '12:00 am', 10000);
			});

			it("should render sunset", async function() {
				const sunrise = moment().startOf('day').unix();
				const sunset = moment().endOf('day').unix();

				const weather = generateWeather({sys: {sunrise, sunset}});
				await setup([weather, template]);

				await app.client.waitForExist(".weather .normal.medium span.wi.dimmed.wi-sunset", 10000);

				return app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(4)', '11:59 pm', 10000);
			});

			it("should render temperature with icon", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				await app.client.waitForExist(".weather .large.light span.wi.weathericon.wi-snow", 10000);

				return app.client.waitUntilTextExists('.weather .large.light span.bright', '1.5°', 10000);
			});

			it("should render feels like temperature", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				return app.client.waitUntilTextExists('.weather .normal.medium span.dimmed', 'Feels like -5.6°', 10000);
			});
		});

		const wait = () => new Promise(res => setTimeout(res, 3000));

		describe("Configuration Options", function() {
			before(function() {
				process.env.MM_CONFIG_FILE = "tests/configs/modules/weather/currentweather_options.js";
			});

			it("should render useBeaufort = false", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				return app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(2)', '12', 10000);
			});

			it("should render showWindDirectionAsArrow = true", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				await app.client.waitForExist('.weather .normal.medium sup i.fa-long-arrow-up', 10000);
				const element = await app.client.getHTML('.weather .normal.medium sup i.fa-long-arrow-up');

				expect(element).to.include("transform:rotate(250deg);");
			});

			it("should render showHumidity = true", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				await app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(3)', '93', 10000);
				return app.client.waitForExist('.weather .normal.medium sup i.wi-humidity', 10000);
			});

			it("should render degreeLabel = true", async function() {
				const weather = generateWeather();
				await setup([weather, template]);

				await app.client.waitUntilTextExists('.weather .large.light span.bright', '1°C', 10000);

				return app.client.waitUntilTextExists('.weather .normal.medium span.dimmed', 'Feels like -6°C', 10000);
			});
		});

		describe("Current weather units", function() {
			before(function() {
				process.env.MM_CONFIG_FILE = "tests/configs/modules/weather/currentweather_units.js";
			});

			it("should render imperial units", async function() {
				const weather = generateWeather({
					main:{
						temp: 1.49 * 9 / 5 + 32,
						temp_min: 1 * 9 / 5 + 32,
						temp_max: 2 * 9 / 5 + 32
					},
					wind:{
						speed: 11.8 * 2.23694
					},
				});
				await setup([weather, template]);

				await app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(2)', '6 WSW', 10000);
				await app.client.waitUntilTextExists('.weather .large.light span.bright', '34,7°', 10000);
				return app.client.waitUntilTextExists('.weather .normal.medium span.dimmed', '22,0°', 10000);
			});

			it("should render decimalSymbol = ','", async function() {
				const weather = generateWeather({
					main:{
						temp: 1.49 * 9 / 5 + 32,
						temp_min: 1 * 9 / 5 + 32,
						temp_max: 2 * 9 / 5 + 32
					},
					wind:{
						speed: 11.8 * 2.23694
					},
				});
				await setup([weather, template]);

				await app.client.waitUntilTextExists('.weather .normal.medium span:nth-child(3)', '93,7', 10000);
				await app.client.waitUntilTextExists('.weather .large.light span.bright', '34,7°', 10000);
				return app.client.waitUntilTextExists('.weather .normal.medium span.dimmed', '22,0°', 10000);
			});
		});
	});
});
<|endoftext|>


<commit_before>var _ = require("lodash");
var async = require("async");

var shlog = require(global.gBaseDir + "/src/shlog.js");
var sh = require(global.gBaseDir + "/src/shutil.js");
var ShGame = require(global.gBaseDir + "/src/shgame.js");
var ShUser = require(global.gBaseDir + "/src/shuser.js");

var db = global.db;

var user = exports;

user.desc = "utility functions for shelly modules";
user.functions = {
  get: {desc: "get user object", params: {}, security: []},
  set: {desc: "set user object", params: {user: {dtype: "object"}}, security: []},
  profiles: {desc: "get public user infoformation", params: {users : {dtype: "array"}}, security: []},
};

user.pre = function (req, res, cb) {
  shlog.info("user.pre");
  // user is always preloaded now in session check

  // SWD - eventually check security session.uid has rights to params.uid
  cb(0);
};

user.post = function (req, res, cb) {
  shlog.info("user.post");

  if (_.isObject(req.session.user)) {
    req.session.user.save(function (error, data) {
      // ingore
    });
  }

  // SWD: work out pre/post user save later, for now save on every set
  cb(0);
};

user.get = function (req, res, cb) {
  shlog.info(req.env.user);
  cb(0, sh.event("event.user.get", req.session.user.getData()));
};

user.set = function (req, res, cb) {
  var newUser = req.params.user;

  req.session.user.setData(newUser);

  cb(0, sh.event("event.user.get", req.session.user.getData()));
};

user.profiles = function (req, res, cb) {
  var userIds = req.params.users;
  sh.fillProfiles(userIds, function (error, data) {
    if (!error) {
      cb(0, sh.event("event.user.profiles", data));
    } else {
      cb(error, data);
    }
  });
};<commit_msg>fix jslint error;<commit_after>var _ = require("lodash");
var async = require("async");

var shlog = require(global.gBaseDir + "/src/shlog.js");
var sh = require(global.gBaseDir + "/src/shutil.js");
var ShGame = require(global.gBaseDir + "/src/shgame.js");
var ShUser = require(global.gBaseDir + "/src/shuser.js");

var db = global.db;

var user = exports;

user.desc = "utility functions for shelly modules";
user.functions = {
  get: {desc: "get user object", params: {}, security: []},
  set: {desc: "set user object", params: {user: {dtype: "object"}}, security: []},
  profiles: {desc: "get public user infoformation", params: {users : {dtype: "array"}}, security: []}
};

user.pre = function (req, res, cb) {
  shlog.info("user.pre");
  // user is always preloaded now in session check

  // SWD - eventually check security session.uid has rights to params.uid
  cb(0);
};

user.post = function (req, res, cb) {
  shlog.info("user.post");

  if (_.isObject(req.session.user)) {
    req.session.user.save(function (error, data) {
      // ingore
    });
  }

  // SWD: work out pre/post user save later, for now save on every set
  cb(0);
};

user.get = function (req, res, cb) {
  shlog.info(req.env.user);
  cb(0, sh.event("event.user.get", req.session.user.getData()));
};

user.set = function (req, res, cb) {
  var newUser = req.params.user;

  req.session.user.setData(newUser);

  cb(0, sh.event("event.user.get", req.session.user.getData()));
};

user.profiles = function (req, res, cb) {
  var userIds = req.params.users;
  sh.fillProfiles(userIds, function (error, data) {
    if (!error) {
      cb(0, sh.event("event.user.profiles", data));
    } else {
      cb(error, data);
    }
  });
};<|endoftext|>


<commit_before>(function ($) {
    $.fn.extend({
        expandoControl: function (getControllees, options) {
            if (typeof getControllees !== "function")
                return this;

            var _this = $(this);
            var __cookieName = "Exp";
            var settings = $.extend({
                path: "/",
                key: _this.selector,
                collapse: false,
                remember: true
            }, options);
            _this.each(function (index, element) {
                var controller = $(element);
                var glyph = $("");

                glyph.data("controllees", getControllees(controller));

                if (glyph.data("controllees").length === 0 || glyph.data("controllees").height() < 1) {
                    return;
                }

                if ((settings.remember && "closed" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path }))
                    || settings.collapse
                    || (controller.closest("li").hasClass("collapsed") && !(settings.remember && "open" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path })))) {
                    glyph.addClass("closed").data("controllees").hide();
                }
                else if (settings.collapse) {

                }

                glyph.click(function () {
                    var __this = $(this);

                    if (settings.remember && !settings.collapse) { // remembering closed state as true because that's not the default - doesn't make sense to remember if the controllees are always to be collapsed by default
                        // need to allow specified keys since these selectors could get *really* long
                        $.orchard.setting(__cookieName, !__this.hasClass("closed") ? "closed" : "open", { key: settings.key + "-" + controller.text(), path: settings.path });
                    }

                    if (__this.hasClass("closed") || __this.hasClass("closing")) {
                        __this.data("controllees").slideDown(300, function () { __this.removeClass("opening").removeClass("closed").addClass("open"); });
                        __this.addClass("opening");
                    }
                    else {
                        __this.data("controllees").slideUp(300, function () { __this.removeClass("closing").removeClass("open").addClass("closed"); });
                        __this.addClass("closing");
                    }

                    return false;
                });

                controller.prepend(glyph);
            });

            return this;
        }
    });

    $(".bulk-actions-auto select").change(function () {
        $(this).closest("form").find(".apply-bulk-actions-auto:first").click();
    });

    $("[itemprop~='RemoveUrl']").click(function () {
        // don't show the confirm dialog if the link is also UnsafeUrl, as it will already be handled in base.js
        if ($(this).filter("[itemprop~='UnsafeUrl']").length == 1) {
            return false;
        }

        return confirm(confirmRemoveMessage);
    });

    $(".check-all").change(function () {
    	$(this).parents("table.items").find(":checkbox").prop('checked', $(this).prop("checked"));
 	});
})(jQuery);

/*
 console-shim 1.0.2
 https://github.com/kayahr/console-shim
 Copyright (C) 2011 Klaus Reimer <k@ailis.de>
 Licensed under the MIT license
 (See http://www.opensource.org/licenses/mit-license)
*/
function f() { return function () { } }
(function () {
    function c(a, l, b) { var c = Array.prototype.slice.call(arguments, 2); return function () { var b = c.concat(Array.prototype.slice.call(arguments, 0)); a.apply(l, b) } } window.console || (window.console = {}); var a = window.console; if (!a.log) if (window.log4javascript) { var b = log4javascript.getDefaultLogger(); a.log = c(b.info, b); a.debug = c(b.debug, b); a.info = c(b.info, b); a.warn = c(b.warn, b); a.error = c(b.error, b) } else a.log = f(); a.debug || (a.debug = a.log); a.info || (a.info = a.log); a.warn || (a.warn = a.log); a.error || (a.error = a.log);
    if (null != window.__consoleShimTest__ || eval("/*@cc_on @_jscript_version \x3c\x3d 9@*/")) b = function (d) { var b, e, c; d = Array.prototype.slice.call(arguments, 0); c = d.shift(); e = d.length; if (1 < e && !1 !== window.__consoleShimTest__) { "string" != typeof d[0] && (d.unshift("%o"), e += 1); for (b = (b = d[0].match(/%[a-z]/g)) ? b.length + 1 : 1; b < e; b += 1) d[0] += " %o" } Function.apply.call(c, a, d) }, a.log = c(b, window, a.log), a.debug = c(b, window, a.debug), a.info = c(b, window, a.info), a.warn = c(b, window, a.warn), a.error = c(b, window, a.error); a.assert || (a.assert =
    function () { var d = Array.prototype.slice.call(arguments, 0); d.shift() || (d[0] = "Assertion failed: " + d[0], a.error.apply(a, d)) }); a.dir || (a.dir = a.log); a.dirxml || (a.dirxml = a.log); a.exception || (a.exception = a.error); if (!a.time || !a.timeEnd) { var g = {}; a.time = function (a) { g[a] = (new Date).getTime() }; a.timeEnd = function (b) { var c = g[b]; c && (a.log(b + ": " + ((new Date).getTime() - c) + "ms"), delete g[b]) } } a.table || (a.table = function (b, c) {
        var e, g, j, h, k; if (b && b instanceof Array && b.length) {
            if (!c || !(c instanceof Array)) for (e in c =
            [], b[0]) b[0].hasOwnProperty(e) && c.push(e); e = 0; for (g = b.length; e < g; e += 1) { j = []; h = 0; for (k = c.length; h < k; h += 1) j.push(b[e][c[h]]); Function.apply.call(a.log, a, j) }
        }
    }); a.clear || (a.clear = f()); a.trace || (a.trace = f()); a.group || (a.group = f()); a.groupCollapsed || (a.groupCollapsed = f()); a.groupEnd || (a.groupEnd = f()); a.timeStamp || (a.timeStamp = f()); a.profile || (a.profile = f()); a.profileEnd || (a.profileEnd = f()); a.count || (a.count = f())
})();<commit_msg>Removing mixed tabs and spaces, consistifying to spaces.<commit_after>(function ($) {
    $.fn.extend({
        expandoControl: function (getControllees, options) {
            if (typeof getControllees !== "function")
                return this;

            var _this = $(this);
            var __cookieName = "Exp";
            var settings = $.extend({
                path: "/",
                key: _this.selector,
                collapse: false,
                remember: true
            }, options);
            _this.each(function (index, element) {
                var controller = $(element);
                var glyph = $("");

                glyph.data("controllees", getControllees(controller));

                if (glyph.data("controllees").length === 0 || glyph.data("controllees").height() < 1) {
                    return;
                }

                if ((settings.remember && "closed" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path }))
                    || settings.collapse
                    || (controller.closest("li").hasClass("collapsed") && !(settings.remember && "open" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path })))) {
                    glyph.addClass("closed").data("controllees").hide();
                }
                else if (settings.collapse) {

                }

                glyph.click(function () {
                    var __this = $(this);

                    if (settings.remember && !settings.collapse) { // remembering closed state as true because that's not the default - doesn't make sense to remember if the controllees are always to be collapsed by default
                        // need to allow specified keys since these selectors could get *really* long
                        $.orchard.setting(__cookieName, !__this.hasClass("closed") ? "closed" : "open", { key: settings.key + "-" + controller.text(), path: settings.path });
                    }

                    if (__this.hasClass("closed") || __this.hasClass("closing")) {
                        __this.data("controllees").slideDown(300, function () { __this.removeClass("opening").removeClass("closed").addClass("open"); });
                        __this.addClass("opening");
                    }
                    else {
                        __this.data("controllees").slideUp(300, function () { __this.removeClass("closing").removeClass("open").addClass("closed"); });
                        __this.addClass("closing");
                    }

                    return false;
                });

                controller.prepend(glyph);
            });

            return this;
        }
    });

    $(".bulk-actions-auto select").change(function () {
        $(this).closest("form").find(".apply-bulk-actions-auto:first").click();
    });

    $("[itemprop~='RemoveUrl']").click(function () {
        // don't show the confirm dialog if the link is also UnsafeUrl, as it will already be handled in base.js
        if ($(this).filter("[itemprop~='UnsafeUrl']").length == 1) {
            return false;
        }

        return confirm(confirmRemoveMessage);
    });

    $(".check-all").change(function () {
        $(this).parents("table.items").find(":checkbox").prop('checked', $(this).prop("checked"));
    });
})(jQuery);

/*
 console-shim 1.0.2
 https://github.com/kayahr/console-shim
 Copyright (C) 2011 Klaus Reimer <k@ailis.de>
 Licensed under the MIT license
 (See http://www.opensource.org/licenses/mit-license)
*/
function f() { return function () { } }
(function () {
    function c(a, l, b) { var c = Array.prototype.slice.call(arguments, 2); return function () { var b = c.concat(Array.prototype.slice.call(arguments, 0)); a.apply(l, b) } } window.console || (window.console = {}); var a = window.console; if (!a.log) if (window.log4javascript) { var b = log4javascript.getDefaultLogger(); a.log = c(b.info, b); a.debug = c(b.debug, b); a.info = c(b.info, b); a.warn = c(b.warn, b); a.error = c(b.error, b) } else a.log = f(); a.debug || (a.debug = a.log); a.info || (a.info = a.log); a.warn || (a.warn = a.log); a.error || (a.error = a.log);
    if (null != window.__consoleShimTest__ || eval("/*@cc_on @_jscript_version \x3c\x3d 9@*/")) b = function (d) { var b, e, c; d = Array.prototype.slice.call(arguments, 0); c = d.shift(); e = d.length; if (1 < e && !1 !== window.__consoleShimTest__) { "string" != typeof d[0] && (d.unshift("%o"), e += 1); for (b = (b = d[0].match(/%[a-z]/g)) ? b.length + 1 : 1; b < e; b += 1) d[0] += " %o" } Function.apply.call(c, a, d) }, a.log = c(b, window, a.log), a.debug = c(b, window, a.debug), a.info = c(b, window, a.info), a.warn = c(b, window, a.warn), a.error = c(b, window, a.error); a.assert || (a.assert =
    function () { var d = Array.prototype.slice.call(arguments, 0); d.shift() || (d[0] = "Assertion failed: " + d[0], a.error.apply(a, d)) }); a.dir || (a.dir = a.log); a.dirxml || (a.dirxml = a.log); a.exception || (a.exception = a.error); if (!a.time || !a.timeEnd) { var g = {}; a.time = function (a) { g[a] = (new Date).getTime() }; a.timeEnd = function (b) { var c = g[b]; c && (a.log(b + ": " + ((new Date).getTime() - c) + "ms"), delete g[b]) } } a.table || (a.table = function (b, c) {
        var e, g, j, h, k; if (b && b instanceof Array && b.length) {
            if (!c || !(c instanceof Array)) for (e in c =
            [], b[0]) b[0].hasOwnProperty(e) && c.push(e); e = 0; for (g = b.length; e < g; e += 1) { j = []; h = 0; for (k = c.length; h < k; h += 1) j.push(b[e][c[h]]); Function.apply.call(a.log, a, j) }
        }
    }); a.clear || (a.clear = f()); a.trace || (a.trace = f()); a.group || (a.group = f()); a.groupCollapsed || (a.groupCollapsed = f()); a.groupEnd || (a.groupEnd = f()); a.timeStamp || (a.timeStamp = f()); a.profile || (a.profile = f()); a.profileEnd || (a.profileEnd = f()); a.count || (a.count = f())
})();<|endoftext|>


<commit_before>var gamename = 'smurfs.zip';
var game_file = null;
var bios_filenames = 'coleco.zip'.split(' ');
var bios_files = {};
var file_countdown = 0;
if (bios_filenames.length !== 0 && bios_filenames[0] !== '') {
  file_countdown += bios_filenames.length;
}
if (gamename !== '') {
  file_countdown++;
}

var newCanvas = document.createElement('canvas');
newCanvas.id = 'canvas';
newCanvas.width = 256;
newCanvas.height = 256;
var holder = document.getElementById('canvasholder');
holder.appendChild(newCanvas);

var fetch_file = function(url, cb) {
	var xhr = new XMLHttpRequest();
	xhr.open("GET", url, true);
	xhr.responseType = "arraybuffer";
	xhr.onload = function(e) {
		var ints = new Int8Array(xhr.response);
		cb(ints);
	};
	xhr.send();
};

var Module = {
	'arguments': ["coleco","-verbose","-rompath",".","-cart",gamename,"-window","-resolution","256x192","-nokeepaspect"],
	print: (function() {
		var element = document.getElementById('output');
		return function(text) {
			text = text.replace(/&/g, "&");
			text = text.replace(/</g, "<");
			text = text.replace(/>/g, ">");
			text = text.replace('\n', '
', 'g');
			element.innerHTML += text + '
';
		};
	})(),
	canvas: document.getElementById('canvas'),
	noInitialRun: false,
	preInit: function() {
		// Load the downloaded binary files into the filesystem.
		for (var bios_fname in bios_files) {
			if (bios_files.hasOwnProperty(bios_fname)) {
				Module['FS_createDataFile']('/', bios_fname, bios_files[bios_fname], true, true);
			}
		}
		Module['FS_createDataFile']('/', gamename, game_file, true, true);
	}
};

var update_countdown = function() {
  file_countdown -= 1;
  if (file_countdown === 0) {
    var headID = document.getElementsByTagName("head")[0];
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src = 'messcolecovision.js.gz';
		headID.appendChild(newScript);
  }
};

// Fetch the BIOS and the game we want to run.
for (var i=0; i < bios_filenames.length; i++) {
  var fname = bios_filenames[i];
  if (fname === "") {
    continue;
  }
  fetch_file(fname, function(data) { bios_files[fname] = data; update_countdown(); });
}

if (gamename !== "") {
  fetch_file(gamename, function(data) { game_file = data; update_countdown(); });
}
<commit_msg>Replace tabs with spaces<commit_after>var gamename = 'smurfs.zip';
var game_file = null;
var bios_filenames = 'coleco.zip'.split(' ');
var bios_files = {};
var file_countdown = 0;
if (bios_filenames.length !== 0 && bios_filenames[0] !== '') {
  file_countdown += bios_filenames.length;
}
if (gamename !== '') {
  file_countdown++;
}

var newCanvas = document.createElement('canvas');
newCanvas.id = 'canvas';
newCanvas.width = 256;
newCanvas.height = 256;
var holder = document.getElementById('canvasholder');
holder.appendChild(newCanvas);

var fetch_file = function(url, cb) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "arraybuffer";
  xhr.onload = function(e) {
    var ints = new Int8Array(xhr.response);
    cb(ints);
  };
  xhr.send();
};

var Module = {
  'arguments': ["coleco","-verbose","-rompath",".","-cart",gamename,"-window","-resolution","256x192","-nokeepaspect"],
  print: (function() {
    var element = document.getElementById('output');
    return function(text) {
      text = text.replace(/&/g, "&");
      text = text.replace(/</g, "<");
      text = text.replace(/>/g, ">");
      text = text.replace('\n', '
', 'g');
      element.innerHTML += text + '
';
    };
  })(),
  canvas: document.getElementById('canvas'),
  noInitialRun: false,
  preInit: function() {
    // Load the downloaded binary files into the filesystem.
    for (var bios_fname in bios_files) {
      if (bios_files.hasOwnProperty(bios_fname)) {
        Module['FS_createDataFile']('/', bios_fname, bios_files[bios_fname], true, true);
      }
    }
    Module['FS_createDataFile']('/', gamename, game_file, true, true);
  }
};

var update_countdown = function() {
  file_countdown -= 1;
  if (file_countdown === 0) {
    var headID = document.getElementsByTagName("head")[0];
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = 'messcolecovision.js.gz';
    headID.appendChild(newScript);
  }
};

// Fetch the BIOS and the game we want to run.
for (var i=0; i < bios_filenames.length; i++) {
  var fname = bios_filenames[i];
  if (fname === "") {
    continue;
  }
  fetch_file(fname, function(data) { bios_files[fname] = data; update_countdown(); });
}

if (gamename !== "") {
  fetch_file(gamename, function(data) { game_file = data; update_countdown(); });
}
<|endoftext|>


<commit_before>route.controller("CentreController", function($scope, $location, $routeParams, addressStorage, rest, globalMessages, validation, errorRender) {

	$scope.centre = {
		formSelector: "#centre-type-form",
		form: {
			hours: [],
		},
		modalId: "centre-modal-form",
		modalSelector: "#centre-modal-form",
		modal: {},
		facility: {
			formSelector: "#facility-form",
			form: {
				hours: [],
			},
			modalId: "facility-modal-form",
			modalSelector: "#facility-modal-form",
			modal: {},
		},
		select: {
			country: [
			         {value: "CZ", name: "Česká republika"},
			         {value: "DE", name: "Německo"},
			         {value: "UK", name: "Velká británie"}
			         ],
			day: [
			      {value: 1, name: "pondělí"},
			      {value: 2, name: "úterý"},
			      {value: 3, name: "středa"},
			      {value: 4, name: "čtvrtek"},
			      {value: 5, name: "pátek"},
			      {value: 6, name: "sobota"},
			      {value: 7, name: "neděle"},
			      ]
		}
	};

	/**
	 * Zobrazi detail centra
	 */
	var showCentre = function(address) {
		rest.get(address, null, function(response) {
			$scope.centre.detail = response.data;
		});
	}

	/**
	 * Vraci seznam sportovist
	 */
	var getCentres = function() {
		addressStorage.get("centre", function(address) {
			rest.get(address, null, function(response) {
//				console.log(response.data);
				$scope.centre.list = response.data;
			});
		});
	}

	/**
	 * Vraci seznam typu zarizeni
	 */
	var getTypes = function() {
		addressStorage.get("facilityType", function(address) {
			rest.get(address, null, function(response) {
//				console.log(response.data);
				$scope.centre.facility.type = response.data;
			});
		});
	}

	var centreId = $routeParams.centreId;
//	console.log($routeParams.centreId);
	if (centreId != null) {
		addressStorage.get("centre", function(address) {
			showCentre(address + centreId);
		});
	} else {
		getCentres();
	}

	/**
	 * Zavola se pri otevreni modalniho okna za ucelem vytvoreni sportoviste
	 */
	$scope.centre.openCentreAddModal = function() {
		errorRender.clear(angular.element($scope.centre.formSelector));
		$scope.centre.form = {
			country: "CZ",
			hours: []
		};
		$scope.centre.modal = {
			btn: "Přidat",
			submit: function() {
				errorRender.clear(angular.element($scope.centre.formSelector));
				$scope.centre.addCentre();
			}
		};
	}

	/**
	 * Zavola se pri otevreni modalniho okna za ucelem vytvoreni noveho zarizeni
	 */
	$scope.centre.openFacilityAddModal = function(address) {
		errorRender.clear(angular.element($scope.centre.facility.formSelector));
		getTypes();
		$scope.centre.facility.form = {
			hours: []
		};
		$scope.centre.facility.modal = {
			btn: "Přidat",
			submit: function() {
				errorRender.clear(angular.element($scope.centre.facility.formSelector));
				$scope.centre.addFacility(address);
			}
		};
	}

	/**
	 * Zavola se pri otevreni modalniho okna za ucelem upraveni sportoviste
	 */
	$scope.centre.openCentreUpdateModal = function(centre) {
		errorRender.clear(angular.element($scope.centre.formSelector));
		rest.get(centre.url, null, function(response) {
			$scope.centre.form = {
				street: response.data.street,
				city: response.data.city,
				country: response.data.country,
				buildingNumber: response.data.building,
				phone: response.data.phone,
				hours: []
			};
			angular.forEach(response.data.hours, function(h) {
				$scope.centre.form.hours.push({
					day: h.day,
					open: h.open,
					close: h.close
				});
			});
//			console.log(response.data);
		});

		$scope.centre.modal = {
			btn: "Upravit",
			submit: function() {
				errorRender.clear(angular.element($scope.centre.formSelector));
				$scope.centre.updateCentre(centre.url);
			}
		};
	}

	/**
	 * Zavola se pri otevreni modalniho okna za ucelem upraveni zarizeni
	 */
	$scope.centre.openFacilityUpdateModal = function(index, centre) {
		errorRender.clear(angular.element($scope.centre.facility.formSelector));
		getTypes();
		$scope.centre.facility.form = {
			type: centre.type.id,
			hours: []
		};
		angular.forEach(centre.hours, function(h) {
			$scope.centre.facility.form.hours.push({
				day: h.day,
				open: h.open,
				close: h.close
			});
		});
//			console.log(response.data);

		$scope.centre.facility.modal = {
			btn: "Upravit",
			submit: function() {
				errorRender.clear(angular.element($scope.centre.facility.formSelector));
				$scope.centre.updateFacility(index, centre.url);
			}
		};
	}

	/**
	 * Zavre modalni okno
	 */
	$scope.centre.closeCentreModal = function() {
		angular.element($scope.centre.modalSelector).modal("hide");
	}

	/**
	 * Zavre modalni okno
	 */
	$scope.centre.closeFacilityModal = function() {
		angular.element($scope.centre.facility.modalSelector).modal("hide");
	}

	/**
	 * Prida sportoviste
	 */
	$scope.centre.addCentre = function() {
		$scope.centre.applyValidation(function () {
//			console.log($scope.centre.form);
			addressStorage.get("centre", function(address) {
				rest.post(address, $scope.centre.form, function(response) {
					$scope.centre.closeCentreModal();
					globalMessages.push("success", "Sportoviště bylo přidáno");
					getCentres();
				});
			});
		});
	}

	/**
	 * Prida zarizeni
	 */
	$scope.centre.addFacility = function(address) {
		$scope.centre.facility.applyValidation(function() {
			console.log($scope.centre.facility.form);
			rest.post(address, $scope.centre.facility.form, function(response) {
				$scope.centre.closeFacilityModal();
				$scope.centre.detail.facilities.push(response.data);
				globalMessages.push("success", "Zařízení bylo přidáno");
			});
		});
	}

	/**
	 * Upravi sportoviste
	 */
	$scope.centre.updateCentre = function(address) {
//		console.log($scope.centre.form);
		$scope.centre.applyValidation(function () {
			rest.put(address, $scope.centre.form, function(response) {
				$scope.centre.closeCentreModal();
				globalMessages.push("success", "Sportoviště bylo upraveno");
				getCentres();
			});
		});
	}

	var getTypeName = function(id) {
		if($scope.centre.facility.type == null) return null;
		var name = null;
		angular.forEach($scope.centre.facility.type.list, function(item) {
			if (item.id == id) {
				name = item.name;
				return ;
			}
		});
		return name
	}

	/**
	 * Upravi sportoviste
	 */
	$scope.centre.updateFacility = function(index, address) {
		$scope.centre.facility.applyValidation(function() {
			rest.put(address, $scope.centre.facility.form, function(response) {
				$scope.centre.closeFacilityModal();
				console.log(index);
				console.log($scope.centre.detail.facilities);
				$scope.centre.detail.facilities[index].hours = $scope.centre.facility.form.hours;
				$scope.centre.detail.facilities[index].type.name = getTypeName($scope.centre.facility.form.type);
				$scope.centre.detail.facilities[index].type.id = $scope.centre.facility.form.type;
				globalMessages.push("success", "Zařízení bylo upraveno");
			});
		});
	}

	/**
	 * Smazat sportoviste
	 */
	$scope.centre.deleteCentre = function(address) {
		if (confirm("Opravdu smazat ?")) {
			rest.delete(address, function(response) {
				globalMessages.push("success", "Sportoviště bylo odebráno");
				getCentres();
			});
		}
	}

	/**
	 * Smazat sportoviste
	 */
	$scope.centre.deleteFacility = function(index, address) {
		if (confirm("Opravdu smazat ?")) {
			rest.delete(address, function(response) {
				globalMessages.push("success", "Zařízení bylo odebráno");
				$scope.centre.detail.facilities.splice(index, 1);
			});
		}
	}

	/**
	 * Prida hodiny do formulare sportoviste
	 */
	$scope.centre.addHours = function() {
		if ($scope.centre.form.hours.length < 7)
			$scope.centre.form.hours.push({});
//		console.log($scope.centre.form.hours);
	}

	/**
	 * Prida hodiny do formulare zarizeni
	 */
	$scope.centre.facility.addHours = function() {
		if ($scope.centre.facility.form.hours.length < 7)
			$scope.centre.facility.form.hours.push({});
//		console.log($scope.centre.facility.form.hours);
	}

	/**
	 * Odebere hodiny z formulare sportoviste
	 */
	$scope.centre.removeHours = function(index) {
		if ($scope.centre.form.hours != null) {
			$scope.centre.form.hours.splice(index, 1);
//			console.log($scope.centre.form.hours);
		}
	}

	/**
	 * Odebere hodiny z formulare zarizeni
	 */
	$scope.centre.facility.removeHours = function(index) {
		if ($scope.centre.facility.form.hours != null) {
			$scope.centre.facility.form.hours.splice(index, 1);
//			console.log($scope.centre.facility.form.hours);
		}
	}

	/**
	 * Validace sportoviste
	 */
	$scope.centre.applyValidation = function(valid, invalid) {
		validation.input("street", $scope.centre.form.street).required().length(125);
		validation.input("city", $scope.centre.form.city).required().length(125);
		validation.input("buildingNumber", $scope.centre.form.buildingNumber).required().length(125);
		validation.input("phone", $scope.centre.form.phone).required().length(125);

		if (validation.isValid()) {
			if (valid != null)
				valid();
		} else {
			errorRender.showErrors(angular.element($scope.centre.formSelector), validation);
			if (invalid != null)
				invalid()
		}
	}

	/**
	 * Validace sportoviste
	 */
	$scope.centre.facility.applyValidation = function(valid, invalid) {
		validation.input("type", $scope.centre.facility.form.type).notValue(null);

		if (validation.isValid()) {
			if (valid != null)
				valid();
		} else {
			errorRender.showErrors(angular.element($scope.centre.facility.formSelector), validation);
			if (invalid != null)
				invalid()
		}
	}

});<commit_msg>oprava cislovani dnu<commit_after>route.controller("CentreController", function($scope, $location, $routeParams, addressStorage, rest, globalMessages, validation, errorRender) {

	$scope.centre = {
		formSelector: "#centre-type-form",
		form: {
			hours: [],
		},
		modalId: "centre-modal-form",
		modalSelector: "#centre-modal-form",
		modal: {},
		facility: {
			formSelector: "#facility-form",
			form: {
				hours: [],
			},
			modalId: "facility-modal-form",
			modalSelector: "#facility-modal-form",
			modal: {},
		},
		select: {
			country: [
			         {value: "CZ", name: "Česká republika"},
			         {value: "DE", name: "Německo"},
			         {value: "UK", name: "Velká británie"}
			         ],
			day: [
			      {value: 2, name: "pondělí"},
			      {value: 3, name: "úterý"},
			      {value: 4, name: "středa"},
			      {value: 5, name: "čtvrtek"},
			      {value: 6, name: "pátek"},
			      {value: 7, name: "sobota"},
			      {value: 1, name: "neděle"},
			      ]
		}
	};

	/**
	 * Zobrazi detail centra
	 */
	var showCentre = function(address) {
		rest.get(address, null, function(response) {
			$scope.centre.detail = response.data;
		});
	}

	/**
	 * Vraci seznam sportovist
	 */
	var getCentres = function() {
		addressStorage.get("centre", function(address) {
			rest.get(address, null, function(response) {
//				console.log(response.data);
				$scope.centre.list = response.data;
			});
		});
	}

	/**
	 * Vraci seznam typu zarizeni
	 */
	var getTypes = function() {
		addressStorage.get("facilityType", function(address) {
			rest.get(address, null, function(response) {
//				console.log(response.data);
				$scope.centre.facility.type = response.data;
			});
		});
	}

	var centreId = $routeParams.centreId;
//	console.log($routeParams.centreId);
	if (centreId != null) {
		addressStorage.get("centre", function(address) {
			showCentre(address + centreId);
		});
	} else {
		getCentres();
	}

	/**
	 * Zavola se pri otevreni modalniho okna za ucelem vytvoreni sportoviste
	 */
	$scope.centre.openCentreAddModal = function() {
		errorRender.clear(angular.element($scope.centre.formSelector));
		$scope.centre.form = {
			country: "CZ",
			hours: []
		};
		$scope.centre.modal = {
			btn: "Přidat",
			submit: function() {
				errorRender.clear(angular.element($scope.centre.formSelector));
				$scope.centre.addCentre();
			}
		};
	}

	/**
	 * Zavola se pri otevreni modalniho okna za ucelem vytvoreni noveho zarizeni
	 */
	$scope.centre.openFacilityAddModal = function(address) {
		errorRender.clear(angular.element($scope.centre.facility.formSelector));
		getTypes();
		$scope.centre.facility.form = {
			hours: []
		};
		$scope.centre.facility.modal = {
			btn: "Přidat",
			submit: function() {
				errorRender.clear(angular.element($scope.centre.facility.formSelector));
				$scope.centre.addFacility(address);
			}
		};
	}

	/**
	 * Zavola se pri otevreni modalniho okna za ucelem upraveni sportoviste
	 */
	$scope.centre.openCentreUpdateModal = function(centre) {
		errorRender.clear(angular.element($scope.centre.formSelector));
		rest.get(centre.url, null, function(response) {
			$scope.centre.form = {
				street: response.data.street,
				city: response.data.city,
				country: response.data.country,
				buildingNumber: response.data.building,
				phone: response.data.phone,
				hours: []
			};
			angular.forEach(response.data.hours, function(h) {
				$scope.centre.form.hours.push({
					day: h.day,
					open: h.open,
					close: h.close
				});
			});
//			console.log(response.data);
		});

		$scope.centre.modal = {
			btn: "Upravit",
			submit: function() {
				errorRender.clear(angular.element($scope.centre.formSelector));
				$scope.centre.updateCentre(centre.url);
			}
		};
	}

	/**
	 * Zavola se pri otevreni modalniho okna za ucelem upraveni zarizeni
	 */
	$scope.centre.openFacilityUpdateModal = function(index, centre) {
		errorRender.clear(angular.element($scope.centre.facility.formSelector));
		getTypes();
		$scope.centre.facility.form = {
			type: centre.type.id,
			hours: []
		};
		angular.forEach(centre.hours, function(h) {
			$scope.centre.facility.form.hours.push({
				day: h.day,
				open: h.open,
				close: h.close
			});
		});
//			console.log(response.data);

		$scope.centre.facility.modal = {
			btn: "Upravit",
			submit: function() {
				errorRender.clear(angular.element($scope.centre.facility.formSelector));
				$scope.centre.updateFacility(index, centre.url);
			}
		};
	}

	/**
	 * Zavre modalni okno
	 */
	$scope.centre.closeCentreModal = function() {
		angular.element($scope.centre.modalSelector).modal("hide");
	}

	/**
	 * Zavre modalni okno
	 */
	$scope.centre.closeFacilityModal = function() {
		angular.element($scope.centre.facility.modalSelector).modal("hide");
	}

	/**
	 * Prida sportoviste
	 */
	$scope.centre.addCentre = function() {
		$scope.centre.applyValidation(function () {
//			console.log($scope.centre.form);
			addressStorage.get("centre", function(address) {
				rest.post(address, $scope.centre.form, function(response) {
					$scope.centre.closeCentreModal();
					globalMessages.push("success", "Sportoviště bylo přidáno");
					getCentres();
				});
			});
		});
	}

	/**
	 * Prida zarizeni
	 */
	$scope.centre.addFacility = function(address) {
		$scope.centre.facility.applyValidation(function() {
			console.log($scope.centre.facility.form);
			rest.post(address, $scope.centre.facility.form, function(response) {
				$scope.centre.closeFacilityModal();
				$scope.centre.detail.facilities.push(response.data);
				globalMessages.push("success", "Zařízení bylo přidáno");
			});
		});
	}

	/**
	 * Upravi sportoviste
	 */
	$scope.centre.updateCentre = function(address) {
//		console.log($scope.centre.form);
		$scope.centre.applyValidation(function () {
			rest.put(address, $scope.centre.form, function(response) {
				$scope.centre.closeCentreModal();
				globalMessages.push("success", "Sportoviště bylo upraveno");
				getCentres();
			});
		});
	}

	var getTypeName = function(id) {
		if($scope.centre.facility.type == null) return null;
		var name = null;
		angular.forEach($scope.centre.facility.type.list, function(item) {
			if (item.id == id) {
				name = item.name;
				return ;
			}
		});
		return name
	}

	/**
	 * Upravi sportoviste
	 */
	$scope.centre.updateFacility = function(index, address) {
		$scope.centre.facility.applyValidation(function() {
			rest.put(address, $scope.centre.facility.form, function(response) {
				$scope.centre.closeFacilityModal();
				console.log(index);
				console.log($scope.centre.detail.facilities);
				$scope.centre.detail.facilities[index].hours = $scope.centre.facility.form.hours;
				$scope.centre.detail.facilities[index].type.name = getTypeName($scope.centre.facility.form.type);
				$scope.centre.detail.facilities[index].type.id = $scope.centre.facility.form.type;
				globalMessages.push("success", "Zařízení bylo upraveno");
			});
		});
	}

	/**
	 * Smazat sportoviste
	 */
	$scope.centre.deleteCentre = function(address) {
		if (confirm("Opravdu smazat ?")) {
			rest.delete(address, function(response) {
				globalMessages.push("success", "Sportoviště bylo odebráno");
				getCentres();
			});
		}
	}

	/**
	 * Smazat sportoviste
	 */
	$scope.centre.deleteFacility = function(index, address) {
		if (confirm("Opravdu smazat ?")) {
			rest.delete(address, function(response) {
				globalMessages.push("success", "Zařízení bylo odebráno");
				$scope.centre.detail.facilities.splice(index, 1);
			});
		}
	}

	/**
	 * Prida hodiny do formulare sportoviste
	 */
	$scope.centre.addHours = function() {
		if ($scope.centre.form.hours.length < 7)
			$scope.centre.form.hours.push({});
//		console.log($scope.centre.form.hours);
	}

	/**
	 * Prida hodiny do formulare zarizeni
	 */
	$scope.centre.facility.addHours = function() {
		if ($scope.centre.facility.form.hours.length < 7)
			$scope.centre.facility.form.hours.push({});
//		console.log($scope.centre.facility.form.hours);
	}

	/**
	 * Odebere hodiny z formulare sportoviste
	 */
	$scope.centre.removeHours = function(index) {
		if ($scope.centre.form.hours != null) {
			$scope.centre.form.hours.splice(index, 1);
//			console.log($scope.centre.form.hours);
		}
	}

	/**
	 * Odebere hodiny z formulare zarizeni
	 */
	$scope.centre.facility.removeHours = function(index) {
		if ($scope.centre.facility.form.hours != null) {
			$scope.centre.facility.form.hours.splice(index, 1);
//			console.log($scope.centre.facility.form.hours);
		}
	}

	/**
	 * Validace sportoviste
	 */
	$scope.centre.applyValidation = function(valid, invalid) {
		validation.input("street", $scope.centre.form.street).required().length(125);
		validation.input("city", $scope.centre.form.city).required().length(125);
		validation.input("buildingNumber", $scope.centre.form.buildingNumber).required().length(125);
		validation.input("phone", $scope.centre.form.phone).required().length(125);

		if (validation.isValid()) {
			if (valid != null)
				valid();
		} else {
			errorRender.showErrors(angular.element($scope.centre.formSelector), validation);
			if (invalid != null)
				invalid()
		}
	}

	/**
	 * Validace sportoviste
	 */
	$scope.centre.facility.applyValidation = function(valid, invalid) {
		validation.input("type", $scope.centre.facility.form.type).notValue(null);

		if (validation.isValid()) {
			if (valid != null)
				valid();
		} else {
			errorRender.showErrors(angular.element($scope.centre.facility.formSelector), validation);
			if (invalid != null)
				invalid()
		}
	}

});<|endoftext|>