<commit_before>;(function (decoraki) { // jshint ignore:line
    'use strict';

    var OrbitControl = decoraki.helpers.OrbitControl;
    var control = decoraki.control;

    //-
    //- Private
    //-

    var _sceneData = {};
    var _colliders = {};

    var _createCameraController = function () {
        _sceneData.cameraController = new OrbitControl(_sceneData.camera, _sceneData.container);
        _sceneData.cameraController.center.set(0, 1.5, 0);
    };

    var _initCamera = function () {
        var viewWidth = _sceneData.container.offsetWidth;
        var viewHeight = _sceneData.container.offsetHeight;

        _sceneData.camera = new THREE.PerspectiveCamera(35, viewWidth / viewHeight, 1, 70);
        _sceneData.camera.position.set(0, 12.940344, 20.31728);
        _createCameraController();
    };

    var _initRenderer = function () {
        var viewWidth = _sceneData.container.offsetWidth;
        var viewHeight = _sceneData.container.offsetHeight;

        _sceneData.renderer = new THREE.WebGLRenderer({
            antialias: true,
            alpha: true,
            preserveDrawingBuffer: false
        });

        _sceneData.renderer.setSize(viewWidth, viewHeight);
        _sceneData.container.appendChild(_sceneData.renderer.domElement);
    };

    var _initMobile = function () {
        _sceneData.camera.position.set(0, 2, 5);
        _sceneData.camera.fov = 12;
        _sceneData.cameraController.center.set(0, 0.3, 0);
        _sceneData.camera.updateProjectionMatrix();
    };

    var _initColliders = function () {
        _colliders.walls = [];
        _colliders.floor = [];
        _colliders.furnitures = [];
    };

    var _initScene = function () {
        _sceneData.scene = new THREE.Scene();
        _sceneData.animationFrame = false;
    };

    var _initSceneObjects = function () {
        _initColliders();
        _initRenderer();
        _initCamera();
    };

    var _init = function () {
        _sceneData.container = control.getContainer();

        if (control.checkWebGL()) {
            _sceneData.container.appendChild(control.getWebGLErrorMessage());
            return;
        }

        _initScene();
        _initSceneObjects();

        if (control.isMobile()) {
            _initMobile();
            return;
        }

        control.createEvent('canvas');
    };

    var _addObject = function (object) {
        _sceneData.scene.add(object);
    };

    var _deleteObject = function (object, modelId) {
        var newColliders = _colliders.furnitures.filter(function (mesh) {
            return mesh.modelId !== modelId;
        });

        _colliders.furnitures = newColliders;

        _sceneData.scene.remove(object);
    };

    var _renderScene = function () {
        if (_sceneData.animationFrame) return;
        _sceneData.cameraController.update();
        _sceneData.renderer.render(_sceneData.scene, _sceneData.camera);
    };

    var _animationFrame = function () {
        if (!_sceneData.animationFrame) return;
        requestAnimationFrame(_animationFrame);
        _sceneData.cameraController.update();
        _sceneData.renderer.render(_sceneData.scene, _sceneData.camera);
    };

    var _startAnimationFrame = function () {
        if (_sceneData.animationFrame) return;
        _sceneData.animationFrame = true;
        _animationFrame();
    };

    var _stopAnimationFrame = function () {
        _sceneData.animationFrame = false;
    };

    var _calculateMousePositionDomElement = function (x, y) {
        var offsetTop = _sceneData.container.parentNode.offsetTop;
        var offsetLeft = _sceneData.container.parentNode.offsetLeft;

        var position = {};

        position.x = ((x - offsetLeft) / _sceneData.renderer.domElement.width) * 2 - 1;
        position.y = -((y - offsetTop) / _sceneData.renderer.domElement.height) * 2 + 1;

        return position;
    };

    var _getObjects = function (fromPos, toPos) {
        var vectorPosition = new THREE.Vector3(fromPos.x, fromPos.y, 0.5);
        var unprojectVector = vectorPosition.unproject(_sceneData.camera);
        var unprojectOffset = unprojectVector.sub(_sceneData.camera.position).normalize();

        var ray = new THREE.Raycaster(_sceneData.camera.position, unprojectOffset);
        var intersected = {};

        if (toPos !== undefined) ray = new THREE.Raycaster(fromPos, toPos.normalize());

        intersected.walls = ray.intersectObjects(_colliders.walls)[0] || undefined;
        intersected.floor = ray.intersectObjects(_colliders.floor)[0] || undefined;
        intersected.furnitures = ray.intersectObjects(_colliders.furnitures)[0] || undefined;

        return intersected;
    };

    var _addColliders = function (mesh, meshType) {
        var add = {};

        add.walls = function () { _colliders.walls.push(mesh); };

        add.floor = function () { _colliders.floor.push(mesh); };

        add.furniture = function () { _colliders.furnitures.push(mesh); };

        if (add[meshType]) add[meshType]();
    };

    var _showObjects = function (objectType) {
        _colliders[objectType].forEach(function (element) {
            var object = element.parent.parent;
            object.visible = true;
        });
    };

    var _hideObjects = function (objectType, value) {
        var objToHide = _colliders[objectType].filter(function (element) {
            return element.parent.parent.placeName === value;
        });

        objToHide.forEach(function (element) {
            var object = element.parent.parent;
            object.visible = false;
        });
    };

    var _updateCamera = function (viewWidth, viewHeight) {
        _sceneData.camera.aspect = viewWidth / viewHeight;
        _sceneData.camera.updateProjectionMatrix();
        _sceneData.renderer.setSize(viewWidth, viewHeight);
    };

    var _resizeScene = function () {
        var canvas = _sceneData.container.childNodes[0];
        var windowWidth = window.innerWidth;

        var mainWidth = windowWidth * 0.96;
        var simulatorBorder = 1;

        var containerWidth = mainWidth;

        if (windowWidth >= 575 && !control.isMobile()) containerWidth = mainWidth * 0.6666;

        var viewWidth = containerWidth - simulatorBorder;
        var viewHeight = _sceneData.container.parentNode.offsetHeight;

        canvas.width = viewWidth;

        _updateCamera(viewWidth, viewHeight);
    };

    //-
    //- Public
    //-

    decoraki.scene = {
        init: function () {
            _init();
        },

        addObject: function (object) {
            _addObject(object);
        },

        deleteObject: function (object, modelId) {
            _deleteObject(object, modelId);
        },

        render: function () {
            _renderScene();
        },

        addColliders: function (mesh, meshType) {
            _addColliders(mesh, meshType);
        },

        hideObjects: function (objectType, value) {
            _hideObjects(objectType, value);
        },

        showObjects: function (objectType) {
            _showObjects(objectType);
        },

        getRenderer: function () {
            return _sceneData.renderer;
        },

        calculateMousePosition: function (x, y) {
            return _calculateMousePositionDomElement(x, y);
        },

        getObjects: function (fromPosition, toPosition) {
            return _getObjects(fromPosition, toPosition);
        },

        resizeScene: function () {
            _resizeScene();
        },

        getScene: function () {
            return _sceneData.scene;
        },

        startAnimationFrame: function () {
            _startAnimationFrame();
        },

        stopAnimationFrame: function () {
            _stopAnimationFrame();
        },

        getCameraPosition: function () {
            return _sceneData.camera.position;
        }
    };

})(window.decoraki = window.decoraki || {});
<commit_msg>add clientWidth and clientHeight<commit_after>;(function (decoraki) { // jshint ignore:line
    'use strict';

    var OrbitControl = decoraki.helpers.OrbitControl;
    var control = decoraki.control;

    //-
    //- Private
    //-

    var _sceneData = {};
    var _colliders = {};

    var _createCameraController = function () {
        _sceneData.cameraController = new OrbitControl(_sceneData.camera, _sceneData.container);
        _sceneData.cameraController.center.set(0, 1.5, 0);
    };

    var _initCamera = function () {
        var viewWidth = _sceneData.container.offsetWidth;
        var viewHeight = _sceneData.container.offsetHeight;

        _sceneData.camera = new THREE.PerspectiveCamera(35, viewWidth / viewHeight, 1, 70);
        _sceneData.camera.position.set(0, 12.940344, 20.31728);
        _createCameraController();
    };

    var _initRenderer = function () {
        var viewWidth = _sceneData.container.offsetWidth;
        var viewHeight = _sceneData.container.offsetHeight;

        _sceneData.renderer = new THREE.WebGLRenderer({
            antialias: true,
            alpha: true,
            preserveDrawingBuffer: false
        });

        _sceneData.renderer.setSize(viewWidth, viewHeight);
        _sceneData.container.appendChild(_sceneData.renderer.domElement);
    };

    var _initMobile = function () {
        _sceneData.camera.position.set(0, 2, 5);
        _sceneData.camera.fov = 12;
        _sceneData.cameraController.center.set(0, 0.3, 0);
        _sceneData.camera.updateProjectionMatrix();
    };

    var _initColliders = function () {
        _colliders.walls = [];
        _colliders.floor = [];
        _colliders.furnitures = [];
    };

    var _initScene = function () {
        _sceneData.scene = new THREE.Scene();
        _sceneData.animationFrame = false;
    };

    var _initSceneObjects = function () {
        _initColliders();
        _initRenderer();
        _initCamera();
    };

    var _init = function () {
        _sceneData.container = control.getContainer();

        if (control.checkWebGL()) {
            _sceneData.container.appendChild(control.getWebGLErrorMessage());
            return;
        }

        _initScene();
        _initSceneObjects();

        if (control.isMobile()) {
            _initMobile();
            return;
        }

        control.createEvent('canvas');
    };

    var _addObject = function (object) {
        _sceneData.scene.add(object);
    };

    var _deleteObject = function (object, modelId) {
        var newColliders = _colliders.furnitures.filter(function (mesh) {
            return mesh.modelId !== modelId;
        });

        _colliders.furnitures = newColliders;

        _sceneData.scene.remove(object);
    };

    var _renderScene = function () {
        if (_sceneData.animationFrame) return;
        _sceneData.cameraController.update();
        _sceneData.renderer.render(_sceneData.scene, _sceneData.camera);
    };

    var _animationFrame = function () {
        if (!_sceneData.animationFrame) return;
        requestAnimationFrame(_animationFrame);
        _sceneData.cameraController.update();
        _sceneData.renderer.render(_sceneData.scene, _sceneData.camera);
    };

    var _startAnimationFrame = function () {
        if (_sceneData.animationFrame) return;
        _sceneData.animationFrame = true;
        _animationFrame();
    };

    var _stopAnimationFrame = function () {
        _sceneData.animationFrame = false;
    };

    var _calculateMousePositionDomElement = function (x, y) {
        var offsetTop = _sceneData.container.parentNode.offsetTop;
        var offsetLeft = _sceneData.container.parentNode.offsetLeft;

        var position = {};

        position.x = ((x - offsetLeft) / _sceneData.renderer.domElement.clientWidth) * 2 - 1;
        position.y = -((y - offsetTop) / _sceneData.renderer.domElement.clientHeight) * 2 + 1;

        return position;
    };

    var _getObjects = function (fromPos, toPos) {
        var vectorPosition = new THREE.Vector3(fromPos.x, fromPos.y, 0.5);
        vectorPosition.unproject(_sceneData.camera);

        var unprojectOffset = vectorPosition.sub(_sceneData.camera.position).normalize();

        var ray = new THREE.Raycaster(_sceneData.camera.position, unprojectOffset);
        var intersected = {};

        if (toPos !== undefined) ray = new THREE.Raycaster(fromPos, toPos.normalize());

        intersected.walls = ray.intersectObjects(_colliders.walls)[0] || undefined;
        intersected.floor = ray.intersectObjects(_colliders.floor)[0] || undefined;
        intersected.furnitures = ray.intersectObjects(_colliders.furnitures)[0] || undefined;

        return intersected;
    };

    var _addColliders = function (mesh, meshType) {
        var add = {};

        add.walls = function () { _colliders.walls.push(mesh); };

        add.floor = function () { _colliders.floor.push(mesh); };

        add.furniture = function () { _colliders.furnitures.push(mesh); };

        if (add[meshType]) add[meshType]();
    };

    var _showObjects = function (objectType) {
        _colliders[objectType].forEach(function (element) {
            var object = element.parent.parent;
            object.visible = true;
        });
    };

    var _hideObjects = function (objectType, value) {
        var objToHide = _colliders[objectType].filter(function (element) {
            return element.parent.parent.placeName === value;
        });

        objToHide.forEach(function (element) {
            var object = element.parent.parent;
            object.visible = false;
        });
    };

    var _updateCamera = function (viewWidth, viewHeight) {
        _sceneData.camera.aspect = viewWidth / viewHeight;
        _sceneData.camera.updateProjectionMatrix();
        _sceneData.renderer.setSize(viewWidth, viewHeight);
    };

    var _resizeScene = function () {
        var canvas = _sceneData.container.childNodes[0];
        var windowWidth = window.innerWidth;

        var mainWidth = windowWidth * 0.96;
        var simulatorBorder = 1;

        var containerWidth = mainWidth;

        if (windowWidth >= 575 && !control.isMobile()) containerWidth = mainWidth * 0.6666;

        var viewWidth = containerWidth - simulatorBorder;
        var viewHeight = _sceneData.container.parentNode.offsetHeight;

        canvas.width = viewWidth;

        _updateCamera(viewWidth, viewHeight);
    };

    //-
    //- Public
    //-

    decoraki.scene = {
        init: function () {
            _init();
        },

        addObject: function (object) {
            _addObject(object);
        },

        deleteObject: function (object, modelId) {
            _deleteObject(object, modelId);
        },

        render: function () {
            _renderScene();
        },

        addColliders: function (mesh, meshType) {
            _addColliders(mesh, meshType);
        },

        hideObjects: function (objectType, value) {
            _hideObjects(objectType, value);
        },

        showObjects: function (objectType) {
            _showObjects(objectType);
        },

        getRenderer: function () {
            return _sceneData.renderer;
        },

        calculateMousePosition: function (x, y) {
            return _calculateMousePositionDomElement(x, y);
        },

        getObjects: function (fromPosition, toPosition) {
            return _getObjects(fromPosition, toPosition);
        },

        resizeScene: function () {
            _resizeScene();
        },

        getScene: function () {
            return _sceneData.scene;
        },

        startAnimationFrame: function () {
            _startAnimationFrame();
        },

        stopAnimationFrame: function () {
            _stopAnimationFrame();
        },

        getCameraPosition: function () {
            return _sceneData.camera.position;
        }
    };

})(window.decoraki = window.decoraki || {});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */
'use strict';

var fs = require('fs'),
    resolve = require('path').resolve,
    Scan = require('scanfs'),

    jslint = require('jslint/lib/linter').lint,
    config = require('./config'),
    log = require('./lib/log'),
    usage,

    // state
    pending,
    errors,
    callback;

function onerr(err) {
    log.error('uh oh.', err);
}

function ondone(err, count) {
    pending--;
    if (!pending) {
        if (errors.length) {
            log.warn(errors);
        }
    	callback(err, 'Done');
    }
}

function tally(pathname, offenses) {
    offenses.forEach(function(o) {
        errors.push({
            file: pathname,
            line: o.line,
            col: o.character,
            reason: o.reason,
            evidence: o.evidence
        });
    });
}

function lint(err, pathname) {
    pending++;
    fs.readFile(pathname, function onread(err, data) {
    	var results;
    	if (!err) {
            results = jslint(data.toString());
            log.debug(results.ok ? '✔' : '✖', pathname);
            if (!results.ok) {
                log.warn('✖ %d error%s in %s', results.errors.length, results.errors.length > 1 ? 's' : '', pathname);
                tally(pathname, results.errors);
            }
    	}
        ondone(err);
    });
}

function isJs(err, pathname, stat) {
    if (stat.isFile() && ('.js' === pathname.slice(-3))) {
        return '.js';
    }
}

function exec(sources, env, cb) {
    var scan = new Scan(env.opts.exclude, isJs);

    // up-scope state
    callback = cb || log.info;
    errors = [];
    pending = 1;

    scan.on('.js', lint);
    scan.on('error', onerr);
    scan.on('done', ondone);
    scan.relatively(sources);
}

function main(env, cb) {
    var exclude = config.exclude.always.concat(env.opts.exclude || []),
        type = env.args.shift() || '',
        sources = env.args.concat();

    if (env.opts.loglevel) {
        log.level = env.opts.loglevel;
    }

    // output dir
    if (!env.opts.directory) {
        env.opts.directory = resolve(env.cwd, 'artifacts/jslint');
    }

    //
    switch (type.toLowerCase()) {
    case 'app':
        break;
    case 'mojit':
        // todo: convert mojit to source path(s)
        break;
    case 'mojito':
        sources = [env.mojito.path];
        break;
    default:
        sources.unshift(type || '.');
        type = 'app';
    }

    // directories to exclude
    env.opts.exclude = exclude.concat(config.exclude[type]);

    exec(sources, env, cb);
}

module.exports = main;

module.exports.usage = usage = [
    'Usage: mojito jslint [options] [type] [source]',
    '  type    "app", "mojit", or "mojito"',
    '  source  mojit name or path',
    '',
    'Options:',
    '  --directory          directory to save results. Default is artifacts/jslint',
    '  -d                   short for --directory',
    '  --exclude <pattern>  pattern of pathnames to exclude from linting',
    '  -e <pattern>         short for -e',
    '  --print              print results to stdout ',
    '  -p                   short for --print',
    '',
    'Examples:',
    '  Run jslint on the app in the current directory',
    '    mojito jslint app',
    '',
    '  Run jslint on mojits/Bar',
    '    mojito jslint mojit mojits/Bar',
    '    mojito jslint mojit Bar',
    '',
    '  Run jslint on the mojito framework',
    '    mojito jslint mojito'
].join('\n');

module.exports.options = [
    {shortName: 'd', hasValue: true, longName: 'directory'},
    {shortName: 'e', hasValue: [String, Array],  longName: 'exclude'},
    {shortName: 'p', hasValue: false, longName: 'print'}
];
<commit_msg>minor log.debug ignored, whsp<commit_after>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */
'use strict';

var fs = require('fs'),
    resolve = require('path').resolve,
    Scan = require('scanfs'),

    jslint = require('jslint/lib/linter').lint,
    config = require('./config'),
    log = require('./lib/log'),
    usage,

    // state
    pending,
    errors,
    callback;

function onerr(err) {
    log.error('uh oh.', err);
}

function ondone(err, count) {
    pending--;
    if (!pending) {
        if (errors.length) {
            log.warn(errors);
        }
        callback(err, 'Done');
    }
}

function onignored(err, pathname) {
    log.debug('ignored', pathname);
}

function tally(pathname, offenses) {
    offenses.forEach(function(o) {
        errors.push({
            file: pathname,
            line: o.line,
            col: o.character,
            reason: o.reason,
            evidence: o.evidence
        });
    });
}

function lint(err, pathname) {
    pending++;
    fs.readFile(pathname, function onread(err, data) {
        var results;
        if (!err) {
            results = jslint(data.toString());
            if (!results.ok) {
                log.error('✖ %d error%s in %s', results.errors.length, results.errors.length > 1 ? 's' : '', pathname);
                tally(pathname, results.errors);
            }
        }
        ondone(err);
    });
}

function isJs(err, pathname, stat) {
    if (stat.isFile() && ('.js' === pathname.slice(-3))) {
        return '.js';
    }
}

function exec(sources, env, cb) {
    var scan = new Scan(env.opts.exclude, isJs);

    // up-scope state
    callback = cb || log.info;
    errors = [];
    pending = 1;

    scan.on('.js', lint);
    scan.on('ignored', onignored);
    scan.on('error', onerr);
    scan.on('done', ondone);
    scan.relatively(sources);
}

function main(env, cb) {
    var exclude = config.exclude.always.concat(env.opts.exclude || []),
        type = env.args.shift() || '',
        sources = env.args.concat();

    if (env.opts.loglevel) {
        log.level = env.opts.loglevel;
    }

    // output dir
    if (!env.opts.directory) {
        env.opts.directory = resolve(env.cwd, 'artifacts/jslint');
    }

    // BC
    switch (type.toLowerCase()) {
    case 'app':
        break;
    case 'mojit':
        // todo: convert mojit to source path(s)
        break;
    case 'mojito':
        sources = [env.mojito.path];
        break;
    default:
        sources.unshift(type || '.');
        type = 'app';
    }

    // directories to exclude
    env.opts.exclude = exclude.concat(config.exclude[type]);

    exec(sources, env, cb);
}

module.exports = main;

module.exports.usage = usage = [
    'Usage: mojito jslint [options] [type] [source]',
    '  type    "app", "mojit", or "mojito"',
    '  source  mojit name or path',
    '',
    'Options:',
    '  --directory          directory to save results. Default is artifacts/jslint',
    '  -d                   short for --directory',
    '  --exclude <pattern>  pattern of pathnames to exclude from linting',
    '  -e <pattern>         short for -e',
    '  --print              print results to stdout ',
    '  -p                   short for --print',
    '',
    'Examples:',
    '  Run jslint on the app in the current directory',
    '    mojito jslint app',
    '',
    '  Run jslint on mojits/Bar',
    '    mojito jslint mojit mojits/Bar',
    '    mojito jslint mojit Bar',
    '',
    '  Run jslint on the mojito framework',
    '    mojito jslint mojito'
].join('\n');

module.exports.options = [
    {shortName: 'd', hasValue: true, longName: 'directory'},
    {shortName: 'e', hasValue: [String, Array],  longName: 'exclude'},
    {shortName: 'p', hasValue: false, longName: 'print'}
];
<|endoftext|>


<commit_before>// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
//
// History:
//
//		1.00 - Released (29 December 2008)
//
//		1.01 - Fixed bug where unbinding would destroy all resize events
//
// License:
//
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC.
//
(function($) {

	$.alerts = {

		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time

		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: ' Ok ',         // text for the OK button
		cancelButton: ' Cancel ', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs

		// Public methods

		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},

		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},

		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},

		// Private methods

		_show: function(title, msg, value, type, callback) {

			$.alerts._hide();
			$.alerts._overlay('show');

			$("BODY").append(
			  '
' +
			    '
'+
			    	'
v.12.2
'+
			    	'

'+
			    	'
 .Community Distributed Cache
'+
			    '
' +
			    '
' +
			      '

' +
				'
' +
			  '
');

			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);

			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed';

			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});

			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '
') );

			$("#popup_container").css({
				width: '640px'

			});

			$.alerts._reposition();
			$.alerts._maintainPosition(true);

			switch( type ) {
				case 'alert':
					$("#popup_message").after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" />
');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_message").after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" />
');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('
<input type="text" size="30" id="popup_prompt" />').after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" />
');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}

			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},

		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},

		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('

');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},

		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;

			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();

			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},

		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}

	}

	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}

	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};

	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};

})(jQuery);<commit_msg>Fix for jquery new version<commit_after>// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
//
// History:
//
//		1.00 - Released (29 December 2008)
//
//		1.01 - Fixed bug where unbinding would destroy all resize events
//
// License:
//
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC.
//
(function($) {

	$.alerts = {

		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time

		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: ' Ok ',         // text for the OK button
		cancelButton: ' Cancel ', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs

		// Public methods

		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},

		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},

		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},

		// Private methods

		_show: function(title, msg, value, type, callback) {

			$.alerts._hide();
			$.alerts._overlay('show');

			$("BODY").append(
			  '
' +
			    '
'+
			    	'
v.12.2
'+
			    	'

'+
			    	'
 .Community Distributed Cache
'+
			    '
' +
			    '
' +
			      '

' +
				'
' +
			  '
');

			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);

			// IE6 Fix
			var pos = 'fixed';

			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});

			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '
') );

			$("#popup_container").css({
				width: '640px'

			});

			$.alerts._reposition();
			$.alerts._maintainPosition(true);

			switch( type ) {
				case 'alert':
					$("#popup_message").after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" />
');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_message").after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" />
');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('
<input type="text" size="30" id="popup_prompt" />').after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" />
');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}

			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},

		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},

		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('

');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},

		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;

			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},

		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}

	}

	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}

	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};

	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};

})(jQuery);<|endoftext|>


<commit_before>/*
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

const {
    CordovaError,
    superspawn: { spawn }
} = require('cordova-common');
const semver = require('semver');

function fetchSdkVersionByType (sdkType) {
    return spawn('xcodebuild', ['-showsdks'])
        .then(output => {
            const regexSdk = new RegExp(`^${sdkType} \\d`);

            const versions = output.split('\n')
                .filter(line => line.trim().match(regexSdk))
                .map(line => line.match(/\d+\.\d+/)[0])
                .sort(exports.compareVersions);

            return versions[0];
        });
}

exports.get_apple_ios_version = () => {
    return fetchSdkVersionByType('iOS');
};

exports.get_apple_osx_version = () => {
    return fetchSdkVersionByType('macOS');
};

exports.get_apple_xcode_version = () => {
    return spawn('xcodebuild', ['-version'])
        .then(output => {
            const versionMatch = /Xcode (.*)/.exec(output);

            if (!versionMatch) return Promise.reject(output);

            return versionMatch[1];
        });
};

/**
 * Gets ios-deploy util version
 * @return {Promise} Promise that either resolved with ios-deploy version
 *                           or rejected in case of error
 */
exports.get_ios_deploy_version = () => {
    return spawn('ios-deploy', ['--version']);
};

/**
 * Gets pod (CocoaPods) util version
 * @return {Promise} Promise that either resolved with pod version
 *                           or rejected in case of error
 */
exports.get_cocoapods_version = () => {
    return spawn('pod', ['--version']);
};

/**
 * Gets ios-sim util version
 * @return {Promise} Promise that either resolved with ios-sim version
 *                           or rejected in case of error
 */
exports.get_ios_sim_version = () => {
    return spawn('ios-sim', ['--version']);
};

/**
 * Gets specific tool version
 * @param  {String} toolName Tool name to check. Known tools are 'xcodebuild', 'ios-sim' and 'ios-deploy'
 * @return {Promise}         Promise that either resolved with tool version
 *                                   or rejected in case of error
 */
exports.get_tool_version = toolName => {
    switch (toolName) {
    case 'xcodebuild': return exports.get_apple_xcode_version();
    case 'ios-sim': return exports.get_ios_sim_version();
    case 'ios-deploy': return exports.get_ios_deploy_version();
    case 'pod': return exports.get_cocoapods_version();
    default: return Promise.reject(new CordovaError(`${toolName} is not valid tool name. Valid names are: 'xcodebuild', 'ios-sim', 'ios-deploy', and 'pod'`));
    }
};

/**
 * Compares two version strings that can be coerced to semver.
 *
 * @param  {String} version1 Version to compare
 * @param  {String} version2 Another version to compare
 * @return {Number}          Negative number if first version is lower than the second,
 *                                    positive otherwise and 0 if versions are equal.
 */
exports.compareVersions = (...args) => {
    const coerceToSemverIfInvalid = v => {
        const semverVersion = semver.parse(v) || semver.coerce(v);
        if (!semverVersion) throw new TypeError(`Invalid Version: ${v}`);
        return semverVersion;
    };

    const semverVersions = args.map(coerceToSemverIfInvalid);
    return semver.compare(...semverVersions);
};

exports.printOrDie = versionName =>
    exports[`get_${versionName}_version`]().then(
        version => {
            console.log(version);
        },
        err => {
            console.error(err);
            process.exit(2);
        }
    );
<commit_msg>feat(versions): print error messages, not error objects (#1186)<commit_after>/*
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

const {
    CordovaError,
    superspawn: { spawn }
} = require('cordova-common');
const semver = require('semver');

function fetchSdkVersionByType (sdkType) {
    return spawn('xcodebuild', ['-showsdks'])
        .then(output => {
            const regexSdk = new RegExp(`^${sdkType} \\d`);

            const versions = output.split('\n')
                .filter(line => line.trim().match(regexSdk))
                .map(line => line.match(/\d+\.\d+/)[0])
                .sort(exports.compareVersions);

            return versions[0];
        });
}

exports.get_apple_ios_version = () => {
    return fetchSdkVersionByType('iOS');
};

exports.get_apple_osx_version = () => {
    return fetchSdkVersionByType('macOS');
};

exports.get_apple_xcode_version = () => {
    return spawn('xcodebuild', ['-version'])
        .then(output => {
            const versionMatch = /Xcode (.*)/.exec(output);
            if (!versionMatch) {
                throw new CordovaError('Could not determine Xcode version from output:\n' + output);
            }
            return versionMatch[1];
        });
};

/**
 * Gets ios-deploy util version
 * @return {Promise} Promise that either resolved with ios-deploy version
 *                           or rejected in case of error
 */
exports.get_ios_deploy_version = () => {
    return spawn('ios-deploy', ['--version']);
};

/**
 * Gets pod (CocoaPods) util version
 * @return {Promise} Promise that either resolved with pod version
 *                           or rejected in case of error
 */
exports.get_cocoapods_version = () => {
    return spawn('pod', ['--version']);
};

/**
 * Gets ios-sim util version
 * @return {Promise} Promise that either resolved with ios-sim version
 *                           or rejected in case of error
 */
exports.get_ios_sim_version = () => {
    return spawn('ios-sim', ['--version']);
};

/**
 * Gets specific tool version
 * @param  {String} toolName Tool name to check. Known tools are 'xcodebuild', 'ios-sim' and 'ios-deploy'
 * @return {Promise}         Promise that either resolved with tool version
 *                                   or rejected in case of error
 */
exports.get_tool_version = toolName => {
    switch (toolName) {
    case 'xcodebuild': return exports.get_apple_xcode_version();
    case 'ios-sim': return exports.get_ios_sim_version();
    case 'ios-deploy': return exports.get_ios_deploy_version();
    case 'pod': return exports.get_cocoapods_version();
    default: return Promise.reject(new CordovaError(`${toolName} is not valid tool name. Valid names are: 'xcodebuild', 'ios-sim', 'ios-deploy', and 'pod'`));
    }
};

/**
 * Compares two version strings that can be coerced to semver.
 *
 * @param  {String} version1 Version to compare
 * @param  {String} version2 Another version to compare
 * @return {Number}          Negative number if first version is lower than the second,
 *                                    positive otherwise and 0 if versions are equal.
 */
exports.compareVersions = (...args) => {
    const coerceToSemverIfInvalid = v => {
        const semverVersion = semver.parse(v) || semver.coerce(v);
        if (!semverVersion) throw new TypeError(`Invalid Version: ${v}`);
        return semverVersion;
    };

    const semverVersions = args.map(coerceToSemverIfInvalid);
    return semver.compare(...semverVersions);
};

exports.printOrDie = versionName =>
    exports[`get_${versionName}_version`]().then(
        version => {
            console.log(version);
        },
        err => {
            console.error(err.message);
            process.exit(2);
        }
    );
<|endoftext|>


<commit_before>var async  = require('async');
var fs     = require('fs');
var utils  = require('../utils');
var Issue  = utils.issues.Issue;

var TSV    = require('./tsv');
var json   = require('./json');
var NIFTI  = require('./nii');
var bval   = require('./bval');
var bvec   = require('./bvec');
var session = require('./session');
var headerFields = require('./headerFields');

var BIDS;
BIDS = {

    options: {},
    issues: [],

    /**
     * Start
     *
     * Takes either a filelist array or
     * a path to a BIDS directory and an
     * options object and starts
     * the validation process and
     * returns the errors and warnings as
     * arguments to the callback.
     */
    start: function (dir, options, callback) {
        var self = BIDS;
        utils.options.parse(options, function (issues, options) {
            if (issues && issues.length > 0) {
                // option parsing issues
                callback({config: issues});
            } else {
                self.options = options;
                BIDS.reset();
                utils.files.readDir(dir, function (files) {
                    self.quickTest(files, function (couldBeBIDS) {
                        if (couldBeBIDS) {
                            self.fullTest(files, callback);
                        } else {
                            // Return an error immediately if quickTest fails
                            var issue = new Issue({
                                code: 61
                            });
                            callback({errors: [issue], warnings: []});
                        }
                    });
                });
            }
        });
    },

    /**
     * Quick Test
     *
     * A quick test to see if it could be a BIDS
     * dataset based on structure/naming. If it
     * could be it will trigger the full validation
     * otherwise it will throw a callback with a
     * generic error.
     */
    quickTest: function (fileList, callback) {
        var couldBeBIDS = false;
        for (var key in fileList) {
            if (fileList.hasOwnProperty(key)) {
                var file = fileList[key];
                var path = utils.files.relativePath(file);
                if (path) {
                    path = path.split('/');
                    path = path.reverse();
                    if (
                        path[0].includes('.nii') &&
                        (
                            path[1] == 'anat' ||
                            path[1] == 'func' ||
                            path[1] == 'dwi'
                        ) &&
                        (
                            (path[2] && path[2].indexOf('ses-') == 0) ||
                            (path[2] && path[2].indexOf('sub-') == 0)
                        )
                    ) {
                        couldBeBIDS = true;
                        break;
                    }
                }
            }
        }
        callback(couldBeBIDS);
    },

    /**
     * Full Test
     *
     * Takes on an array of files and starts
     * the validation process for a BIDS
     * package.
     */
    fullTest: function (fileList, callback) {
        var self = this;

        var jsonContentsDict = {},
            bContentsDict = {},
            events = [],
            niftis = [],
            headers = [],
            participants = null,
            phenotypeParticipants = [],
            hasSubjectDir = false;

        var summary = {
            sessions: [],
            subjects: [],
            tasks: [],
            modalities: [],
            totalFiles: Object.keys(fileList).length,
            size: 0
        };

        // check for illegal character in task name and acq name

        var task_re = /sub-(.*?)_task-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*(?:_acq-[a-zA-Z0-9-]*)?(?:_run-\d+)?_/g;
        var acq_re = /sub-(.*?)_task-\w+.\w+(_acq-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*)(?:_run-\d+)?_/g;

        var illegalchar_regex_list = [
            [task_re, 58, "task name contains illegal character:"],
            [acq_re, 59, "acq name contains illegal character:"]
        ];

        for (var f in fileList) {
            var completename = fileList[f].relativePath;

            for (var re_index = 0; re_index < illegalchar_regex_list.length; re_index++) {
                var err_regex = illegalchar_regex_list[re_index][0];
                var err_code = illegalchar_regex_list[re_index][1];
                var err_evidence = illegalchar_regex_list[re_index][2];

                if (err_regex.exec(completename)) {
                    self.issues.push(new Issue({
                        file: fileList[f],
                        code: err_code,
                        evidence: err_evidence + fileList[f].relativePath
                    }));
                }
            }
        }

        // validate individual files
        async.eachOfLimit(fileList, 200, function (file, key, cb) {
            var path = utils.files.relativePath(file);
            file.relativePath = path;

            // check for subject directory presence
            if (path.startsWith('/sub-')) {
                hasSubjectDir = true;
            }

            // ignore associated data
            if (utils.type.isAssociatedData(file.relativePath)) {
                process.nextTick(cb);
            }

            // validate path naming
            else if (!utils.type.isBIDS(file.relativePath)) {
                self.issues.push(new Issue({
                    file: file,
                    evidence: file.name,
                    code: 1
                }));
                process.nextTick(cb);
            }

            // capture niftis for later validation
            else if (file.name.endsWith('.nii') || file.name.endsWith('.nii.gz')) {
                niftis.push(file);

                // collect modality summary
                var pathParts = path.split('_');
                var suffix = pathParts[pathParts.length - 1];
                suffix = suffix.slice(0, suffix.indexOf('.'));
                if (summary.modalities.indexOf(suffix) === -1) {
                    summary.modalities.push(suffix);
                }

                process.nextTick(cb);
            }

            // validate tsv
            else if (file.name && file.name.endsWith('.tsv')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    if (file.name.endsWith('_events.tsv')) {
                        events.push(file.relativePath);
                    }
                    TSV(file, contents, fileList, function (issues, participantList) {
                        if (participantList) {
                            if (file.name.endsWith('participants.tsv')) {
                                participants = {
                                    list: participantList,
                                    file: file
                                };
                            } else if (file.relativePath.includes('phenotype/')) {
                                phenotypeParticipants.push({
                                    list: participantList,
                                    file: file
                                });
                            }
                        }
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate bvec
            else if (file.name && file.name.endsWith('.bvec')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    bContentsDict[file.relativePath] = contents;
                    bvec(file, contents, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate bval
            else if (file.name && file.name.endsWith('.bval')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    bContentsDict[file.relativePath] = contents;
                    bval(file, contents, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate json
            else if (file.name && file.name.endsWith('.json')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    json(file, contents, function (issues, jsObj) {
                        self.issues = self.issues.concat(issues);
                        jsonContentsDict[file.relativePath] = jsObj;

                        // collect task summary
                        if (file.name.indexOf('task') > -1) {
                            var task = jsObj ? jsObj.TaskName : null;
                            if (task && summary.tasks.indexOf(task) === -1) {
                                summary.tasks.push(task);
                            }
                        }
                        process.nextTick(cb);
                    });
                });
            } else {
                process.nextTick(cb);
            }

            // collect file stats
            if (typeof window !== 'undefined') {
                if (file.size) {
                    summary.size += file.size;
                }
            } else {
                if (!file.stats) {
                    try {
                        file.stats = fs.statSync(file.path);
                    } catch (err) {
                        file.stats = {size: 0};
                    }
                }
                summary.size += file.stats.size;
            }

            // collect sessions & subjects
            if (!utils.type.isAssociatedData(file.relativePath) && utils.type.isBIDS(file.relativePath)) {
                var pathValues = utils.type.getPathValues(file.relativePath);

                if (pathValues.sub && summary.subjects.indexOf(pathValues.sub) === -1) {
                    summary.subjects.push(pathValues.sub);
                }
                if (pathValues.ses && summary.sessions.indexOf(pathValues.ses) === -1) {
                    summary.sessions.push(pathValues.ses);
                }
            }

        }, function () {
            async.eachOfLimit(niftis, 200, function (file, key, cb) {
                if (self.options.ignoreNiftiHeaders) {
                    NIFTI(null, file, jsonContentsDict, bContentsDict, fileList, events, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                } else {
                    utils.files.readNiftiHeader(file, function (header) {
                        // check if header could be read
                        if (header && header.hasOwnProperty('error')) {
                            self.issues.push(header.error);
                            process.nextTick(cb);
                        } else {
                            headers.push([file, header]);
                            NIFTI(header, file, jsonContentsDict, bContentsDict, fileList, events, function (issues) {
                                self.issues = self.issues.concat(issues);
                                process.nextTick(cb);
                            });
                        }
                    });
                }

            }, function () {
                if (!hasSubjectDir) {
                    self.issues.push(new Issue({code: 45}));
                }
                // check if participants file match found subjects

                if (participants) {
                    var participantsFromFile = participants.list.sort();
                    var participantsFromFolders = summary.subjects.sort();
                    if (!utils.array.equals(participantsFromFolders, participantsFromFile, true)) {
                        self.issues.push(new Issue({
                            code: 49,
                            evidence: "participants.tsv: " + participantsFromFile.join(', ') + " folder structure: " + participantsFromFolders.join(', '),
                            file: participants.file
                        }));
                    }
                }

                // check if dataset contains T1w
                if (summary.modalities.indexOf('T1w') < 0) {
                    self.issues.push(new Issue({
                        code: 53
                    }));
                }

                if (phenotypeParticipants && phenotypeParticipants.length > 0) {
                    for (var j = 0; j < phenotypeParticipants.length; j++) {
                        var fileParticpants = phenotypeParticipants[j];
                        var diff = utils.array.diff(fileParticpants.list, summary.subjects)[0];
                        if (diff && diff.length > 0) {
                            self.issues.push(new Issue({
                                code: 51,
                                evidence: 'sub-' + diff.join(', sub-'),
                                file: fileParticpants.file
                            }));
                        }
                    }
                }
                self.issues = self.issues.concat(headerFields(headers));
                self.issues = self.issues.concat(session(fileList));
                summary.modalities = utils.modalities.group(summary.modalities);
                var issues = utils.issues.format(self.issues, summary, self.options);
                callback(issues, summary);
            });
        });
    },

    /**
     * Reset
     *
     * Resets the in object data back to original values.
     */
    reset: function () {
        this.issues = [];
    }

};

module.exports = BIDS;
<commit_msg>Extend error 61 quick validation failure with required metadata.<commit_after>var async  = require('async');
var fs     = require('fs');
var utils  = require('../utils');
var Issue  = utils.issues.Issue;

var TSV    = require('./tsv');
var json   = require('./json');
var NIFTI  = require('./nii');
var bval   = require('./bval');
var bvec   = require('./bvec');
var session = require('./session');
var headerFields = require('./headerFields');

var BIDS;
BIDS = {

    options: {},
    issues: [],

    /**
     * Start
     *
     * Takes either a filelist array or
     * a path to a BIDS directory and an
     * options object and starts
     * the validation process and
     * returns the errors and warnings as
     * arguments to the callback.
     */
    start: function (dir, options, callback) {
        var self = BIDS;
        utils.options.parse(options, function (issues, options) {
            if (issues && issues.length > 0) {
                // option parsing issues
                callback({config: issues});
            } else {
                self.options = options;
                BIDS.reset();
                utils.files.readDir(dir, function (files) {
                    self.quickTest(files, function (couldBeBIDS) {
                        if (couldBeBIDS) {
                            self.fullTest(files, callback);
                        } else {
                            // Return an error immediately if quickTest fails
                            var issue = new Issue({
                                code: 61,
                                file: 'N/A'
                            });
                            callback({errors: [issue], warnings: []});
                        }
                    });
                });
            }
        });
    },

    /**
     * Quick Test
     *
     * A quick test to see if it could be a BIDS
     * dataset based on structure/naming. If it
     * could be it will trigger the full validation
     * otherwise it will throw a callback with a
     * generic error.
     */
    quickTest: function (fileList, callback) {
        var couldBeBIDS = false;
        for (var key in fileList) {
            if (fileList.hasOwnProperty(key)) {
                var file = fileList[key];
                var path = utils.files.relativePath(file);
                if (path) {
                    path = path.split('/');
                    path = path.reverse();
                    if (
                        path[0].includes('.nii') &&
                        (
                            path[1] == 'anat' ||
                            path[1] == 'func' ||
                            path[1] == 'dwi'
                        ) &&
                        (
                            (path[2] && path[2].indexOf('ses-') == 0) ||
                            (path[2] && path[2].indexOf('sub-') == 0)
                        )
                    ) {
                        couldBeBIDS = true;
                        break;
                    }
                }
            }
        }
        callback(couldBeBIDS);
    },

    /**
     * Full Test
     *
     * Takes on an array of files and starts
     * the validation process for a BIDS
     * package.
     */
    fullTest: function (fileList, callback) {
        var self = this;

        var jsonContentsDict = {},
            bContentsDict = {},
            events = [],
            niftis = [],
            headers = [],
            participants = null,
            phenotypeParticipants = [],
            hasSubjectDir = false;

        var summary = {
            sessions: [],
            subjects: [],
            tasks: [],
            modalities: [],
            totalFiles: Object.keys(fileList).length,
            size: 0
        };

        // check for illegal character in task name and acq name

        var task_re = /sub-(.*?)_task-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*(?:_acq-[a-zA-Z0-9-]*)?(?:_run-\d+)?_/g;
        var acq_re = /sub-(.*?)_task-\w+.\w+(_acq-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*)(?:_run-\d+)?_/g;

        var illegalchar_regex_list = [
            [task_re, 58, "task name contains illegal character:"],
            [acq_re, 59, "acq name contains illegal character:"]
        ];

        for (var f in fileList) {
            var completename = fileList[f].relativePath;

            for (var re_index = 0; re_index < illegalchar_regex_list.length; re_index++) {
                var err_regex = illegalchar_regex_list[re_index][0];
                var err_code = illegalchar_regex_list[re_index][1];
                var err_evidence = illegalchar_regex_list[re_index][2];

                if (err_regex.exec(completename)) {
                    self.issues.push(new Issue({
                        file: fileList[f],
                        code: err_code,
                        evidence: err_evidence + fileList[f].relativePath
                    }));
                }
            }
        }

        // validate individual files
        async.eachOfLimit(fileList, 200, function (file, key, cb) {
            var path = utils.files.relativePath(file);
            file.relativePath = path;

            // check for subject directory presence
            if (path.startsWith('/sub-')) {
                hasSubjectDir = true;
            }

            // ignore associated data
            if (utils.type.isAssociatedData(file.relativePath)) {
                process.nextTick(cb);
            }

            // validate path naming
            else if (!utils.type.isBIDS(file.relativePath)) {
                self.issues.push(new Issue({
                    file: file,
                    evidence: file.name,
                    code: 1
                }));
                process.nextTick(cb);
            }

            // capture niftis for later validation
            else if (file.name.endsWith('.nii') || file.name.endsWith('.nii.gz')) {
                niftis.push(file);

                // collect modality summary
                var pathParts = path.split('_');
                var suffix = pathParts[pathParts.length - 1];
                suffix = suffix.slice(0, suffix.indexOf('.'));
                if (summary.modalities.indexOf(suffix) === -1) {
                    summary.modalities.push(suffix);
                }

                process.nextTick(cb);
            }

            // validate tsv
            else if (file.name && file.name.endsWith('.tsv')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    if (file.name.endsWith('_events.tsv')) {
                        events.push(file.relativePath);
                    }
                    TSV(file, contents, fileList, function (issues, participantList) {
                        if (participantList) {
                            if (file.name.endsWith('participants.tsv')) {
                                participants = {
                                    list: participantList,
                                    file: file
                                };
                            } else if (file.relativePath.includes('phenotype/')) {
                                phenotypeParticipants.push({
                                    list: participantList,
                                    file: file
                                });
                            }
                        }
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate bvec
            else if (file.name && file.name.endsWith('.bvec')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    bContentsDict[file.relativePath] = contents;
                    bvec(file, contents, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate bval
            else if (file.name && file.name.endsWith('.bval')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    bContentsDict[file.relativePath] = contents;
                    bval(file, contents, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate json
            else if (file.name && file.name.endsWith('.json')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    json(file, contents, function (issues, jsObj) {
                        self.issues = self.issues.concat(issues);
                        jsonContentsDict[file.relativePath] = jsObj;

                        // collect task summary
                        if (file.name.indexOf('task') > -1) {
                            var task = jsObj ? jsObj.TaskName : null;
                            if (task && summary.tasks.indexOf(task) === -1) {
                                summary.tasks.push(task);
                            }
                        }
                        process.nextTick(cb);
                    });
                });
            } else {
                process.nextTick(cb);
            }

            // collect file stats
            if (typeof window !== 'undefined') {
                if (file.size) {
                    summary.size += file.size;
                }
            } else {
                if (!file.stats) {
                    try {
                        file.stats = fs.statSync(file.path);
                    } catch (err) {
                        file.stats = {size: 0};
                    }
                }
                summary.size += file.stats.size;
            }

            // collect sessions & subjects
            if (!utils.type.isAssociatedData(file.relativePath) && utils.type.isBIDS(file.relativePath)) {
                var pathValues = utils.type.getPathValues(file.relativePath);

                if (pathValues.sub && summary.subjects.indexOf(pathValues.sub) === -1) {
                    summary.subjects.push(pathValues.sub);
                }
                if (pathValues.ses && summary.sessions.indexOf(pathValues.ses) === -1) {
                    summary.sessions.push(pathValues.ses);
                }
            }

        }, function () {
            async.eachOfLimit(niftis, 200, function (file, key, cb) {
                if (self.options.ignoreNiftiHeaders) {
                    NIFTI(null, file, jsonContentsDict, bContentsDict, fileList, events, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                } else {
                    utils.files.readNiftiHeader(file, function (header) {
                        // check if header could be read
                        if (header && header.hasOwnProperty('error')) {
                            self.issues.push(header.error);
                            process.nextTick(cb);
                        } else {
                            headers.push([file, header]);
                            NIFTI(header, file, jsonContentsDict, bContentsDict, fileList, events, function (issues) {
                                self.issues = self.issues.concat(issues);
                                process.nextTick(cb);
                            });
                        }
                    });
                }

            }, function () {
                if (!hasSubjectDir) {
                    self.issues.push(new Issue({code: 45}));
                }
                // check if participants file match found subjects

                if (participants) {
                    var participantsFromFile = participants.list.sort();
                    var participantsFromFolders = summary.subjects.sort();
                    if (!utils.array.equals(participantsFromFolders, participantsFromFile, true)) {
                        self.issues.push(new Issue({
                            code: 49,
                            evidence: "participants.tsv: " + participantsFromFile.join(', ') + " folder structure: " + participantsFromFolders.join(', '),
                            file: participants.file
                        }));
                    }
                }

                // check if dataset contains T1w
                if (summary.modalities.indexOf('T1w') < 0) {
                    self.issues.push(new Issue({
                        code: 53
                    }));
                }

                if (phenotypeParticipants && phenotypeParticipants.length > 0) {
                    for (var j = 0; j < phenotypeParticipants.length; j++) {
                        var fileParticpants = phenotypeParticipants[j];
                        var diff = utils.array.diff(fileParticpants.list, summary.subjects)[0];
                        if (diff && diff.length > 0) {
                            self.issues.push(new Issue({
                                code: 51,
                                evidence: 'sub-' + diff.join(', sub-'),
                                file: fileParticpants.file
                            }));
                        }
                    }
                }
                self.issues = self.issues.concat(headerFields(headers));
                self.issues = self.issues.concat(session(fileList));
                summary.modalities = utils.modalities.group(summary.modalities);
                var issues = utils.issues.format(self.issues, summary, self.options);
                callback(issues, summary);
            });
        });
    },

    /**
     * Reset
     *
     * Resets the in object data back to original values.
     */
    reset: function () {
        this.issues = [];
    }

};

module.exports = BIDS;
<|endoftext|>


<commit_before>var printf = require("printf");
var RandomMessage = require(__dirname + "/../api/randommessages.js");

var Impanatrice = function() {
  this.messages = new RandomMessage();
  this.messages.push("Impanatrice @%s buongiorno!!");
  this.messages.push("Nostra impanatrice @%s buongiorno!!");
  this.messages.push("@%s buongiorno!!");
  this.messages.push("@%s maestà!!");
}

Impanatrice.prototype.onMessage = function(bot, chat_id, from, message)
{
	var IMPANATRICE = new RegExp(/paraflu/i); //new RegExp(/MikaMohawk/i);
	var buongiorno = new RegExp(/buon\s*giorno/i);
	console.log(from);
	if (from !== undefined && IMPANATRICE.test(from.username)) {
	  bot.sendMessage(chat_id, printf(this.messages.getMessage(), from.username));
	}
}

module.exports = new Impanatrice();
<commit_msg>correttto matching del nick<commit_after>var printf = require("printf");
var RandomMessage = require(__dirname + "/../api/randommessages.js");

var Impanatrice = function() {
  this.messages = new RandomMessage();
  this.messages.push("Impanatrice @%s buongiorno!!");
  this.messages.push("Nostra impanatrice @%s buongiorno!!");
  this.messages.push("@%s buongiorno!!");
  this.messages.push("@%s maestà!!");
}

Impanatrice.prototype.onMessage = function(bot, chat_id, from, message)
{
	var IMPANATRICE = new RegExp(/MikaMohawk/i);
	var buongiorno = new RegExp(/buon\s*giorno/i);
	console.log(from);
	if (from !== undefined && IMPANATRICE.test(from.username)) {
	  bot.sendMessage(chat_id, printf(this.messages.getMessage(), from.username));
	}
}

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


<commit_before>var filepickerUpload = require('../../services/filepickerUpload');

var controller = function($scope, $analytics, currentUser, growl, onboarding) {
  var user = $scope.user = currentUser,
    editData = $scope.editData = _.pick(user, [
      'bio', 'work', 'intention', 'extra_info', 'avatar_url', 'banner_url',
      'skills', 'organizations', 'phones', 'emails', 'websites',
      'twitter_name', 'linkedin_url', 'facebook_url'
    ]),
    edited = {},
    bio = editData.bio;

  $scope.save = function() {
    if (editData.banner_url === require('../../services/defaultUserBanner')) {
      editData.banner_url = null;
    }

    var saveData = _.clone(editData);

    if (saveData.bio != bio) $analytics.eventTrack('My Profile: Updated Bio');

    if (!edited.skills) delete saveData.skills;
    else $analytics.eventTrack('My Profile: Updated Skills');

    if (!edited.organizations) delete saveData.organizations;
    else $analytics.eventTrack('My Profile: Updated Affiliations');

    user.update(saveData, function() {
      _.extend(user, saveData);
      $analytics.eventTrack('My Profile: Saved Changes');

      if (onboarding && onboarding.currentStep() === 'profile') {
        onboarding.goNext();
      } else {
        $scope.cancel();
      }

    });
  };

  $scope.cancel = function() {
    $scope.$state.go('profile', {id: user.id});
  };

  $scope.add = function(event, type) {
    if (event.which == 13) {
      editData[type].unshift(event.target.value);
      event.target.value = '';
      edited[type] = true;
      $analytics.eventTrack('My Profile: Edit: Add to Profile', {item_type: type});
    }
    return true;
  };

  $scope.remove = function(value, type) {
    editData[type].splice(editData[type].indexOf(value), 1);
    edited[type] = true;
  };

  var imageChangeFn = function(opts) {
    return function() {
      filepickerUpload({
        path: opts.path,
        convert: opts.convert,
        success: function(url) {
          editData[opts.fieldName] = url;
          $analytics.eventTrack('Profile: Changed ' + opts.humanName, {user_id: user.id});
        },
        failure: function(error) {
          if (error.code != 101) {
            growl.addErrorMessage('An error occurred while uploading the image. Please try again.');
            $analytics.eventTrack('Profile: Failed to Change ' + opts.humanName, {user_id: user.id});
          }
        }
      });
    };
  };

  $scope.changeAvatar = imageChangeFn({
    fieldName: 'avatar_url',
    humanName: 'Icon',
    path: 'thumb',
    convert: {width: 200, height: 200, fit: 'clip', rotate: "exif"}
  });

  $scope.changeBanner = imageChangeFn({
    fieldName: 'banner_url',
    humanName: 'Banner',
    path: 'userBanner',
    convert: {width: 1600, format: 'jpg', fit: 'max', rotate: "exif"}
  });

  $scope.changeTwitter = function() {
    var response = prompt(
      'Enter your Twitter username, or leave blank:',
      editData.twitter_name
    );

    editData.twitter_name = response;

    if (response) {
      $analytics.eventTrack('My Profile: Edit: Add Social Media Link to Profile', {provider: 'Twitter'});
    }
  };

  $scope.changeFacebook = function() {
    if (editData.facebook_url) {
      if (confirm('Choose OK to remove your Facebook information.')) {
        editData.facebook_url = null;
        $analytics.eventTrack('My Profile: Edit: Remove Social Media Link from Profile', {provider: 'Facebook'});
      }
    } else {
      FB.login(function() {
        FB.api('/me', function(resp) {
          editData.facebook_url = resp.link;
          $analytics.eventTrack('My Profile: Edit: Add Social Media Link to Profile', {provider: 'Facebook'});
        })
      })
    }
  };

  $scope.changeLinkedin = function() {
    if (editData.linkedin_url) {
      if (confirm('Choose OK to remove your LinkedIn information.')) {
        editData.linkedin_url = null;
        $analytics.eventTrack('My Profile: Edit: Remove Social Media Link from Profile', {provider: 'LinkedIn'});

      }
    } else {
      var left = document.documentElement.clientWidth/2 - 520/2;
      $scope.linkedinDialog = window.open('/noo/linkedin/authorize', 'linkedinAuth',
        'width=400, height=625, titlebar=no, toolbar=no, menubar=no, left=' + left);
    }
  };

  $scope.finishLinkedinChange = function(url) {
    editData.linkedin_url = url;
    $scope.linkedinDialog.close();
    $analytics.eventTrack('My Profile: Edit: Add Social Media Link to Profile', {provider: 'LinkedIn'});
  };
};

module.exports = function(angularModule) {
  angularModule.controller('ProfileEditCtrl', controller);
};
<commit_msg>fix a bug with facebook integration<commit_after>var filepickerUpload = require('../../services/filepickerUpload');

var controller = function($scope, $analytics, currentUser, growl, onboarding) {
  var user = $scope.user = currentUser,
    editData = $scope.editData = _.pick(user, [
      'bio', 'work', 'intention', 'extra_info', 'avatar_url', 'banner_url',
      'skills', 'organizations', 'phones', 'emails', 'websites',
      'twitter_name', 'linkedin_url', 'facebook_url'
    ]),
    edited = {},
    bio = editData.bio;

  $scope.save = function() {
    if (editData.banner_url === require('../../services/defaultUserBanner')) {
      editData.banner_url = null;
    }

    var saveData = _.clone(editData);

    if (saveData.bio != bio) $analytics.eventTrack('My Profile: Updated Bio');

    if (!edited.skills) delete saveData.skills;
    else $analytics.eventTrack('My Profile: Updated Skills');

    if (!edited.organizations) delete saveData.organizations;
    else $analytics.eventTrack('My Profile: Updated Affiliations');

    user.update(saveData, function() {
      _.extend(user, saveData);
      $analytics.eventTrack('My Profile: Saved Changes');

      if (onboarding && onboarding.currentStep() === 'profile') {
        onboarding.goNext();
      } else {
        $scope.cancel();
      }

    });
  };

  $scope.cancel = function() {
    $scope.$state.go('profile', {id: user.id});
  };

  $scope.add = function(event, type) {
    if (event.which == 13) {
      editData[type].unshift(event.target.value);
      event.target.value = '';
      edited[type] = true;
      $analytics.eventTrack('My Profile: Edit: Add to Profile', {item_type: type});
    }
    return true;
  };

  $scope.remove = function(value, type) {
    editData[type].splice(editData[type].indexOf(value), 1);
    edited[type] = true;
  };

  var imageChangeFn = function(opts) {
    return function() {
      filepickerUpload({
        path: opts.path,
        convert: opts.convert,
        success: function(url) {
          editData[opts.fieldName] = url;
          $analytics.eventTrack('Profile: Changed ' + opts.humanName, {user_id: user.id});
        },
        failure: function(error) {
          if (error.code != 101) {
            growl.addErrorMessage('An error occurred while uploading the image. Please try again.');
            $analytics.eventTrack('Profile: Failed to Change ' + opts.humanName, {user_id: user.id});
          }
        }
      });
    };
  };

  $scope.changeAvatar = imageChangeFn({
    fieldName: 'avatar_url',
    humanName: 'Icon',
    path: 'thumb',
    convert: {width: 200, height: 200, fit: 'clip', rotate: "exif"}
  });

  $scope.changeBanner = imageChangeFn({
    fieldName: 'banner_url',
    humanName: 'Banner',
    path: 'userBanner',
    convert: {width: 1600, format: 'jpg', fit: 'max', rotate: "exif"}
  });

  $scope.changeTwitter = function() {
    var response = prompt(
      'Enter your Twitter username, or leave blank:',
      editData.twitter_name
    );

    editData.twitter_name = response;

    if (response) {
      $analytics.eventTrack('My Profile: Edit: Add Social Media Link to Profile', {provider: 'Twitter'});
    }
  };

  $scope.changeFacebook = function() {
    if (editData.facebook_url) {
      if (confirm('Choose OK to remove your Facebook information.')) {
        editData.facebook_url = null;
        $analytics.eventTrack('My Profile: Edit: Remove Social Media Link from Profile', {provider: 'Facebook'});
      }
    } else {
      FB.login(function() {
        FB.api('/me', function(resp) {
          $scope.$apply(function() {
            editData.facebook_url = resp.link;
            $analytics.eventTrack('My Profile: Edit: Add Social Media Link to Profile', {provider: 'Facebook'});
          });
        })
      })
    }
  };

  $scope.changeLinkedin = function() {
    if (editData.linkedin_url) {
      if (confirm('Choose OK to remove your LinkedIn information.')) {
        editData.linkedin_url = null;
        $analytics.eventTrack('My Profile: Edit: Remove Social Media Link from Profile', {provider: 'LinkedIn'});

      }
    } else {
      var left = document.documentElement.clientWidth/2 - 520/2;
      $scope.linkedinDialog = window.open('/noo/linkedin/authorize', 'linkedinAuth',
        'width=400, height=625, titlebar=no, toolbar=no, menubar=no, left=' + left);
    }
  };

  $scope.finishLinkedinChange = function(url) {
    editData.linkedin_url = url;
    $scope.linkedinDialog.close();
    $analytics.eventTrack('My Profile: Edit: Add Social Media Link to Profile', {provider: 'LinkedIn'});
  };
};

module.exports = function(angularModule) {
  angularModule.controller('ProfileEditCtrl', controller);
};
<|endoftext|>