<commit_before>'use strict';

var NR = require('node-resque');

module.exports = {
  startPriority: 200,
  stopPriority:  100,
  loadPriority:  600,
  initialize: function(api, next){

    var resqueOverrides = api.config.tasks.resque_overrides;

    api.resque = {
      verbose: false,
      queue: null,
      multiWorker: null,
      scheduler: null,
      connectionDetails: {redis: api.redis.clients.tasks},

      startQueue: function(callback){
        var self = this;
        var queue = NR.queue;
        if(resqueOverrides && resqueOverrides.queue){ queue = resqueOverrides.queue; }
        self.queue = new queue({connection: self.connectionDetails}, api.tasks.jobs);
        self.queue.on('error', function(error){
          api.log(error, 'error', '[api.resque.queue]');
        });
        self.queue.connect(callback);
      },

      stopQueue: function(callback){
        if(api.resque.queue){ api.resque.queue.end(callback); }
        else{ callback(); }
      },

      startScheduler: function(callback){
        var self = this;
        var scheduler = NR.scheduler;
        if(resqueOverrides && resqueOverrides.scheduler){ scheduler = resqueOverrides.scheduler; }
        if(api.config.tasks.scheduler === true){
          self.schedulerLogging = api.config.tasks.schedulerLogging;
          self.scheduler = new scheduler({connection: self.connectionDetails, timeout: api.config.tasks.timeout});
          self.scheduler.on('error', function(error){
            api.log(error, 'error', '[api.resque.scheduler]');
          });
          self.scheduler.connect(function(){
            self.scheduler.on('start',             function(){               api.log('resque scheduler started', self.schedulerLogging.start); });
            self.scheduler.on('end',               function(){               api.log('resque scheduler ended', self.schedulerLogging.end); });
            self.scheduler.on('poll',              function(){               api.log('resque scheduler polling', self.schedulerLogging.poll); });
            self.scheduler.on('working_timestamp', function(timestamp){      api.log(['resque scheduler working timestamp %s', timestamp], self.schedulerLogging.working_timestamp); });
            self.scheduler.on('transferred_job',   function(timestamp, job){ api.log(['resque scheduler enqueuing job %s', timestamp], self.schedulerLogging.transferred_job, job); });

            self.scheduler.start();
            callback();
          });
        }else{
          callback();
        }
      },

      stopScheduler: function(callback){
        var self = this;
        if(!self.scheduler){
          callback();
        }else{
          self.scheduler.end(function(){
            delete self.scheduler;
            callback();
          });
        }
      },

      startMultiWorker: function(callback){
        var self = this;
        var multiWorker = NR.multiWorker;
        if(resqueOverrides && resqueOverrides.multiWorker){ multiWorker = resqueOverrides.multiWorker; }
        self.workerLogging = api.config.tasks.workerLogging;
        self.schedulerLogging = api.config.tasks.schedulerLogging;

        self.multiWorker = new multiWorker({
          connection:             api.resque.connectionDetails,
          queues:                 api.config.tasks.queues,
          timeout:                api.config.tasks.timeout,
          checkTimeout:           api.config.tasks.checkTimeout,
          minTaskProcessors:      api.config.tasks.minTaskProcessors,
          maxTaskProcessors:      api.config.tasks.maxTaskProcessors,
          maxEventLoopDelay:      api.config.tasks.maxEventLoopDelay,
          toDisconnectProcessors: api.config.tasks.toDisconnectProcessors,
        }, api.tasks.jobs);

        // normal worker emitters
        self.multiWorker.on('start',             function(workerId){                      api.log('worker: started',                 self.workerLogging.start,         {workerId: workerId}); });
        self.multiWorker.on('end',               function(workerId){                      api.log('worker: ended',                   self.workerLogging.end,           {workerId: workerId}); });
        self.multiWorker.on('cleaning_worker',   function(workerId, worker, pid){         api.log(['worker: cleaning old worker %s, (%s)', worker, pid],  self.workerLogging.cleaning_worker); });
        self.multiWorker.on('poll',              function(workerId, queue){               api.log(['worker: polling %s', queue],     self.workerLogging.poll,          {workerId: workerId}); });
        self.multiWorker.on('job',               function(workerId, queue, job){          api.log(['worker: working job %s', queue], self.workerLogging.job,           {workerId: workerId, job: {class: job['class'], queue: job.queue}}); });
        self.multiWorker.on('reEnqueue',         function(workerId, queue, job, plugin){  api.log('worker: reEnqueue job',           self.workerLogging.reEnqueue,     {workerId: workerId, plugin: plugin, job: {class: job['class'], queue: job.queue}}); });
        self.multiWorker.on('success',           function(workerId, queue, job, result){  api.log(['worker: job success %s', queue], self.workerLogging.success,       {workerId: workerId, job: {class: job['class'], queue: job.queue}, result: result}); });
        self.multiWorker.on('pause',             function(workerId){                      api.log('worker: paused',                  self.workerLogging.pause,         {workerId: workerId}); });

        self.multiWorker.on('failure',           function(workerId, queue, job, failure){ api.exceptionHandlers.task(failure, queue, job, workerId); });
        self.multiWorker.on('error',             function(workerId, queue, job, error){   api.exceptionHandlers.task(error, queue, job, workerId);   });

        // multiWorker emitters
        self.multiWorker.on('internalError',     function(error){                         api.log(error, self.workerLogging.internalError); });
        self.multiWorker.on('multiWorkerAction', function(verb, delay){                   api.log(['*** checked for worker status: %s (event loop delay: %sms)', verb, delay], self.workerLogging.multiWorkerAction); });

        if(api.config.tasks.minTaskProcessors > 0){
          self.multiWorker.start(function(){
            if(typeof callback === 'function'){ callback(); }
          });
        }else{
          if(typeof callback === 'function'){ callback(); }
        }
      },

      stopMultiWorker: function(callback){
        var self = this;
        if(self.multiWorker && api.config.tasks.minTaskProcessors > 0){
          self.multiWorker.stop(function(){
            api.log('task workers stopped');
            callback();
          });
        }else{
          callback();
        }
      }
    };

    next();
  },

  start: function(api, next){
    if(api.config.tasks.minTaskProcessors === 0 && api.config.tasks.maxTaskProcessors > 0){
      api.config.tasks.minTaskProcessors = 1;
    }

    api.resque.startQueue(function(){
      api.resque.startScheduler(function(){
        api.resque.startMultiWorker(function(){
          next();
        });
      });
    });
  },

  stop: function(api, next){
    api.resque.stopScheduler(function(){
      api.resque.stopMultiWorker(function(){
        api.resque.stopQueue(function(){
          next();
        });
      });
    });
  },
};
<commit_msg>log when node becomes resque scheudler master<commit_after>'use strict';

var NR = require('node-resque');

module.exports = {
  startPriority: 200,
  stopPriority:  100,
  loadPriority:  600,
  initialize: function(api, next){

    var resqueOverrides = api.config.tasks.resque_overrides;

    api.resque = {
      verbose: false,
      queue: null,
      multiWorker: null,
      scheduler: null,
      connectionDetails: {redis: api.redis.clients.tasks},

      startQueue: function(callback){
        var self = this;
        var queue = NR.queue;
        if(resqueOverrides && resqueOverrides.queue){ queue = resqueOverrides.queue; }
        self.queue = new queue({connection: self.connectionDetails}, api.tasks.jobs);
        self.queue.on('error', function(error){
          api.log(error, 'error', '[api.resque.queue]');
        });
        self.queue.connect(callback);
      },

      stopQueue: function(callback){
        if(api.resque.queue){ api.resque.queue.end(callback); }
        else{ callback(); }
      },

      startScheduler: function(callback){
        var self = this;
        var scheduler = NR.scheduler;
        if(resqueOverrides && resqueOverrides.scheduler){ scheduler = resqueOverrides.scheduler; }
        if(api.config.tasks.scheduler === true){
          self.schedulerLogging = api.config.tasks.schedulerLogging;
          self.scheduler = new scheduler({connection: self.connectionDetails, timeout: api.config.tasks.timeout});
          self.scheduler.on('error', function(error){
            api.log(error, 'error', '[api.resque.scheduler]');
          });
          self.scheduler.connect(function(){
            self.scheduler.on('start',             function(){               api.log('resque scheduler started', self.schedulerLogging.start); });
            self.scheduler.on('end',               function(){               api.log('resque scheduler ended', self.schedulerLogging.end); });
            self.scheduler.on('poll',              function(){               api.log('resque scheduler polling', self.schedulerLogging.poll); });
            self.scheduler.on('working_timestamp', function(timestamp){      api.log(['resque scheduler working timestamp %s', timestamp], self.schedulerLogging.working_timestamp); });
            self.scheduler.on('transferred_job',   function(timestamp, job){ api.log(['resque scheduler enqueuing job %s', timestamp], self.schedulerLogging.transferred_job, job); });
            self.scheduler.on('master',            function(state){          api.log(['This node is now the Resque scheduler master']); });

            self.scheduler.start();
            callback();
          });
        }else{
          callback();
        }
      },

      stopScheduler: function(callback){
        var self = this;
        if(!self.scheduler){
          callback();
        }else{
          self.scheduler.end(function(){
            delete self.scheduler;
            callback();
          });
        }
      },

      startMultiWorker: function(callback){
        var self = this;
        var multiWorker = NR.multiWorker;
        if(resqueOverrides && resqueOverrides.multiWorker){ multiWorker = resqueOverrides.multiWorker; }
        self.workerLogging = api.config.tasks.workerLogging;
        self.schedulerLogging = api.config.tasks.schedulerLogging;

        self.multiWorker = new multiWorker({
          connection:             api.resque.connectionDetails,
          queues:                 api.config.tasks.queues,
          timeout:                api.config.tasks.timeout,
          checkTimeout:           api.config.tasks.checkTimeout,
          minTaskProcessors:      api.config.tasks.minTaskProcessors,
          maxTaskProcessors:      api.config.tasks.maxTaskProcessors,
          maxEventLoopDelay:      api.config.tasks.maxEventLoopDelay,
          toDisconnectProcessors: api.config.tasks.toDisconnectProcessors,
        }, api.tasks.jobs);

        // normal worker emitters
        self.multiWorker.on('start',             function(workerId){                      api.log('worker: started',                 self.workerLogging.start,         {workerId: workerId}); });
        self.multiWorker.on('end',               function(workerId){                      api.log('worker: ended',                   self.workerLogging.end,           {workerId: workerId}); });
        self.multiWorker.on('cleaning_worker',   function(workerId, worker, pid){         api.log(['worker: cleaning old worker %s, (%s)', worker, pid],  self.workerLogging.cleaning_worker); });
        self.multiWorker.on('poll',              function(workerId, queue){               api.log(['worker: polling %s', queue],     self.workerLogging.poll,          {workerId: workerId}); });
        self.multiWorker.on('job',               function(workerId, queue, job){          api.log(['worker: working job %s', queue], self.workerLogging.job,           {workerId: workerId, job: {class: job['class'], queue: job.queue}}); });
        self.multiWorker.on('reEnqueue',         function(workerId, queue, job, plugin){  api.log('worker: reEnqueue job',           self.workerLogging.reEnqueue,     {workerId: workerId, plugin: plugin, job: {class: job['class'], queue: job.queue}}); });
        self.multiWorker.on('success',           function(workerId, queue, job, result){  api.log(['worker: job success %s', queue], self.workerLogging.success,       {workerId: workerId, job: {class: job['class'], queue: job.queue}, result: result}); });
        self.multiWorker.on('pause',             function(workerId){                      api.log('worker: paused',                  self.workerLogging.pause,         {workerId: workerId}); });

        self.multiWorker.on('failure',           function(workerId, queue, job, failure){ api.exceptionHandlers.task(failure, queue, job, workerId); });
        self.multiWorker.on('error',             function(workerId, queue, job, error){   api.exceptionHandlers.task(error, queue, job, workerId);   });

        // multiWorker emitters
        self.multiWorker.on('internalError',     function(error){                         api.log(error, self.workerLogging.internalError); });
        self.multiWorker.on('multiWorkerAction', function(verb, delay){                   api.log(['*** checked for worker status: %s (event loop delay: %sms)', verb, delay], self.workerLogging.multiWorkerAction); });

        if(api.config.tasks.minTaskProcessors > 0){
          self.multiWorker.start(function(){
            if(typeof callback === 'function'){ callback(); }
          });
        }else{
          if(typeof callback === 'function'){ callback(); }
        }
      },

      stopMultiWorker: function(callback){
        var self = this;
        if(self.multiWorker && api.config.tasks.minTaskProcessors > 0){
          self.multiWorker.stop(function(){
            api.log('task workers stopped');
            callback();
          });
        }else{
          callback();
        }
      }
    };

    next();
  },

  start: function(api, next){
    if(api.config.tasks.minTaskProcessors === 0 && api.config.tasks.maxTaskProcessors > 0){
      api.config.tasks.minTaskProcessors = 1;
    }

    api.resque.startQueue(function(){
      api.resque.startScheduler(function(){
        api.resque.startMultiWorker(function(){
          next();
        });
      });
    });
  },

  stop: function(api, next){
    api.resque.stopScheduler(function(){
      api.resque.stopMultiWorker(function(){
        api.resque.stopQueue(function(){
          next();
        });
      });
    });
  },
};
<|endoftext|>


<commit_before>define(function (require) {

    var echarts = require('../echarts');
    var zrUtil = require('zrender/core/util');
    var graphicUtil = require('../util/graphic');
    var labelHelper = require('./helper/labelHelper');
    var createListFromArray = require('./helper/createListFromArray');
    var barGrid = require('../layout/barGrid');

    var ITEM_STYLE_NORMAL_PATH = ['itemStyle', 'normal'];
    var ITEM_STYLE_EMPHASIS_PATH = ['itemStyle', 'emphasis'];
    var LABEL_NORMAL = ['label', 'normal'];
    var LABEL_EMPHASIS = ['label', 'emphasis'];

    /**
     * To reduce total package size of each coordinate systems, the modules `prepareCustom`
     * of each coordinate systems are not required by each coordinate systems directly, but
     * required by the module `custom`.
     *
     * prepareInfoForCustomSeries {Function}: optional
     *     @return {Object} {coordSys: {...}, api: {
     *         coord: function (data, clamp) {}, // return point in global.
     *         size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
     *     }}
     */
    var prepareCustoms = {
        cartesian2d: require('../coord/cartesian/prepareCustom'),
        geo: require('../coord/geo/prepareCustom'),
        singleAxis: require('../coord/single/prepareCustom'),
        polar: require('../coord/polar/prepareCustom'),
        calendar: require('../coord/calendar/prepareCustom')
    };

    // ------
    // Model
    // ------

    echarts.extendSeriesModel({

        type: 'series.custom',

        dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],

        defaultOption: {
            coordinateSystem: 'cartesian2d',
            zlevel: 0,
            z: 2,
            legendHoverLink: true

            // Cartesian coordinate system
            // xAxisIndex: 0,
            // yAxisIndex: 0,

            // Polar coordinate system
            // polarIndex: 0,

            // Geo coordinate system
            // geoIndex: 0,

            // label: {}
            // itemStyle: {}
        },

        getInitialData: function (option, ecModel) {
            return createListFromArray(option.data, this, ecModel);
        }
    });

    // -----
    // View
    // -----

    echarts.extendChartView({

        type: 'custom',

        /**
         * @private
         * @type {module:echarts/data/List}
         */
        _data: null,

        /**
         * @override
         */
        render: function (customSeries, ecModel, api) {
            var oldData = this._data;
            var data = customSeries.getData();
            var group = this.group;
            var renderItem = makeRenderItem(customSeries, data, ecModel, api);

            data.diff(oldData)
                .add(function (newIdx) {
                    data.hasValue(newIdx) && createOrUpdate(
                        null, newIdx, renderItem(newIdx), customSeries, group, data
                    );
                })
                .update(function (newIdx, oldIdx) {
                    var el = oldData.getItemGraphicEl(oldIdx);
                    data.hasValue(newIdx)
                        ? createOrUpdate(
                            el, newIdx, renderItem(newIdx), customSeries, group, data
                        )
                        : (el && group.remove(el));
                })
                .remove(function (oldIdx) {
                    var el = oldData.getItemGraphicEl(oldIdx);
                    el && group.remove(el);
                })
                .execute();

            this._data = data;
        }
    });

    function createEl(elOption) {
        var graphicType = elOption.type;
        var el;

        if (graphicType === 'path') {
            var shape = elOption.shape;
            el = graphicUtil.makePath(
                shape.pathData,
                null,
                {
                    x: shape.x || 0,
                    y: shape.y || 0,
                    width: shape.width || 0,
                    height: shape.height || 0
                },
                'center'
            );
            el.__customPathData = elOption.pathData;
        }
        else if (graphicType === 'image') {
            el = new graphicUtil.Image({
            });
            el.__customImagePath = elOption.style.image;
        }
        else if (graphicType === 'text') {
            el = new graphicUtil.Text({
            });
            el.__customText = elOption.style.text;
        }
        else {
            var Clz = graphicUtil[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];

            if (__DEV__) {
                zrUtil.assert(Clz, 'graphic type "' + graphicType + '" can not be found.');
            }

            el = new Clz();
        }

        el.__customGraphicType = graphicType;

        return el;
    }

    function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
        var targetProps = {};
        var elOptionStyle = elOption.style || {};

        elOption.shape && (targetProps.shape = zrUtil.clone(elOption.shape));
        elOption.position && (targetProps.position = elOption.position.slice());
        elOption.scale && (targetProps.scale = elOption.scale.slice());
        elOption.origin && (targetProps.origin = elOption.origin.slice());
        elOption.rotation && (targetProps.rotation = elOption.rotation);

        if (el.type === 'image' && elOption.style) {
            var targetStyle = targetProps.style = {};
            zrUtil.each(['x', 'y', 'width', 'height'], function (prop) {
                prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
            });
        }

        if (el.type === 'text' && elOption.style) {
            var targetStyle = targetProps.style = {};
            zrUtil.each(['x', 'y'], function (prop) {
                prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
            });
        }

        if (el.type !== 'group') {
            el.useStyle(elOptionStyle);

            // Init animation.
            if (isInit) {
                el.style.opacity = 0;
                var targetOpacity = elOptionStyle.opacity;
                targetOpacity == null && (targetOpacity = 1);
                graphicUtil.initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
            }
        }

        if (isInit) {
            el.attr(targetProps);
        }
        else {
            graphicUtil.updateProps(el, targetProps, animatableModel, dataIndex);
        }

        // z2 must not be null/undefined, otherwise sort error may occur.
        el.attr({z2: elOption.z2 || 0, silent: elOption.silent});

        el.styleEmphasis !== false && graphicUtil.setHoverStyle(el, el.styleEmphasis);
    }

    function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
        if (elOptionStyle[prop] != null && !isInit) {
            targetStyle[prop] = elOptionStyle[prop];
            elOptionStyle[prop] = oldElStyle[prop];
        }
    }

    function makeRenderItem(customSeries, data, ecModel, api) {
        var renderItem = customSeries.get('renderItem');
        var coordSys = customSeries.coordinateSystem;

        if (__DEV__) {
            zrUtil.assert(renderItem, 'series.render is required.');
            zrUtil.assert(
                coordSys.prepareCustoms || prepareCustoms[coordSys.type],
                'This coordSys does not support custom series.'
            );
        }

        var prepareResult = coordSys.prepareCustoms
            ? coordSys.prepareCustoms()
            : prepareCustoms[coordSys.type](coordSys);

        var userAPI = zrUtil.defaults({
            getWidth: api.getWidth,
            getHeight: api.getHeight,
            getZr: api.getZr,
            getDevicePixelRatio: api.getDevicePixelRatio,
            value: value,
            style: style,
            styleEmphasis: styleEmphasis,
            visual: visual,
            barLayout: barLayout,
            currentSeriesIndices: currentSeriesIndices,
            font: font
        }, prepareResult.api);

        var userParams = {
            context: {},
            seriesId: customSeries.id,
            seriesName: customSeries.name,
            seriesIndex: customSeries.seriesIndex,
            coordSys: prepareResult.coordSys,
            dataInsideLength: data.count(),
            encode: wrapEncodeDef(customSeries.getData())
        };

        // Do not support call `api` asynchronously without dataIndexInside input.
        var currDataIndexInside;
        var currDirty = true;
        var currItemModel;
        var currLabelNormalModel;
        var currLabelEmphasisModel;
        var currLabelValueDim;
        var currVisualColor;

        return function (dataIndexInside) {
            currDataIndexInside = dataIndexInside;
            currDirty = true;
            return renderItem && renderItem(
                zrUtil.defaults({
                    dataIndexInside: dataIndexInside,
                    dataIndex: data.getRawIndex(dataIndexInside)
                }, userParams),
                userAPI
            ) || {};
        };

        // Do not update cache until api called.
        function updateCache(dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            if (currDirty) {
                currItemModel = data.getItemModel(dataIndexInside);
                currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
                currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
                currLabelValueDim = labelHelper.findLabelValueDim(data);
                currVisualColor = data.getItemVisual(dataIndexInside, 'color');

                currDirty = false;
            }
        }

        /**
         * @public
         * @param {nubmer|string} dim
         * @param {number} [dataIndexInside=currDataIndexInside]
         * @return {number|string} value
         */
        function value(dim, dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            return data.get(data.getDimension(dim || 0), dataIndexInside);
        }

        /**
         * By default, `visual` is applied to style (to support visualMap).
         * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
         * it can be implemented as:
         * `api.style({stroke: api.visual('color'), fill: null})`;
         * @public
         * @param {Object} [extra]
         * @param {number} [dataIndexInside=currDataIndexInside]
         */
        function style(extra, dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            updateCache(dataIndexInside);

            var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();

            currVisualColor != null && (itemStyle.fill = currVisualColor);
            var opacity = data.getItemVisual(dataIndexInside, 'opacity');
            opacity != null && (itemStyle.opacity = opacity);

            labelHelper.setTextToStyle(
                data, dataIndexInside, currLabelValueDim, itemStyle,
                customSeries, currLabelNormalModel, currVisualColor
            );

            extra && zrUtil.extend(itemStyle, extra);
            return itemStyle;
        }

        /**
         * @public
         * @param {Object} [extra]
         * @param {number} [dataIndexInside=currDataIndexInside]
         */
        function styleEmphasis(extra, dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            updateCache(dataIndexInside);

            var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();

            labelHelper.setTextToStyle(
                data, dataIndexInside, currLabelValueDim, itemStyle,
                customSeries, currLabelEmphasisModel, currVisualColor
            );

            extra && zrUtil.extend(itemStyle, extra);
            return itemStyle;
        }

        /**
         * @public
         * @param {string} visualType
         * @param {number} [dataIndexInside=currDataIndexInside]
         */
        function visual(visualType, dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            return data.getItemVisual(dataIndexInside, visualType);
        }

        /**
         * @public
         * @param {number} opt.count Positive interger.
         * @param {number} [opt.barWidth]
         * @param {number} [opt.barMaxWidth]
         * @param {number} [opt.barGap]
         * @param {number} [opt.barCategoryGap]
         * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
         */
        function barLayout(opt) {
            if (coordSys.getBaseAxis) {
                var baseAxis = coordSys.getBaseAxis();
                return barGrid.getLayoutOnAxis(zrUtil.defaults({axis: baseAxis}, opt), api);
            }
        }

        /**
         * @public
         * @return {Array.<number>}
         */
        function currentSeriesIndices() {
            return ecModel.getCurrentSeriesIndices();
        }

        /**
         * @public
         * @param {Object} opt
         * @param {string} [opt.fontStyle]
         * @param {number} [opt.fontWeight]
         * @param {number} [opt.fontSize]
         * @param {string} [opt.fontFamily]
         * @return {string} font string
         */
        function font(opt) {
            return graphicUtil.getFont(opt, ecModel);
        }
    }

    function wrapEncodeDef(data) {
        var encodeDef = {};
        zrUtil.each(data.dimensions, function (dimName, dataDimIndex) {
            var dimInfo = data.getDimensionInfo(dimName);
            if (!dimInfo.isExtraCoord) {
                var coordDim = dimInfo.coordDim;
                var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
                dataDims[dimInfo.coordDimIndex] = dataDimIndex;
            }
        });
        return encodeDef;
    }

    function createOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
        el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
        el && data.setItemGraphicEl(dataIndex, el);
    }

    function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
        var elOptionType = elOption.type;
        if (el
            && elOptionType !== el.__customGraphicType
            && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
            && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
            && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
        ) {
            group.remove(el);
            el = null;
        }

        // `elOption.type` is undefined when `renderItem` returns nothing.
        if (elOptionType == null) {
            return;
        }

        var isInit = !el;
        !el && (el = createEl(elOption));
        updateEl(el, dataIndex, elOption, animatableModel, data, isInit);

        elOptionType === 'group' && zrUtil.each(elOption.children, function (childOption, index) {
            doCreateOrUpdate(el.childAt(index), dataIndex, childOption, animatableModel, el, data);
        });

        group.add(el);

        return el;
    }

});
<commit_msg>tweak<commit_after>define(function (require) {

    var echarts = require('../echarts');
    var zrUtil = require('zrender/core/util');
    var graphicUtil = require('../util/graphic');
    var labelHelper = require('./helper/labelHelper');
    var createListFromArray = require('./helper/createListFromArray');
    var barGrid = require('../layout/barGrid');

    var ITEM_STYLE_NORMAL_PATH = ['itemStyle', 'normal'];
    var ITEM_STYLE_EMPHASIS_PATH = ['itemStyle', 'emphasis'];
    var LABEL_NORMAL = ['label', 'normal'];
    var LABEL_EMPHASIS = ['label', 'emphasis'];

    /**
     * To reduce total package size of each coordinate systems, the modules `prepareCustom`
     * of each coordinate systems are not required by each coordinate systems directly, but
     * required by the module `custom`.
     *
     * prepareInfoForCustomSeries {Function}: optional
     *     @return {Object} {coordSys: {...}, api: {
     *         coord: function (data, clamp) {}, // return point in global.
     *         size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
     *     }}
     */
    var prepareCustoms = {
        cartesian2d: require('../coord/cartesian/prepareCustom'),
        geo: require('../coord/geo/prepareCustom'),
        singleAxis: require('../coord/single/prepareCustom'),
        polar: require('../coord/polar/prepareCustom'),
        calendar: require('../coord/calendar/prepareCustom')
    };

    // ------
    // Model
    // ------

    echarts.extendSeriesModel({

        type: 'series.custom',

        dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],

        defaultOption: {
            coordinateSystem: 'cartesian2d',
            zlevel: 0,
            z: 2,
            legendHoverLink: true

            // Cartesian coordinate system
            // xAxisIndex: 0,
            // yAxisIndex: 0,

            // Polar coordinate system
            // polarIndex: 0,

            // Geo coordinate system
            // geoIndex: 0,

            // label: {}
            // itemStyle: {}
        },

        getInitialData: function (option, ecModel) {
            return createListFromArray(option.data, this, ecModel);
        }
    });

    // -----
    // View
    // -----

    echarts.extendChartView({

        type: 'custom',

        /**
         * @private
         * @type {module:echarts/data/List}
         */
        _data: null,

        /**
         * @override
         */
        render: function (customSeries, ecModel, api) {
            var oldData = this._data;
            var data = customSeries.getData();
            var group = this.group;
            var renderItem = makeRenderItem(customSeries, data, ecModel, api);

            data.diff(oldData)
                .add(function (newIdx) {
                    data.hasValue(newIdx) && createOrUpdate(
                        null, newIdx, renderItem(newIdx), customSeries, group, data
                    );
                })
                .update(function (newIdx, oldIdx) {
                    var el = oldData.getItemGraphicEl(oldIdx);
                    data.hasValue(newIdx)
                        ? createOrUpdate(
                            el, newIdx, renderItem(newIdx), customSeries, group, data
                        )
                        : (el && group.remove(el));
                })
                .remove(function (oldIdx) {
                    var el = oldData.getItemGraphicEl(oldIdx);
                    el && group.remove(el);
                })
                .execute();

            this._data = data;
        },

        /**
         * @override
         */
        dispose: zrUtil.noop
    });

    function createEl(elOption) {
        var graphicType = elOption.type;
        var el;

        if (graphicType === 'path') {
            var shape = elOption.shape;
            el = graphicUtil.makePath(
                shape.pathData,
                null,
                {
                    x: shape.x || 0,
                    y: shape.y || 0,
                    width: shape.width || 0,
                    height: shape.height || 0
                },
                'center'
            );
            el.__customPathData = elOption.pathData;
        }
        else if (graphicType === 'image') {
            el = new graphicUtil.Image({
            });
            el.__customImagePath = elOption.style.image;
        }
        else if (graphicType === 'text') {
            el = new graphicUtil.Text({
            });
            el.__customText = elOption.style.text;
        }
        else {
            var Clz = graphicUtil[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];

            if (__DEV__) {
                zrUtil.assert(Clz, 'graphic type "' + graphicType + '" can not be found.');
            }

            el = new Clz();
        }

        el.__customGraphicType = graphicType;

        return el;
    }

    function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
        var targetProps = {};
        var elOptionStyle = elOption.style || {};

        elOption.shape && (targetProps.shape = zrUtil.clone(elOption.shape));
        elOption.position && (targetProps.position = elOption.position.slice());
        elOption.scale && (targetProps.scale = elOption.scale.slice());
        elOption.origin && (targetProps.origin = elOption.origin.slice());
        elOption.rotation && (targetProps.rotation = elOption.rotation);

        if (el.type === 'image' && elOption.style) {
            var targetStyle = targetProps.style = {};
            zrUtil.each(['x', 'y', 'width', 'height'], function (prop) {
                prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
            });
        }

        if (el.type === 'text' && elOption.style) {
            var targetStyle = targetProps.style = {};
            zrUtil.each(['x', 'y'], function (prop) {
                prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
            });
        }

        if (el.type !== 'group') {
            el.useStyle(elOptionStyle);

            // Init animation.
            if (isInit) {
                el.style.opacity = 0;
                var targetOpacity = elOptionStyle.opacity;
                targetOpacity == null && (targetOpacity = 1);
                graphicUtil.initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
            }
        }

        if (isInit) {
            el.attr(targetProps);
        }
        else {
            graphicUtil.updateProps(el, targetProps, animatableModel, dataIndex);
        }

        // z2 must not be null/undefined, otherwise sort error may occur.
        el.attr({z2: elOption.z2 || 0, silent: elOption.silent});

        el.styleEmphasis !== false && graphicUtil.setHoverStyle(el, el.styleEmphasis);
    }

    function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
        if (elOptionStyle[prop] != null && !isInit) {
            targetStyle[prop] = elOptionStyle[prop];
            elOptionStyle[prop] = oldElStyle[prop];
        }
    }

    function makeRenderItem(customSeries, data, ecModel, api) {
        var renderItem = customSeries.get('renderItem');
        var coordSys = customSeries.coordinateSystem;

        if (__DEV__) {
            zrUtil.assert(renderItem, 'series.render is required.');
            zrUtil.assert(
                coordSys.prepareCustoms || prepareCustoms[coordSys.type],
                'This coordSys does not support custom series.'
            );
        }

        var prepareResult = coordSys.prepareCustoms
            ? coordSys.prepareCustoms()
            : prepareCustoms[coordSys.type](coordSys);

        var userAPI = zrUtil.defaults({
            getWidth: api.getWidth,
            getHeight: api.getHeight,
            getZr: api.getZr,
            getDevicePixelRatio: api.getDevicePixelRatio,
            value: value,
            style: style,
            styleEmphasis: styleEmphasis,
            visual: visual,
            barLayout: barLayout,
            currentSeriesIndices: currentSeriesIndices,
            font: font
        }, prepareResult.api);

        var userParams = {
            context: {},
            seriesId: customSeries.id,
            seriesName: customSeries.name,
            seriesIndex: customSeries.seriesIndex,
            coordSys: prepareResult.coordSys,
            dataInsideLength: data.count(),
            encode: wrapEncodeDef(customSeries.getData())
        };

        // Do not support call `api` asynchronously without dataIndexInside input.
        var currDataIndexInside;
        var currDirty = true;
        var currItemModel;
        var currLabelNormalModel;
        var currLabelEmphasisModel;
        var currLabelValueDim;
        var currVisualColor;

        return function (dataIndexInside) {
            currDataIndexInside = dataIndexInside;
            currDirty = true;
            return renderItem && renderItem(
                zrUtil.defaults({
                    dataIndexInside: dataIndexInside,
                    dataIndex: data.getRawIndex(dataIndexInside)
                }, userParams),
                userAPI
            ) || {};
        };

        // Do not update cache until api called.
        function updateCache(dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            if (currDirty) {
                currItemModel = data.getItemModel(dataIndexInside);
                currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
                currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
                currLabelValueDim = labelHelper.findLabelValueDim(data);
                currVisualColor = data.getItemVisual(dataIndexInside, 'color');

                currDirty = false;
            }
        }

        /**
         * @public
         * @param {nubmer|string} dim
         * @param {number} [dataIndexInside=currDataIndexInside]
         * @return {number|string} value
         */
        function value(dim, dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            return data.get(data.getDimension(dim || 0), dataIndexInside);
        }

        /**
         * By default, `visual` is applied to style (to support visualMap).
         * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
         * it can be implemented as:
         * `api.style({stroke: api.visual('color'), fill: null})`;
         * @public
         * @param {Object} [extra]
         * @param {number} [dataIndexInside=currDataIndexInside]
         */
        function style(extra, dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            updateCache(dataIndexInside);

            var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();

            currVisualColor != null && (itemStyle.fill = currVisualColor);
            var opacity = data.getItemVisual(dataIndexInside, 'opacity');
            opacity != null && (itemStyle.opacity = opacity);

            labelHelper.setTextToStyle(
                data, dataIndexInside, currLabelValueDim, itemStyle,
                customSeries, currLabelNormalModel, currVisualColor
            );

            extra && zrUtil.extend(itemStyle, extra);
            return itemStyle;
        }

        /**
         * @public
         * @param {Object} [extra]
         * @param {number} [dataIndexInside=currDataIndexInside]
         */
        function styleEmphasis(extra, dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            updateCache(dataIndexInside);

            var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();

            labelHelper.setTextToStyle(
                data, dataIndexInside, currLabelValueDim, itemStyle,
                customSeries, currLabelEmphasisModel, currVisualColor
            );

            extra && zrUtil.extend(itemStyle, extra);
            return itemStyle;
        }

        /**
         * @public
         * @param {string} visualType
         * @param {number} [dataIndexInside=currDataIndexInside]
         */
        function visual(visualType, dataIndexInside) {
            dataIndexInside == null && (dataIndexInside = currDataIndexInside);
            return data.getItemVisual(dataIndexInside, visualType);
        }

        /**
         * @public
         * @param {number} opt.count Positive interger.
         * @param {number} [opt.barWidth]
         * @param {number} [opt.barMaxWidth]
         * @param {number} [opt.barGap]
         * @param {number} [opt.barCategoryGap]
         * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
         */
        function barLayout(opt) {
            if (coordSys.getBaseAxis) {
                var baseAxis = coordSys.getBaseAxis();
                return barGrid.getLayoutOnAxis(zrUtil.defaults({axis: baseAxis}, opt), api);
            }
        }

        /**
         * @public
         * @return {Array.<number>}
         */
        function currentSeriesIndices() {
            return ecModel.getCurrentSeriesIndices();
        }

        /**
         * @public
         * @param {Object} opt
         * @param {string} [opt.fontStyle]
         * @param {number} [opt.fontWeight]
         * @param {number} [opt.fontSize]
         * @param {string} [opt.fontFamily]
         * @return {string} font string
         */
        function font(opt) {
            return graphicUtil.getFont(opt, ecModel);
        }
    }

    function wrapEncodeDef(data) {
        var encodeDef = {};
        zrUtil.each(data.dimensions, function (dimName, dataDimIndex) {
            var dimInfo = data.getDimensionInfo(dimName);
            if (!dimInfo.isExtraCoord) {
                var coordDim = dimInfo.coordDim;
                var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
                dataDims[dimInfo.coordDimIndex] = dataDimIndex;
            }
        });
        return encodeDef;
    }

    function createOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
        el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
        el && data.setItemGraphicEl(dataIndex, el);
    }

    function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
        var elOptionType = elOption.type;
        if (el
            && elOptionType !== el.__customGraphicType
            && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
            && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
            && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
        ) {
            group.remove(el);
            el = null;
        }

        // `elOption.type` is undefined when `renderItem` returns nothing.
        if (elOptionType == null) {
            return;
        }

        var isInit = !el;
        !el && (el = createEl(elOption));
        updateEl(el, dataIndex, elOption, animatableModel, data, isInit);

        elOptionType === 'group' && zrUtil.each(elOption.children, function (childOption, index) {
            doCreateOrUpdate(el.childAt(index), dataIndex, childOption, animatableModel, el, data);
        });

        group.add(el);

        return el;
    }

});
<|endoftext|>


<commit_before>/**
 * @file IThenable interface
 * @since 0.2.2
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfDefineInterface*/ // Internal interface definition helper
/*global _gpfSyncReadSourceJSON*/ // Reads a source json file (only in source mode)
/*exported _gpfIThenable*/ // gpf.interfaces.IThenable
/*exported _gpfPromisify*/ // Converts any value into a Promise
/*exported _gpfPromisifyDefined*/ // Converts any value but undefined into a Promise
/*#endif*/

/**
 * The Thenable interface helps identifying Promise object through the
 * [then](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) method
 *
 * @interface gpf.interfaces.IThenable
 * @since 0.2.2
 */

/**
 * The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure
 * cases of the Promise
 *
 * @method gpf.interfaces.IThenable#then
 * @param {Function} onFulfilled called if the Promise is fulfilled
 * @param {Function} [onRejected] called if the Promise is rejected
 * @return {Promise} Promise
 * @since 0.2.2
 */

/**
 * IThenable interface specifier
 *
 * @type {gpf.interfaces.IThenable}
 * @since 0.2.2
 */
var _gpfIThenable = _gpfDefineInterface("Thenable",
    _gpfSyncReadSourceJSON("interfaces/thenable.json"));

/**
 * Converts any value into a promise.
 * If the value implements {@link gpf.interfaces.IThenable}, it is considered as a promise.
 *
 * @param {*} value Value to convert
 * @return {Promise<*>} Promisified version of the value
 */
function _gpfPromisify (value) {
    if (gpf.interfaces.isImplementedBy(gpf.interfaces.IThenable, value)) {
        return value;
    }
    return Promise.resolve(value);
}

/**
 * Converts value into a promise if not undefined.
 * If the value implements {@link gpf.interfaces.IThenable}, it is considered as a promise.
 *
 * @param {*} value Value to convert
 * @return {Promise<*>|undefined} Promisified version of the value or undefined
 */
function _gpfPromisifyDefined (value) {
    if (undefined !== value) {
        return _gpfPromisify(value);
    }
}

/** @gpf:sameas _gpfPromisify */
gpf.promisify = _gpfPromisify;

/** @gpf:sameas _gpfPromisifyDefined */
gpf.promisifyDefined = _gpfPromisifyDefined;
<commit_msg>Documentation<commit_after>/**
 * @file IThenable interface
 * @since 0.2.2
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfDefineInterface*/ // Internal interface definition helper
/*global _gpfSyncReadSourceJSON*/ // Reads a source json file (only in source mode)
/*exported _gpfIThenable*/ // gpf.interfaces.IThenable
/*exported _gpfPromisify*/ // Converts any value into a Promise
/*exported _gpfPromisifyDefined*/ // Converts any value but undefined into a Promise
/*#endif*/

/**
 * The Thenable interface helps identifying Promise object through the
 * [then](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) method
 *
 * @interface gpf.interfaces.IThenable
 * @since 0.2.2
 */

/**
 * The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure
 * cases of the Promise
 *
 * @method gpf.interfaces.IThenable#then
 * @param {Function} onFulfilled called if the Promise is fulfilled
 * @param {Function} [onRejected] called if the Promise is rejected
 * @return {Promise} Promise
 * @since 0.2.2
 */

/**
 * IThenable interface specifier
 *
 * @type {gpf.interfaces.IThenable}
 * @since 0.2.2
 */
var _gpfIThenable = _gpfDefineInterface("Thenable",
    _gpfSyncReadSourceJSON("interfaces/thenable.json"));

/**
 * Converts any value into a promise.
 * If the value implements {@link gpf.interfaces.IThenable}, it is considered as a promise.
 *
 * @param {*} value Value to convert
 * @return {Promise<*>} Promisified version of the value
 * @since 0.2.2
 */
function _gpfPromisify (value) {
    if (gpf.interfaces.isImplementedBy(gpf.interfaces.IThenable, value)) {
        return value;
    }
    return Promise.resolve(value);
}

/**
 * Converts value into a promise if not undefined.
 * If the value implements {@link gpf.interfaces.IThenable}, it is considered as a promise.
 *
 * @param {*} value Value to convert
 * @return {Promise<*>|undefined} Promisified version of the value or undefined
 * @since 0.2.2
 */
function _gpfPromisifyDefined (value) {
    if (undefined !== value) {
        return _gpfPromisify(value);
    }
}

/**
 * @gpf:sameas _gpfPromisify
 * @since 0.2.2
 */
gpf.promisify = _gpfPromisify;

/**
 * @gpf:sameas _gpfPromisifyDefined
 * @since 0.2.2
 */
gpf.promisifyDefined = _gpfPromisifyDefined;
<|endoftext|>


<commit_before>'use strict'

function SettingsWorld() {
    this.__init__()
}

SettingsWorld.prototype = {

    previous_world: null,

    __init__: function() {

        // Inherit world properties.
        World.call(this, 'SettingsWorld')

        var position = new THREE.Vector3(500, 500, 700)
        this.normal = new THREE.Vector3(-.5, 0, -.85)
        this.normal.normalize()
        this.profile_editor = new FloatingWall(1024, 512, position, this.normal, this)

        var create_entity_wall_title = this.profile_editor.add_floating_2d_text(1024 / 2, 'Edit ur profile kidddooo', TYPE_TITLE, 1024 / -4, 2, 0, 0)
        this.profile_editor.add_object_to_remove_later(create_entity_wall_title)

        var profile_name = this.profile_editor.add_floating_2d_text(1024 / 4, 'Profile Name', TYPE_INPUT_REGULAR, 1024 / -2, 2, 2, 0)
        this.profile_editor.add_object_to_remove_later(profile_name)

        var lightr = new THREE.PointLight(0xff8579, .8, 0)
        lightr.position.set(1000, 100, 0)
        this.add_to_scene(lightr)

        var lightg = new THREE.PointLight(0xb1ff90, .8, 0)
        lightg.position.set(0, 100, 1000)
        this.add_to_scene(lightg)

        var lightb = new THREE.PointLight(0x84b5ff, .8, 0)
        lightb.position.set(500, 100, 500)
        this.add_to_scene(lightb)
    },

    update: function() {
        this.update_interactive_objects()
    },

    key_down_event: function(event) {
        this.key_down_event_for_interactive_objects(event)
    },

    enter_world: function() {
        this.player.disengage()
        if (!PAUSED_MENU.currently_displayed) {
            this.player.enable_controls()
        }

        this.player.set_position(new THREE.Vector3(0, 10, 0))

        this.previous_world = WORLD_MANAGER.previous_world
    },

    exit_world: function() {
    }
}<commit_msg>general updating 46<commit_after>'use strict'

function SettingsWorld() {
    this.__init__()
}

SettingsWorld.prototype = {

    previous_world: null,

    __init__: function() {

        // Inherit world properties.
        World.call(this, 'SettingsWorld')

        var position = new THREE.Vector3(500, 500, 700)
        this.normal = new THREE.Vector3(-.5, 0, -.85)
        this.normal.normalize()
        this.profile_editor = new FloatingWall(1024, 512, position, this.normal, this)

        var create_entity_wall_title = this.profile_editor.add_floating_2d_text(1024 / 2, 'Edit ur profile kidddooo', TYPE_TITLE, 1024 / -4, 2, 0, 0)
        this.profile_editor.add_object_to_remove_later(create_entity_wall_title)

        var profile_name = this.profile_editor.add_floating_2d_text(1024 / 4, 'Profile Name', TYPE_INPUT_REGULAR, 1024 / -4, 2, 3, 0)
        this.profile_editor.add_object_to_remove_later(profile_name)

        var profile_name_input = this.profile_editor.add_floating_2d_text(1024 / 2, '', TYPE_INPUT_REGULAR, 1024 / -4 + (1024 / 4) + 50, 2, 3, 0)
        this.profile_editor.add_object_to_remove_later(profile_name_input)

        var lightr = new THREE.PointLight(0xff8579, .8, 0)
        lightr.position.set(1000, 100, 0)
        this.add_to_scene(lightr)

        var lightg = new THREE.PointLight(0xb1ff90, .8, 0)
        lightg.position.set(0, 100, 1000)
        this.add_to_scene(lightg)

        var lightb = new THREE.PointLight(0x84b5ff, .8, 0)
        lightb.position.set(500, 100, 500)
        this.add_to_scene(lightb)
    },

    update: function() {
        this.update_interactive_objects()
    },

    key_down_event: function(event) {
        this.key_down_event_for_interactive_objects(event)
    },

    enter_world: function() {
        this.player.disengage()
        if (!PAUSED_MENU.currently_displayed) {
            this.player.enable_controls()
        }

        this.player.set_position(new THREE.Vector3(0, 10, 0))

        this.previous_world = WORLD_MANAGER.previous_world
    },

    exit_world: function() {
    }
}<|endoftext|>


<commit_before>/* eslint-env mocha*/

const invRegLowGamma = require('./invRegLowGamma.js');
const expect = require('chai').expect;

describe('invRegLowGamma', function() {
	describe('smoke tests', function() {
		it('should exist', ()=>{
			expect(invRegLowGamma).to.exist;
		});

		it('should be a function', ()=>{
			expect(invRegLowGamma).to.be.a('function');
		});
	});

	describe('the function returns the lower regularized incomplete gamma function evaluated at (p,a)', function() {
		it('should return 228.60679774997897 for p=5 and a=5', ()=>{
			expect(invRegLowGamma(5, 5)).to.equal(228.60679774997897);
		});

		it('should return 6.475606702314761 for p=0.666 and a=5.75', ()=>{
			expect(invRegLowGamma(0.666, 5.75)).to.equal(6.475606702314761);
		});

		it('should return 100 for p=5 and a=0', ()=>{
			expect(invRegLowGamma(5, 0)).to.equal(100);
		});

        it('should return 1.678346990016661 for p=0.5 and a=2', ()=>{
			expect(invRegLowGamma(0.5, 2)).to.equal(1.678346990016661);
		});

        it('should return 0.3759413598815398 for p=0.5 and a=0.666', ()=>{
			expect(invRegLowGamma(0.5, 0.666)).to.equal(0.3759413598815398);
		});

        it('should return 0 for p=-1(any negative number) and a=2', ()=>{
			expect(invRegLowGamma(-1, 2)).to.equal(0);
		});
	});

	describe('error tests', function() {
		it('should return a error for a NaN input in the parameter: p', ()=>{
			expect(()=>invRegLowGamma('Not a number', 6)).to.throw('The value in param "p" is not an number.');
		});

        it('should return a error for a NaN input in the parameter: a', ()=>{
			expect(()=>invRegLowGamma(6, 'Not a number')).to.throw('The value in param "a" is not an number.');
		});
	});
});
<commit_msg>A describe text changed in the invRegLowGamma<commit_after>/* eslint-env mocha*/

const invRegLowGamma = require('./invRegLowGamma.js');
const expect = require('chai').expect;

describe('invRegLowGamma', function() {
	describe('smoke tests', function() {
		it('should exist', ()=>{
			expect(invRegLowGamma).to.exist;
		});

		it('should be a function', ()=>{
			expect(invRegLowGamma).to.be.a('function');
		});
	});

	describe('Returns the inverse of the lower regularized incomplete Gamma function evaluated at (p,a)', function() {
		it('should return 228.60679774997897 for p=5 and a=5', ()=>{
			expect(invRegLowGamma(5, 5)).to.equal(228.60679774997897);
		});

		it('should return 6.475606702314761 for p=0.666 and a=5.75', ()=>{
			expect(invRegLowGamma(0.666, 5.75)).to.equal(6.475606702314761);
		});

		it('should return 100 for p=5 and a=0', ()=>{
			expect(invRegLowGamma(5, 0)).to.equal(100);
		});

        it('should return 1.678346990016661 for p=0.5 and a=2', ()=>{
			expect(invRegLowGamma(0.5, 2)).to.equal(1.678346990016661);
		});

        it('should return 0.3759413598815398 for p=0.5 and a=0.666', ()=>{
			expect(invRegLowGamma(0.5, 0.666)).to.equal(0.3759413598815398);
		});

        it('should return 0 for p=-1(any negative number) and a=2', ()=>{
			expect(invRegLowGamma(-1, 2)).to.equal(0);
		});
	});

	describe('error tests', function() {
		it('should return a error for a NaN input in the parameter: p', ()=>{
			expect(()=>invRegLowGamma('Not a number', 6)).to.throw('The value in param "p" is not an number.');
		});

        it('should return a error for a NaN input in the parameter: a', ()=>{
			expect(()=>invRegLowGamma(6, 'Not a number')).to.throw('The value in param "a" is not an number.');
		});
	});
});
<|endoftext|>


<commit_before>/* global magazineBuilder */

(function(window, $, app, builder) {
    function Page() {
        var $currentPage;

        this.get = function() {
            if (typeof $currentPage === 'undefined') {
                $currentPage = $('#page' + builder.get_CurrentPageNumber());
            }

            return $currentPage;
        };

        this.getContent = function() {
            return this.get().find('.magazineContent');
        };

        this.getId = function() {
            return this.get().data('id');
        };

        this.getNumber = function() {
            return this.get().data('page-number');
        }

        this.getTitle = function() {
            return this.get().data('feature-title');
        };

        this.getIssueId = function() {
            return $("#magazineHolder").data('id');
        };
    }

    app.modules.Page = Page;
})(window, jQuery, MagTool, magazineBuilder);
<commit_msg>Page.js fix<commit_after>/* global magazineBuilder */

(function(window, $, app, builder) {
    function Page() {
        var $currentPage;

        this.get = function() {
            if (typeof $currentPage === 'undefined') {
                $currentPage = $('#page' + builder.get_CurrentPageNumber());
            }

            return $currentPage;
        };

        this.getContent = function() {
            return this.get().find('.magazineContent');
        };

        this.getId = function() {
            return this.get().data('id');
        };

        this.getNumber = function() {
            return this.get().data('page-number');
        };

        this.getTitle = function() {
            return this.get().data('feature-title');
        };

        this.getIssueId = function() {
            return $("#magazineHolder").data('id');
        };
    }

    app.modules.Page = Page;
})(window, jQuery, MagTool, magazineBuilder);
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var specialCollision = {
        bottomRight: [
            129,
            136,
            132,
            67,
            45,
            15
        ],
        bottomLeft: [
            30,
            33,
            37,
            40,
            95,
            117
        ],
        bottomThird: [
            102
        ],
        topThird: [
        ],
        topHalf: [
        ],
        bottomHalf: [
        ],
        exclude: [
            93,
            118,
            143,
            65,
            90,
            155
        ]
    };

    Game.Level = function(game) {
        this.debugMode = false;

        this.levelSize = {
            x: 0,
            y: 0,
            width: 3000,
            height: 3720
        };

        this.toggleFullScreen = function() {
            if (this.game.scale.isFullScreen) {
                this.game.scale.stopFullScreen();
            } else {
                this.game.scale.startFullScreen(false);
            }
        };

        this.toggleDebug = function() {
            if (this.debugMode) {
                this.fpsMeter.parent.remove(this.fpsMeter);
                this.level.debug = false;
            } else {
                this.game.add.existing(this.fpsMeter);
                this.level.debug = true;
            }

            this.level.dirty = true;
            this.debugMode = !this.debugMode;
        };
    };

    Game.Level.prototype = Object.create(self.Game.Utils.BaseState.prototype);
    Game.Level.prototype.constructor = Game.Level;
    /**
     * Load content here, e.g. this.load.image('myDude', '/assets/images/myDude.png')
     */
    Game.Level.prototype.preload = function() {
        var preloadBar = this.game.add.sprite(this.game.width / 2, this.game.height / 2, 'preloadBar');
        preloadBar.fixedToCamera = true;
        preloadBar.anchor.set(0.5);
        this.game.load.setPreloadSprite(preloadBar);

        this.game.load.spritesheet('player1', 'assets/player1.png', 80, 97);
        this.game.load.image('bg', 'assets/background.png');
        this.game.load.spritesheet('tile', 'assets/spritesheet.png', 70, 70);

        this.game.load.atlasXML('alienYellow', 'assets/alienYellow.png', 'assets/alienYellow.xml');
        this.game.load.atlasXML('UI', 'assets/UI.png', 'assets/UI.xml');
        this.game.load.atlasXML('p1', 'assets/p1_spritesheet.png', 'assets/p1_spritesheet.xml');

        this.game.load.audio('solskenspromenad', 'assets/Solskenspromenad.mp3');

        this.game.load.image('plank', 'assets/plank.png');

        this.game.load.tilemap('map', 'assets/spel.json', null, Phaser.Tilemap.TILED_JSON);
    };

    /**
     * Generates any level related objects
     * @return {[type]} [description]
     */
    Game.Level.prototype.generateLevel = function() {
        this.map = this.game.add.tilemap('map');
        this.map.addTilesetImage('tile');

        this.levelSize.width = this.map.width * this.map.tileWidth;
        this.levelSize.height = this.map.height * this.map.tileHeight;

        this.bg = this.game.add.sprite(0, 0, 'bg');
        this.bg.fixedToCamera = true;

        // The layer that the player does not interact with
        this.behind = this.map.createLayer('behind');

        this.level = this.map.createLayer('collision');
        // The layer containing platforms
        var firstID = this.map.tilesets[this.map.getTilesetIndex('tile')].firstgid;
        var collisionTiles = [];
        _.forEach(this.level.layer.data, function(e) {
            _.forEach(e, function(t) {
                if (t.index > -1 && !_.contains(specialCollision.exclude, t.index - firstID)) {
                    collisionTiles.push(t.index);
                }

                if (_.contains(specialCollision.bottomRight, t.index - firstID)) {
                    t.slope = 'HALF_TRIANGLE_BOTTOM_RIGHT';
                }

                if (_.contains(specialCollision.bottomLeft, t.index - firstID)) {
                    t.slope = 'HALF_TRIANGLE_BOTTOM_LEFT';
                }

                if (_.contains(specialCollision.bottomThird, t.index - firstID)) {
                    t.worldY += 2 * t.height / 3;
                    t.height /= 3;
                }

                if (_.contains(specialCollision.topThird, t.index - firstID)) {
                    t.height /= 3;
                }

                if (_.contains(specialCollision.bottomHalf, t.index - firstID)) {
                    t.worldY += t.height * 0.5;
                    t.height *= 0.5;
                }

                if (_.contains(specialCollision.bottomHalf, t.index - firstID)) {
                    t.height *= 0.5;
                }
            });
        });
        this.front = this.map.createLayer('front');

        this.level.resizeWorld();

        var renderSettings = {
            enableScrollDelta: true
        };
        this.level.renderSettings = renderSettings;
        this.behind.renderSettings = renderSettings;
        this.front.renderSettings = renderSettings;

        this.map.setLayer(this.level);
        this.map.setCollision(collisionTiles);
    };

    Game.Level.prototype.setUtils = function() {
        this.fpsMeter = new Game.Utils.FpsMeter(this.game, 32, 32);

        this.f2 = this.game.input.keyboard.addKey(113);
        this.f2.onUp.add(function() {
            this.toggleDebug();
        }, this);

        this.f11 = this.game.input.keyboard.addKey(122);
        this.f11.onUp.add(function() {
            this.toggleFullScreen();
        }, this);

        this.f4 = this.game.input.keyboard.addKey(115);
        this.f4.onUp.add(function() {
            if (this.p1) {
                this.p1.godMode = !this.p1.godMode;

                if (this.p1.godMode) {
                    this.p1.body.allowGravity = false;
                } else {
                    this.p1.body.allowGravity = true;
                }
            }
        }, this);
    };

    Game.Level.prototype.generateObjects = function() {
        _.forEach(this.map.objects['objects'], function(obj) {
            switch (obj.type) {
                case 'spawn':
                    if (this.p1) {
                        var x = obj.x + obj.width / 2;
                        var y = obj.y + obj.height / 2;

                        this.p1.reset(x, y);
                        this.p1._cache[4] = 0;
                    }
                    break;
            }
        }, this);
    };

    Game.Level.prototype.spawnPlayer = function(x, y) {
        this.p1 = new Game.Player(this.game, x || 0, y || 0);
        this.game.add.existing(this.p1);
        this.entitiesGroup.add(this.p1);
        this.game.camera.follow(this.p1);
        this.game.camera.deadzone = this.getCameraDeadzone();
        this.game.camera.roundPx = false;
    };

    /**
     * Initialization logic here
     */
    Game.Level.prototype.create = function() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.game.physics.arcade.gravity = Game.gravity;
        this.game.physics.arcade.TILE_BIAS = 70;

        this.setUtils();
        this.generateLevel();

        this.entitiesGroup = this.game.add.group();

        this.spawnPlayer();

        this.objectiveManager = new Game.ObjectiveManager(this.game, this.game.width - 50, this.game.height * 0.5);
        this.game.add.existing(this.objectiveManager);

        this.generateObjects();

        this.objectiveManager.createObjectives(this.map, this.map.objects['objectives'], this.p1);

        this.alienYellow = new Game.Enemy(this.game, this.p1.position.x - this.game.width, this.p1.position.y);
        this.alienYellow.controller.hostile = false;
        this.game.add.existing(this.alienYellow);
        this.entitiesGroup.add(this.alienYellow);

        var solskenspromenad = this.game.add.audio('solskenspromenad', 0.6, true, true);
        solskenspromenad.play();

        this.HUD = new Game.HUD(this.game);

        this.dialogueManager = new Game.DialogueManager(this.game, this.HUD);

        this.triggerManager = new Game.Trigger.TriggerManager(this.game);

        var dialogue = new Game.Dialogue(this.game, [
            {
                text: 'Use arrows keys to walk, and spacebar to jump'
            }, {
                text: 'And remember, have fun!',
                title: 'lplasödlasd'
            }
        ], 'TEST TU TRE');

        var trigger = new Game.Trigger.ZoneTrigger(this.game, true, new Phaser.Rectangle(this.p1.position.x - 200, this.p1.position.y - 50, 100, 100), this.p1);
        this.triggerManager.addTrigger(trigger);

        trigger.onActive.add(function() {
            this.dialogueManager.setDialogue(dialogue);
        }, this);

        trigger.onInactive.add(function() {
            this.dialogueManager.hidden = true;
        }, this);

        this.f6 = this.game.input.keyboard.addKey(117);
        this.f6.onUp.add(function() {
            this.dialogueManager.nextSlide();
        }, this);

        this.game.world.bringToTop(this.objectiveManager);
    };

    Game.Level.prototype.update = function() {
        this.alienYellow.controller.update(this.p1);
        this.game.physics.arcade.collide(this.entitiesGroup, this.level);
    };

    Game.Level.prototype.render = function() {
        if (this.debugMode) {
            this.entitiesGroup.forEach(function(entity) {
                this.game.debug.body(entity);
            }, this);
        }
    };
})();<commit_msg>Made use of critera functionality in test trigger<commit_after>(function() {
    'use strict';

    var specialCollision = {
        bottomRight: [
            129,
            136,
            132,
            67,
            45,
            15
        ],
        bottomLeft: [
            30,
            33,
            37,
            40,
            95,
            117
        ],
        bottomThird: [
            102
        ],
        topThird: [
        ],
        topHalf: [
        ],
        bottomHalf: [
        ],
        exclude: [
            93,
            118,
            143,
            65,
            90,
            155
        ]
    };

    Game.Level = function(game) {
        this.debugMode = false;

        this.levelSize = {
            x: 0,
            y: 0,
            width: 3000,
            height: 3720
        };

        this.toggleFullScreen = function() {
            if (this.game.scale.isFullScreen) {
                this.game.scale.stopFullScreen();
            } else {
                this.game.scale.startFullScreen(false);
            }
        };

        this.toggleDebug = function() {
            if (this.debugMode) {
                this.fpsMeter.parent.remove(this.fpsMeter);
                this.level.debug = false;
            } else {
                this.game.add.existing(this.fpsMeter);
                this.level.debug = true;
            }

            this.level.dirty = true;
            this.debugMode = !this.debugMode;
        };
    };

    Game.Level.prototype = Object.create(self.Game.Utils.BaseState.prototype);
    Game.Level.prototype.constructor = Game.Level;
    /**
     * Load content here, e.g. this.load.image('myDude', '/assets/images/myDude.png')
     */
    Game.Level.prototype.preload = function() {
        var preloadBar = this.game.add.sprite(this.game.width / 2, this.game.height / 2, 'preloadBar');
        preloadBar.fixedToCamera = true;
        preloadBar.anchor.set(0.5);
        this.game.load.setPreloadSprite(preloadBar);

        this.game.load.spritesheet('player1', 'assets/player1.png', 80, 97);
        this.game.load.image('bg', 'assets/background.png');
        this.game.load.spritesheet('tile', 'assets/spritesheet.png', 70, 70);

        this.game.load.atlasXML('alienYellow', 'assets/alienYellow.png', 'assets/alienYellow.xml');
        this.game.load.atlasXML('UI', 'assets/UI.png', 'assets/UI.xml');
        this.game.load.atlasXML('p1', 'assets/p1_spritesheet.png', 'assets/p1_spritesheet.xml');

        this.game.load.audio('solskenspromenad', 'assets/Solskenspromenad.mp3');

        this.game.load.image('plank', 'assets/plank.png');

        this.game.load.tilemap('map', 'assets/spel.json', null, Phaser.Tilemap.TILED_JSON);
    };

    /**
     * Generates any level related objects
     * @return {[type]} [description]
     */
    Game.Level.prototype.generateLevel = function() {
        this.map = this.game.add.tilemap('map');
        this.map.addTilesetImage('tile');

        this.levelSize.width = this.map.width * this.map.tileWidth;
        this.levelSize.height = this.map.height * this.map.tileHeight;

        this.bg = this.game.add.sprite(0, 0, 'bg');
        this.bg.fixedToCamera = true;

        // The layer that the player does not interact with
        this.behind = this.map.createLayer('behind');

        this.level = this.map.createLayer('collision');
        // The layer containing platforms
        var firstID = this.map.tilesets[this.map.getTilesetIndex('tile')].firstgid;
        var collisionTiles = [];
        _.forEach(this.level.layer.data, function(e) {
            _.forEach(e, function(t) {
                if (t.index > -1 && !_.contains(specialCollision.exclude, t.index - firstID)) {
                    collisionTiles.push(t.index);
                }

                if (_.contains(specialCollision.bottomRight, t.index - firstID)) {
                    t.slope = 'HALF_TRIANGLE_BOTTOM_RIGHT';
                }

                if (_.contains(specialCollision.bottomLeft, t.index - firstID)) {
                    t.slope = 'HALF_TRIANGLE_BOTTOM_LEFT';
                }

                if (_.contains(specialCollision.bottomThird, t.index - firstID)) {
                    t.worldY += 2 * t.height / 3;
                    t.height /= 3;
                }

                if (_.contains(specialCollision.topThird, t.index - firstID)) {
                    t.height /= 3;
                }

                if (_.contains(specialCollision.bottomHalf, t.index - firstID)) {
                    t.worldY += t.height * 0.5;
                    t.height *= 0.5;
                }

                if (_.contains(specialCollision.bottomHalf, t.index - firstID)) {
                    t.height *= 0.5;
                }
            });
        });
        this.front = this.map.createLayer('front');

        this.level.resizeWorld();

        var renderSettings = {
            enableScrollDelta: true
        };
        this.level.renderSettings = renderSettings;
        this.behind.renderSettings = renderSettings;
        this.front.renderSettings = renderSettings;

        this.map.setLayer(this.level);
        this.map.setCollision(collisionTiles);
    };

    Game.Level.prototype.setUtils = function() {
        this.fpsMeter = new Game.Utils.FpsMeter(this.game, 32, 32);

        this.f2 = this.game.input.keyboard.addKey(113);
        this.f2.onUp.add(function() {
            this.toggleDebug();
        }, this);

        this.f11 = this.game.input.keyboard.addKey(122);
        this.f11.onUp.add(function() {
            this.toggleFullScreen();
        }, this);

        this.f4 = this.game.input.keyboard.addKey(115);
        this.f4.onUp.add(function() {
            if (this.p1) {
                this.p1.godMode = !this.p1.godMode;

                if (this.p1.godMode) {
                    this.p1.body.allowGravity = false;
                } else {
                    this.p1.body.allowGravity = true;
                }
            }
        }, this);
    };

    Game.Level.prototype.generateObjects = function() {
        _.forEach(this.map.objects['objects'], function(obj) {
            switch (obj.type) {
                case 'spawn':
                    if (this.p1) {
                        var x = obj.x + obj.width / 2;
                        var y = obj.y + obj.height / 2;

                        this.p1.reset(x, y);
                        this.p1._cache[4] = 0;
                    }
                    break;
            }
        }, this);
    };

    Game.Level.prototype.spawnPlayer = function(x, y) {
        this.p1 = new Game.Player(this.game, x || 0, y || 0);
        this.game.add.existing(this.p1);
        this.entitiesGroup.add(this.p1);
        this.game.camera.follow(this.p1);
        this.game.camera.deadzone = this.getCameraDeadzone();
        this.game.camera.roundPx = false;
    };

    /**
     * Initialization logic here
     */
    Game.Level.prototype.create = function() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.game.physics.arcade.gravity = Game.gravity;
        this.game.physics.arcade.TILE_BIAS = 70;

        this.setUtils();
        this.generateLevel();

        this.entitiesGroup = this.game.add.group();

        this.spawnPlayer();

        this.objectiveManager = new Game.ObjectiveManager(this.game, this.game.width - 50, this.game.height * 0.5);
        this.game.add.existing(this.objectiveManager);

        this.generateObjects();

        this.objectiveManager.createObjectives(this.map, this.map.objects['objectives'], this.p1);

        this.alienYellow = new Game.Enemy(this.game, this.p1.position.x - this.game.width, this.p1.position.y);
        this.alienYellow.controller.hostile = false;
        this.game.add.existing(this.alienYellow);
        this.entitiesGroup.add(this.alienYellow);

        var solskenspromenad = this.game.add.audio('solskenspromenad', 0.6, true, true);
        solskenspromenad.play();

        this.HUD = new Game.HUD(this.game);

        this.dialogueManager = new Game.DialogueManager(this.game, this.HUD);

        this.triggerManager = new Game.Trigger.TriggerManager(this.game);

        var dialogue = new Game.Dialogue(this.game, [
            {
                text: 'Use arrows keys to walk, and spacebar to jump'
            }, {
                text: 'And remember, have fun!',
                title: 'lplasödlasd'
            }
        ], 'TEST TU TRE');

        var trigger = new Game.Trigger.ZoneTrigger(
            this.game,
            true,
            new Phaser.Rectangle(this.p1.position.x - 200, this.p1.position.y - 50, 100, 100),
            this.p1,
            function(sender) {
                return this.activateKey.isDown;
            },
            undefined,
            this);
        this.triggerManager.addTrigger(trigger);

        trigger.onActive.add(function() {
            this.dialogueManager.setDialogue(dialogue);
        }, this);

        trigger.onInactive.add(function() {
            this.dialogueManager.hidden = true;
        }, this);

        this.f6 = this.game.input.keyboard.addKey(117);
        this.f6.onUp.add(function() {
            this.dialogueManager.nextSlide();
        }, this);

        this.game.world.bringToTop(this.objectiveManager);
    };

    Game.Level.prototype.update = function() {
        this.alienYellow.controller.update(this.p1);
        this.game.physics.arcade.collide(this.entitiesGroup, this.level);
    };

    Game.Level.prototype.render = function() {
        if (this.debugMode) {
            this.entitiesGroup.forEach(function(entity) {
                this.game.debug.body(entity);
            }, this);
        }
    };
})();<|endoftext|>


<commit_before>/*global console define require window*/
var registerPlugin;
require(['orion/plugin', 'orion/EventTarget', 'orion/textview/textModel',
		'orion-cm/mirrorTextModel', 'orion-cm/highlighter', 'orion-cm/globalCodeMirror',
		'cm/codemirror-compressed', 'requirejs/domReady!'],
	function(PluginProvider, EventTarget, mTextModel, mMirrorTextModel, mHighlighter, globalCodeMirror, _, document) {
		// Invert 1:1 map
		function invert(obj) {
			var result = {};
			for (var key in obj) {
				if (obj.hasOwnProperty(key)) {
					var arr = obj[key];
					if (arr instanceof Array) {
						for (var i=0; i < arr.length; i++) {
							var val = arr[i];
							result[val] = key;
						}
					} else {
						result[arr] = key;
					}
				}
			}
			return result;
		}

		var modes = "clike clojure coffeescript css diff ecl erlang gfm go groovy haskell haxe htmlembedded htmlmixed javascript jinja2 less lua markdown mysql ntriples ocaml pascal perl php pig plsql properties python r rpm rst ruby rust scheme shell smalltalk smarty sparql stex tiddlywiki tiki vb vbscript velocity verilog xml xquery yaml".split(" ");
		// Orion's content type IDs are MIME-like but don't match CodeMirror's exactly, so we map them.
		var mime2ContentType = {
			"application/xml": "application/xml", // orion
			"text/x-java": "text/x-java-source", // orion
			"text/javascript": "application/javascript", // orion
			"text/x-sh": "text/sh", // orion
			"text/x-properties": "text/conf" // orion
		};
		var contentType2Mime = invert(mime2ContentType);
		var mime2Ext = {
			"text/x-csrc": ["c", "C", "h"],
			"text/x-c++src": ["cc", "cpp", "c++"],
			"text/x-clojure": ["clj"],
			"text/x-coffeescript": ["coffee"],
			"text/x-csharp": ["cs"],
			"text/css": ["css"],
			"text/x-diff": ["diff", "patch"],
			"text/x-erlang": ["erlang"],
			"text/x-go": ["go"],
			"text/x-groovy": ["groovy"],
			"text/x-haskell": ["hs"],
			"text/html": ["html", "htm"],
			"text/x-java": ["java"],
			"text/javascript": ["js"],
			"application/json": ["json"],
			"jinja2": [],
			"text/x-lua": ["lua"],
			"text/x-markdown": ["md"],
			"text/n-triples": ["nt"],
			"text/x-ocaml": ["ocaml"],
			"text/x-pascal": ["pascal", "p"],
			"text/x-perl": ["pl"],
			"text/x-php": ["php", "php3", "php4", "php5"],
			"application/x-httpd-php": ["phtml"],
			"text/x-properties": ["properties", "ini"/*, "conf"*/],
			"text/x-python": ["py"],
			"text/x-rsrc": ["r"],
			"text/x-rst": ["rst"],
			"text/x-ruby": ["rb"],
			"text/x-rust": ["rs", "rc"],
			"text/x-scheme": ["scm", "ss"],
			"text/x-sh": ["sh"],
			"text/x-stsrc": ["sm"],
			"application/x-sparql-query": ["spk"],
			"text/x-plsql": ["sql"],
			"text/stex": [],
			"text/x-tiddlywiki": [],
			"text/x-vb": ["vb"],
			"text/vbscript": ["vbs"],
			"text/velocity": [],
	//		"text/xml": ["xml"],
			"application/xml": ["xml"],
			"text/x-yaml": ["yaml", "yml"]
		};

		function getMimeForContentTypeId(contentTypeId) {
			return contentType2Mime[contentTypeId] || contentTypeId;
		}
		function getContentTypeIdForMime(mime) {
			return mime2ContentType[mime];
		}

		function getMimes(modes) {
			return globalCodeMirror.listMIMEs().filter(
				function(mime) {
					var mname = globalCodeMirror._getModeName(mime);
					return modes.indexOf(mname) !== -1;
				});
		}
		// Create Orion content types for modes
		function getContentTypes(modes) {
			return getMimes(modes).map(function(mime) {
				return {
					id: getContentTypeIdForMime(mime) || mime,
					extension: mime2Ext[mime],
					"extends": "text/plain"
				};
			});
		}
		function createForm() {
			var list = document.getElementById("modelist");
			modes.forEach(function(mode) {
				var li = document.createElement("li");
				var label = document.createElement("div");
				var modeNode = document.createElement("a");
				modeNode.href = "http://codemirror.net/mode/" + mode + "/";
				modeNode.innerHTML = mode;
				label.appendChild(modeNode);
				li.appendChild(label);
				list.appendChild(li);
			});
		}

		function errback(e) {
			if (typeof console === "object" && console) {
				console.log("orion-codemirror: Couldn't install plugin: " + e);
			}
		}

		// Register plugin
		(function() {
			var modeSet = modes; // modeSet to install
			try {
				var model = new mMirrorTextModel.MirrorTextModel();
				var highlighter = new mHighlighter.Highlighter(model, globalCodeMirror);
				var contentTypes = getContentTypes(modeSet);

				var provider = new PluginProvider({
					name: "Orion CodeMirror syntax highlighting",
					version: "2.0",
					description: "Provides syntax highlighting for various languages. Powered by code from the CodeMirror project.",
					license: "Eclipse Distribution License",
					website: "https://github.com/mamacdon/orion-codemirror"
				});
				provider.registerService("orion.edit.model",
					{
						onModelChanging: function(modelChangingEvent) {
							model.onTargetModelChanging(modelChangingEvent);
						},
						onScroll: function(scrollEvent) {
							highlighter.setViewportIndex(scrollEvent.topIndex);
						}
					},
					{ types: ["ModelChanging", "Scroll"],
					  contentType: contentTypes
					});

				// Register editor associations for installed modes
				provider.registerService("orion.file.contenttype", {},
					{	contentTypes: contentTypes
					});
				provider.registerService("orion.navigate.openWith", {},
					{	editor: "orion.editor",
						contentType: contentTypes.map(function(ct) { return ct.id; })
					});

				var highlighterServiceImpl = {
					setContentType: function(contentType) {
						var mime = getMimeForContentTypeId(contentType.id);
						if (mime) {
							highlighter.setMode(mime);
						} else {
							console.log("Missing MIME in content type " + contentType.id);
						}
					}
				};
				// Turn the service impl into an event emitter
				EventTarget.attach(highlighterServiceImpl);
				provider.registerService("orion.edit.highlighter",
					highlighterServiceImpl,
					{ type: "highlighter",
					  contentType: contentTypes
					});
				highlighter.addEventListener("StyleReady", function(styleReadyEvent) {
					styleReadyEvent.type = "orion.edit.highlighter.styleReady";
					highlighterServiceImpl.dispatchEvent(styleReadyEvent);
				});

				provider.connect(function(e){
	//				console.log("orion-codemirror: connected. Supported modes: [" + modeSet.join(",") + "]");
				}, errback);
			} catch (e) {
				errback(e);
			}

			createForm();
			document.getElementById("url").value =  window.location.href;
		}());
});<commit_msg>Bump plugin version to 4.0<commit_after>/*global console define require window*/
var registerPlugin;
require(['orion/plugin', 'orion/EventTarget', 'orion/textview/textModel',
		'orion-cm/mirrorTextModel', 'orion-cm/highlighter', 'orion-cm/globalCodeMirror',
		'cm/codemirror-compressed', 'requirejs/domReady!'],
	function(PluginProvider, EventTarget, mTextModel, mMirrorTextModel, mHighlighter, globalCodeMirror, _, document) {
		// Invert 1:1 map
		function invert(obj) {
			var result = {};
			for (var key in obj) {
				if (obj.hasOwnProperty(key)) {
					var arr = obj[key];
					if (arr instanceof Array) {
						for (var i=0; i < arr.length; i++) {
							var val = arr[i];
							result[val] = key;
						}
					} else {
						result[arr] = key;
					}
				}
			}
			return result;
		}

		var modes = "clike clojure coffeescript css diff ecl erlang gfm go groovy haskell haxe htmlembedded htmlmixed javascript jinja2 less lua markdown mysql ntriples ocaml pascal perl php pig plsql properties python r rpm rst ruby rust scheme shell smalltalk smarty sparql stex tiddlywiki tiki vb vbscript velocity verilog xml xquery yaml".split(" ");
		// Orion's content type IDs are MIME-like but don't match CodeMirror's exactly, so we map them.
		var mime2ContentType = {
			"application/xml": "application/xml", // orion
			"text/x-java": "text/x-java-source", // orion
			"text/javascript": "application/javascript", // orion
			"text/x-sh": "text/sh", // orion
			"text/x-properties": "text/conf" // orion
		};
		var contentType2Mime = invert(mime2ContentType);
		var mime2Ext = {
			"text/x-csrc": ["c", "C", "h"],
			"text/x-c++src": ["cc", "cpp", "c++"],
			"text/x-clojure": ["clj"],
			"text/x-coffeescript": ["coffee"],
			"text/x-csharp": ["cs"],
			"text/css": ["css"],
			"text/x-diff": ["diff", "patch"],
			"text/x-erlang": ["erlang"],
			"text/x-go": ["go"],
			"text/x-groovy": ["groovy"],
			"text/x-haskell": ["hs"],
			"text/html": ["html", "htm"],
			"text/x-java": ["java"],
			"text/javascript": ["js"],
			"application/json": ["json"],
			"jinja2": [],
			"text/x-lua": ["lua"],
			"text/x-markdown": ["md"],
			"text/n-triples": ["nt"],
			"text/x-ocaml": ["ocaml"],
			"text/x-pascal": ["pascal", "p"],
			"text/x-perl": ["pl"],
			"text/x-php": ["php", "php3", "php4", "php5"],
			"application/x-httpd-php": ["phtml"],
			"text/x-properties": ["properties", "ini"/*, "conf"*/],
			"text/x-python": ["py"],
			"text/x-rsrc": ["r"],
			"text/x-rst": ["rst"],
			"text/x-ruby": ["rb"],
			"text/x-rust": ["rs", "rc"],
			"text/x-scheme": ["scm", "ss"],
			"text/x-sh": ["sh"],
			"text/x-stsrc": ["sm"],
			"application/x-sparql-query": ["spk"],
			"text/x-plsql": ["sql"],
			"text/stex": [],
			"text/x-tiddlywiki": [],
			"text/x-vb": ["vb"],
			"text/vbscript": ["vbs"],
			"text/velocity": [],
	//		"text/xml": ["xml"],
			"application/xml": ["xml"],
			"text/x-yaml": ["yaml", "yml"]
		};

		function getMimeForContentTypeId(contentTypeId) {
			return contentType2Mime[contentTypeId] || contentTypeId;
		}
		function getContentTypeIdForMime(mime) {
			return mime2ContentType[mime];
		}

		function getMimes(modes) {
			return globalCodeMirror.listMIMEs().filter(
				function(mime) {
					var mname = globalCodeMirror._getModeName(mime);
					return modes.indexOf(mname) !== -1;
				});
		}
		// Create Orion content types for modes
		function getContentTypes(modes) {
			return getMimes(modes).map(function(mime) {
				return {
					id: getContentTypeIdForMime(mime) || mime,
					extension: mime2Ext[mime],
					"extends": "text/plain"
				};
			});
		}
		function createForm() {
			var list = document.getElementById("modelist");
			modes.forEach(function(mode) {
				var li = document.createElement("li");
				var label = document.createElement("div");
				var modeNode = document.createElement("a");
				modeNode.href = "http://codemirror.net/mode/" + mode + "/";
				modeNode.innerHTML = mode;
				label.appendChild(modeNode);
				li.appendChild(label);
				list.appendChild(li);
			});
		}

		function errback(e) {
			if (typeof console === "object" && console) {
				console.log("orion-codemirror: Couldn't install plugin: " + e);
			}
		}

		// Register plugin
		(function() {
			var modeSet = modes; // modeSet to install
			try {
				var model = new mMirrorTextModel.MirrorTextModel();
				var highlighter = new mHighlighter.Highlighter(model, globalCodeMirror);
				var contentTypes = getContentTypes(modeSet);

				var provider = new PluginProvider({
					name: "Orion CodeMirror syntax highlighting",
					version: "4.0",
					description: "Provides syntax highlighting for various languages. Powered by code from the CodeMirror project.",
					license: "Eclipse Distribution License",
					website: "https://github.com/mamacdon/orion-codemirror"
				});
				provider.registerService("orion.edit.model",
					{
						onModelChanging: function(modelChangingEvent) {
							model.onTargetModelChanging(modelChangingEvent);
						},
						onScroll: function(scrollEvent) {
							highlighter.setViewportIndex(scrollEvent.topIndex);
						}
					},
					{ types: ["ModelChanging", "Scroll"],
					  contentType: contentTypes
					});

				// Register editor associations for installed modes
				provider.registerService("orion.file.contenttype", {},
					{	contentTypes: contentTypes
					});
				provider.registerService("orion.navigate.openWith", {},
					{	editor: "orion.editor",
						contentType: contentTypes.map(function(ct) { return ct.id; })
					});

				var highlighterServiceImpl = {
					setContentType: function(contentType) {
						var mime = getMimeForContentTypeId(contentType.id);
						if (mime) {
							highlighter.setMode(mime);
						} else {
							console.log("Missing MIME in content type " + contentType.id);
						}
					}
				};
				// Turn the service impl into an event emitter
				EventTarget.attach(highlighterServiceImpl);
				provider.registerService("orion.edit.highlighter",
					highlighterServiceImpl,
					{ type: "highlighter",
					  contentType: contentTypes
					});
				highlighter.addEventListener("StyleReady", function(styleReadyEvent) {
					styleReadyEvent.type = "orion.edit.highlighter.styleReady";
					highlighterServiceImpl.dispatchEvent(styleReadyEvent);
				});

				provider.connect(function(e){
	//				console.log("orion-codemirror: connected. Supported modes: [" + modeSet.join(",") + "]");
				}, errback);
			} catch (e) {
				errback(e);
			}

			createForm();
			document.getElementById("url").value =  window.location.href;
		}());
});<|endoftext|>


<commit_before>import classNames from 'classnames/dedupe';
import React from 'react';
import ReactDOM from 'react-dom';

import Util from '../utils/Util';

const METHODS_TO_BIND = ['onImageError'];

class Image extends React.Component {
  constructor() {
    super(...arguments);

    this.state = {
      imageErrorCount: 0
    };

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  componentWillReceiveProps(nextProps) {
    // Try again if new urls were provided
    let image = ReactDOM.findDOMNode(this);
    image.src = nextProps.src;

    this.setState({imageErrorCount: 0});
  }

  onImageError(event) {
    let {props: {fallbackSrc}, state: {imageErrorCount}} = this;

    if (imageErrorCount === 0) {
      event.target.src = fallbackSrc;
    }

    // Both src and fallback failed
    this.setState({imageErrorCount: imageErrorCount + 1});
  }

  render() {
    let {props, state: {imageErrorCount}} = this;
    let classes = classNames(
      {'hidden': imageErrorCount > 1},
      props.className
    );

    return (
      <img
        className={classes}
        onError={this.onImageError}
        {...Util.omit(props, ['className'])} />
    );
  }
}

Image.propTypes = {
  src: React.PropTypes.string,
  fallbackSrc: React.PropTypes.string,

  // Classes
  className: React.PropTypes.oneOfType([
    React.PropTypes.array,
    React.PropTypes.object,
    React.PropTypes.string
  ])
};

module.exports = Image;
<commit_msg>Only updating if new src or fallbackSrc is provided<commit_after>import classNames from 'classnames/dedupe';
import React from 'react';
import ReactDOM from 'react-dom';

import Util from '../utils/Util';

const METHODS_TO_BIND = ['onImageError'];

class Image extends React.Component {
  constructor() {
    super(...arguments);

    this.state = {
      imageErrorCount: 0
    };

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  componentWillReceiveProps(nextProps) {
    let {src, fallbackSrc} = this.props;
    let newSrc;
    if (src !== nextProps.src) {
      newSrc = nextProps.src;
    }

    if (src === nextProps.src && fallbackSrc !== nextProps.fallbackSrc) {
      newSrc = nextProps.fallbackSrc;
    }

    // Try again if a new url was provided
    if (newSrc) {
      let image = ReactDOM.findDOMNode(this);
      image.src = newSrc;
      this.setState({imageErrorCount: 0});
    }
  }

  onImageError(event) {
    let {props: {fallbackSrc}, state: {imageErrorCount}} = this;

    if (imageErrorCount === 0) {
      event.target.src = fallbackSrc;
    }

    // Both src and fallback failed
    this.setState({imageErrorCount: imageErrorCount + 1});
  }

  render() {
    let {props, state: {imageErrorCount}} = this;
    let classes = classNames(
      {'hidden': imageErrorCount > 1},
      props.className
    );

    return (
      <img
        className={classes}
        onError={this.onImageError}
        {...Util.omit(props, ['className'])} />
    );
  }
}

Image.propTypes = {
  src: React.PropTypes.string,
  fallbackSrc: React.PropTypes.string,

  // Classes
  className: React.PropTypes.oneOfType([
    React.PropTypes.array,
    React.PropTypes.object,
    React.PropTypes.string
  ])
};

module.exports = Image;
<|endoftext|>