<commit_before>
audio_engine={};

var BeatAnalyser=function()
{
  // guessed beat to lock upon
  this.lock_beat=2.2;

  // analyzer outputs
  this.pulse=0;

  // state variables
  this.sawtooth=0
  this.frequency=this.lock_beat;
  this.phase=0;

  this.analyse=function(pulse_amplitude,beat_frequency,amplitude,phase,offset)
  {
    if(beat_frequency!=this.lock_beat)
      this.frequency=this.lock_beat=beat_frequency;

    return pulse_amplitude * this.pulse + amplitude * (Math.sin(this.sawtooth*2.0*Math.PI+phase)+1.0)/2.0  + offset;
  }

  this.update=function(pulse,dt)
  {
    this.sawtooth+=this.frequency*dt;
    this.sawtooth=this.sawtooth % 1.0;

    var sine=Math.sin((this.sawtooth+this.phase)*2*Math.PI);

    // proportinally control energy (balances energy pulse around zero crossing)
    var k = 0.000125 * 256 *  pulse * sine;
    this.frequency +=  k ;
    this.phase += k*0.5;

    // stabilize around proposed beat
    this.frequency-=0.0001*(this.frequency-this.lock_beat);

    // console.log("f "+frequency+" s "+sine+" p "+phase+ " "+spectrogram.length);

    this.pulse=pulse;
  }
}

var beatAnalysers=[];

// helper function for retrieving beat values. creates analysers on demand.
audio_engine.beatValue=function()
{

  // TODO prevent leaking, how to remove dumped analysers?
  // We only may know they aren't used to analyse for some time..
  // maybe push on .analyse(), remove after 1s of .update
  //
  // so for now, only ONE analyser!
  if(!beatAnalysers.length)
    beatAnalysers.push(new BeatAnalyser());

  return beatAnalysers[0].analyse.apply(beatAnalysers[0],arguments);
}

audio_engine.spectrogram=false;
audio_engine.waveform=false;

function initAudioAnalysers(stream)
{
    // show audio histogram for debug purpose, if canvas exists
    var canvas,audio_canvas_ctx;
    if(canvas=document.getElementById('audiocanvas'))
    {
      audio_canvas_ctx = canvas.getContext("2d");
      audio_canvas_ctx.fillStyle='#fff';
    }

    // create the audio context (chrome only for now)
    if (!window.AudioContext)
      window.AudioContext = window.webkitAudioContext;
    var context = new AudioContext();

    var samples=1024;

    var scriptNode = context.createScriptProcessor(samples, 1, 1);
    scriptNode.connect(context.destination);

    var analyser = context.createAnalyser();
    analyser.smoothingTimeConstant = 0.0;
    analyser.fftSize = 1024;
    analyser.connect(scriptNode);

    var source = context.createMediaStreamSource(stream);
    source.connect(analyser);

    // workaround for Webkit bug gc'ing the audio nodes if not referenced from JS side
    // audio processing stops then.
    // see http://code.google.com/p/chromium/issues/detail?id=82795
    window.audioReferencesFix=[scriptNode,analyser,source,context];

    // store time domain waveform
    var waveform    =  new Uint8Array  (analyser.fftSize);
    // store spectrogram and it's gliding means
    var spectrogram =  new Uint8Array  (analyser.frequencyBinCount);
    var means       =  new Float32Array(analyser.frequencyBinCount);

    scriptNode.onaudioprocess = function()
    {
        analyser.getByteTimeDomainData(waveform);
        analyser.getByteFrequencyData(spectrogram);

        // clear the current state
        if(audio_canvas_ctx)
          audio_canvas_ctx.clearRect(0, 0, 640, 256);

        var pulse=0;

        // add up current pulse energy
        for ( var i = 0; i < spectrogram.length; i++ )
        {

          // calculate gliding means
          var a=0.9;
          means[i]=means[i]*a+spectrogram[i]*(1.-a);

          var value = spectrogram[i]-means[i];

          // debug draw
          if(audio_canvas_ctx)
          {
            audio_canvas_ctx.fillStyle='#0f0';
            audio_canvas_ctx.fillRect(i*5,255-means[i],3,255);
            audio_canvas_ctx.fillStyle='#fff';
            audio_canvas_ctx.fillRect(i*5,255-spectrogram[i],3,2);
          }
          var attenuation=(spectrogram.length-i)/spectrogram.length;
          attenuation*=attenuation;
          pulse+=Math.max(0,value*attenuation);
        }
        pulse/=spectrogram.length;
        pulse/=256.;

        // refresh all beat analysers
        var dt=samples/context.sampleRate;
        for(var i=0; i<beatAnalysers.length; i++)
          beatAnalysers[i].update(pulse,dt);
    }
    audio_engine.waveform   =waveform;
    audio_engine.spectrogram=spectrogram;
}

/*
var initAudio=function()
{
  var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.oGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  getUserMedia.call(navigator, {video: false, audio: true}, function(stream){
    initAudioAnalysers(stream);
  }, function(err){
    console.log('no audio capture');
  });
}

initAudio();
*/
<commit_msg>reduced audio buffer (latency)<commit_after>
audio_engine={};

var BeatAnalyser=function()
{
  // guessed beat to lock upon
  this.lock_beat=2.2;

  // analyzer outputs
  this.pulse=0;

  // state variables
  this.sawtooth=0
  this.frequency=this.lock_beat;
  this.phase=0;

  this.analyse=function(pulse_amplitude,beat_frequency,amplitude,phase,offset)
  {
    if(beat_frequency!=this.lock_beat)
      this.frequency=this.lock_beat=beat_frequency;

    return pulse_amplitude * this.pulse + amplitude * (Math.sin(this.sawtooth*2.0*Math.PI+phase)+1.0)/2.0  + offset;
  }

  this.update=function(pulse,dt)
  {
    this.sawtooth+=this.frequency*dt;
    this.sawtooth=this.sawtooth % 1.0;

    var sine=Math.sin((this.sawtooth+this.phase)*2*Math.PI);

    // proportinally control energy (balances energy pulse around zero crossing)
    var k = 0.000125 * 256 *  pulse * sine;
    this.frequency +=  k ;
    this.phase += k*0.5;

    // stabilize around proposed beat
    this.frequency-=0.0001*(this.frequency-this.lock_beat);

    // console.log("f "+frequency+" s "+sine+" p "+phase+ " "+spectrogram.length);

    this.pulse=pulse;
  }
}

var beatAnalysers=[];

// helper function for retrieving beat values. creates analysers on demand.
audio_engine.beatValue=function()
{

  // TODO prevent leaking, how to remove dumped analysers?
  // We only may know they aren't used to analyse for some time..
  // maybe push on .analyse(), remove after 1s of .update
  //
  // so for now, only ONE analyser!
  if(!beatAnalysers.length)
    beatAnalysers.push(new BeatAnalyser());

  return beatAnalysers[0].analyse.apply(beatAnalysers[0],arguments);
}

audio_engine.spectrogram=false;
audio_engine.waveform=false;

function initAudioAnalysers(stream)
{
    // show audio histogram for debug purpose, if canvas exists
    var canvas,audio_canvas_ctx;
    if(canvas=document.getElementById('audiocanvas'))
    {
      audio_canvas_ctx = canvas.getContext("2d");
      audio_canvas_ctx.fillStyle='#fff';
    }

    // create the audio context (chrome only for now)
    if (!window.AudioContext)
      window.AudioContext = window.webkitAudioContext;
    var context = new AudioContext();

    var samples=512;

    var scriptNode = context.createScriptProcessor(samples, 1, 1);
    scriptNode.connect(context.destination);

    var analyser = context.createAnalyser();
    analyser.smoothingTimeConstant = 0.0;
    analyser.fftSize = samples;
    analyser.connect(scriptNode);

    var source = context.createMediaStreamSource(stream);
    source.connect(analyser);

    // workaround for Webkit bug gc'ing the audio nodes if not referenced from JS side
    // audio processing stops then.
    // see http://code.google.com/p/chromium/issues/detail?id=82795
    window.audioReferencesFix=[scriptNode,analyser,source,context];

    // store time domain waveform
    var waveform    =  new Uint8Array  (analyser.fftSize);
    // store spectrogram and it's gliding means
    var spectrogram =  new Uint8Array  (analyser.frequencyBinCount);
    var means       =  new Float32Array(analyser.frequencyBinCount);

    scriptNode.onaudioprocess = function()
    {
        analyser.getByteTimeDomainData(waveform);
        analyser.getByteFrequencyData(spectrogram);

        // clear the current state
        if(audio_canvas_ctx)
          audio_canvas_ctx.clearRect(0, 0, 640, 256);

        var pulse=0;

        // add up current pulse energy
        for ( var i = 0; i < spectrogram.length; i++ )
        {

          // calculate gliding means
          var a=0.9;
          means[i]=means[i]*a+spectrogram[i]*(1.-a);

          var value = spectrogram[i]-means[i];

          // debug draw
          if(audio_canvas_ctx)
          {
            audio_canvas_ctx.fillStyle='#0f0';
            audio_canvas_ctx.fillRect(i*5,255-means[i],3,255);
            audio_canvas_ctx.fillStyle='#fff';
            audio_canvas_ctx.fillRect(i*5,255-spectrogram[i],3,2);
          }
          var attenuation=(spectrogram.length-i)/spectrogram.length;
          attenuation*=attenuation;
          pulse+=Math.max(0,value*attenuation);
        }
        pulse/=spectrogram.length;
        pulse/=256.;

        // refresh all beat analysers
        var dt=samples/context.sampleRate;
        for(var i=0; i<beatAnalysers.length; i++)
          beatAnalysers[i].update(pulse,dt);
    }
    audio_engine.waveform   =waveform;
    audio_engine.spectrogram=spectrogram;
}

/*
var initAudio=function()
{
  var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.oGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  getUserMedia.call(navigator, {video: false, audio: true}, function(stream){
    initAudioAnalysers(stream);
  }, function(err){
    console.log('no audio capture');
  });
}

initAudio();
*/
<|endoftext|>


<commit_before>namespace('Sy.Kernel');

/**
 * Class used to inspect app object tree and extract meta informations
 *
 * @package Sy
 * @subpackage Kernel
 * @class
 */

Sy.Kernel.AppParser = function () {
    this.bundles = [];
    this.controllers = [];
    this.entities = [];
    this.logger = null;
};
Sy.Kernel.AppParser.prototype = Object.create(Object.prototype, {

    /**
     * Set the logger
     *
     * @param {Sy.Lib.Logger.Interface} logger
     *
     * @return {Sy.Kernle.AppParser}
     */

    setLogger: {
        value: function (logger) {
            this.logger = logger;

            return this;
        }
    },

    /**
     * Return the list of defined bundles
     *
     * @return {Array}
     */

    getBundles: {
        value: function () {

            if (this.bundles.length > 0 || !objectGetter('App.Bundle')) {
                return this.bundles;
            }

            for (var bundle in App.Bundle) {
                if (App.Bundle.hasOwnProperty(bundle)) {
                    this.bundles.push(bundle);
                    this.logger && this.logger.debug('Bundle found', bundle);
                }
            }

            return this.bundles;

        }
    },

    /**
     * Return an object with a correspondance controller alias => controller constructor
     *
     * @return {Object}
     */

    getControllers: {
        value: function () {

            if (this.controllers.length > 0) {
                return this.controllers;
            }

            var bundleCtrl;

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleCtrl = App.Bundle[this.bundles[i]].Controller;

                if (!bundleCtrl) {
                    this.logger && this.logger.debug('No controller found in', this.bundles[i]);
                    continue;
                }

                for (var ctrl in bundleCtrl) {
                    if (bundleCtrl.hasOwnProperty(ctrl)) {
                        this.controllers.push({
                            name: this.bundles[i] + '::' + ctrl,
                            creator: bundleCtrl[ctrl]
                        });
                        this.logger && this.logger.debug('Controller found', this.bundles[i] + '::' + ctrl);
                    }
                }
            }

            return this.controllers;

        }
    },

    /**
     * Return the array of all defined entities
     *
     * @return {Array}
     */

    getEntities: {
        value: function () {

            if (this.entities.length > 0) {
                return this.entities;
            }

            var bundleEntities,
                bundleRepositories,
                alias,
                entity;

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleEntities = App.Bundle[this.bundles[i]].Entity;
                bundleRepositories = App.Bundle[this.bundles[i]].Repository || {};

                if (!bundleEntities) {
                    this.logger && this.logger.debug('No entity found in', this.bundles[i]);
                    continue;
                }

                for (var name in bundleEntities) {
                    if (bundleEntities.hasOwnProperty(name)) {
                        alias = this.bundles[i] + '::' + name;
                        entity = bundleEntities[name];

                        this.entities.push({
                            name: alias,
                            repository: bundleRepositories[name] || Sy.Storage.Repository,
                            entity: entity,
                            indexes: (new entity()).indexes,
                            uuid: entity.prototype.UUID
                        });

                        this.logger && this.logger.debug('Entity found ' + alias + (
                            bundleRepositories[name] ?
                                ' with custom repository' :
                                ''
                        ));
                    }
                }
            }

            return this.entities;

        }
    },

    /**
     * Walk through the app services definitions object
     * and call them to register them
     *
     * @param {Sy.ServiceContainer.Core} $container
     *
     * @return {Sy.Kernel.AppParser}
     */

    buildServices: {
        value: function (container) {

            if (!(container instanceof Sy.ServiceContainer.Core)) {
                throw new TypeError('Invalid service container');
            }

            var bundleConfig;

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleConfig = App.Bundle[this.bundles[i]].Config;

                if (!bundleConfig || !bundleConfig.Service) {
                    continue;
                }

                bundleConfig = new bundleConfig.Service();
                bundleConfig.define(container);

                this.logger && this.logger.debug('Services loaded from ' + this.bundles[i] + ' bundle');
            }

            return this;

        }
    },

    /**
     * Walk through the app config definitions object
     * and call them to register them
     *
     * @param {Sy.ConfiguratorInterface} $config
     *
     * @return {Sy.Kernel.AppParser}
     */

    buildConfig: {
        value: function (config) {

            if (!(config instanceof Sy.ConfiguratorInterface)) {
                throw new TypeError('Invalid configurator');
            }

            var bundleConfig;

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleConfig = App.Bundle[this.bundles[i]].Config;

                if (!bundleConfig || !bundleConfig.Configuration) {
                    continue;
                }

                bundleConfig = new bundleConfig.Configuration();
                bundleConfig.define(config);

                this.logger && this.logger.debug('Configuration loaded from ' + this.bundles[i] + ' bundle');
            }

            return this;

        }
    },

    /**
     * Walk through the app validation rules definitions object
     * and call them to register them in the validator
     *
     * @param {Sy.ServiceContainer.Core} container
     *
     * @return {Sy.Kernel.AppParser}
     */

    registerValidationRules: {
        value: function (container) {
            if (!(container instanceof Sy.ServiceContainer.Core)) {
                throw new TypeError('Invalid service container');
            }

            var validator = container.get('sy::core::validator'),
                bundleConfig;

            if (!(validator instanceof Sy.Validator.Core)) {
                throw new TypeError('Invalid validator');
            }

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleConfig = App.Bundle[this.bundles[i]].Config;

                if (!bundleConfig || !bundleConfig.Validation) {
                    continue;
                }

                bundleConfig = new bundleConfig.Validation();
                bundleConfig.define(validator);

                this.logger && this.logger.debug('Validation rules loaded from ' + this.bundles[i] + ' bundle');
            }

            return this;
        }
    }

});
<commit_msg>added the bundle name and entity name to the entities metadata<commit_after>namespace('Sy.Kernel');

/**
 * Class used to inspect app object tree and extract meta informations
 *
 * @package Sy
 * @subpackage Kernel
 * @class
 */

Sy.Kernel.AppParser = function () {
    this.bundles = [];
    this.controllers = [];
    this.entities = [];
    this.logger = null;
};
Sy.Kernel.AppParser.prototype = Object.create(Object.prototype, {

    /**
     * Set the logger
     *
     * @param {Sy.Lib.Logger.Interface} logger
     *
     * @return {Sy.Kernle.AppParser}
     */

    setLogger: {
        value: function (logger) {
            this.logger = logger;

            return this;
        }
    },

    /**
     * Return the list of defined bundles
     *
     * @return {Array}
     */

    getBundles: {
        value: function () {

            if (this.bundles.length > 0 || !objectGetter('App.Bundle')) {
                return this.bundles;
            }

            for (var bundle in App.Bundle) {
                if (App.Bundle.hasOwnProperty(bundle)) {
                    this.bundles.push(bundle);
                    this.logger && this.logger.debug('Bundle found', bundle);
                }
            }

            return this.bundles;

        }
    },

    /**
     * Return an object with a correspondance controller alias => controller constructor
     *
     * @return {Object}
     */

    getControllers: {
        value: function () {

            if (this.controllers.length > 0) {
                return this.controllers;
            }

            var bundleCtrl;

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleCtrl = App.Bundle[this.bundles[i]].Controller;

                if (!bundleCtrl) {
                    this.logger && this.logger.debug('No controller found in', this.bundles[i]);
                    continue;
                }

                for (var ctrl in bundleCtrl) {
                    if (bundleCtrl.hasOwnProperty(ctrl)) {
                        this.controllers.push({
                            name: this.bundles[i] + '::' + ctrl,
                            creator: bundleCtrl[ctrl]
                        });
                        this.logger && this.logger.debug('Controller found', this.bundles[i] + '::' + ctrl);
                    }
                }
            }

            return this.controllers;

        }
    },

    /**
     * Return the array of all defined entities
     *
     * @return {Array}
     */

    getEntities: {
        value: function () {

            if (this.entities.length > 0) {
                return this.entities;
            }

            var bundleEntities,
                bundleRepositories,
                alias,
                entity;

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleEntities = App.Bundle[this.bundles[i]].Entity;
                bundleRepositories = App.Bundle[this.bundles[i]].Repository || {};

                if (!bundleEntities) {
                    this.logger && this.logger.debug('No entity found in', this.bundles[i]);
                    continue;
                }

                for (var name in bundleEntities) {
                    if (bundleEntities.hasOwnProperty(name)) {
                        alias = this.bundles[i] + '::' + name;
                        entity = bundleEntities[name];

                        this.entities.push({
                            alias: alias,
                            bundle: this.bundles[i],
                            name: name,
                            repository: bundleRepositories[name] || Sy.Storage.Repository,
                            entity: entity,
                            indexes: (new entity()).indexes,
                            uuid: entity.prototype.UUID
                        });

                        this.logger && this.logger.debug('Entity found ' + alias + (
                            bundleRepositories[name] ?
                                ' with custom repository' :
                                ''
                        ));
                    }
                }
            }

            return this.entities;

        }
    },

    /**
     * Walk through the app services definitions object
     * and call them to register them
     *
     * @param {Sy.ServiceContainer.Core} $container
     *
     * @return {Sy.Kernel.AppParser}
     */

    buildServices: {
        value: function (container) {

            if (!(container instanceof Sy.ServiceContainer.Core)) {
                throw new TypeError('Invalid service container');
            }

            var bundleConfig;

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleConfig = App.Bundle[this.bundles[i]].Config;

                if (!bundleConfig || !bundleConfig.Service) {
                    continue;
                }

                bundleConfig = new bundleConfig.Service();
                bundleConfig.define(container);

                this.logger && this.logger.debug('Services loaded from ' + this.bundles[i] + ' bundle');
            }

            return this;

        }
    },

    /**
     * Walk through the app config definitions object
     * and call them to register them
     *
     * @param {Sy.ConfiguratorInterface} $config
     *
     * @return {Sy.Kernel.AppParser}
     */

    buildConfig: {
        value: function (config) {

            if (!(config instanceof Sy.ConfiguratorInterface)) {
                throw new TypeError('Invalid configurator');
            }

            var bundleConfig;

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleConfig = App.Bundle[this.bundles[i]].Config;

                if (!bundleConfig || !bundleConfig.Configuration) {
                    continue;
                }

                bundleConfig = new bundleConfig.Configuration();
                bundleConfig.define(config);

                this.logger && this.logger.debug('Configuration loaded from ' + this.bundles[i] + ' bundle');
            }

            return this;

        }
    },

    /**
     * Walk through the app validation rules definitions object
     * and call them to register them in the validator
     *
     * @param {Sy.ServiceContainer.Core} container
     *
     * @return {Sy.Kernel.AppParser}
     */

    registerValidationRules: {
        value: function (container) {
            if (!(container instanceof Sy.ServiceContainer.Core)) {
                throw new TypeError('Invalid service container');
            }

            var validator = container.get('sy::core::validator'),
                bundleConfig;

            if (!(validator instanceof Sy.Validator.Core)) {
                throw new TypeError('Invalid validator');
            }

            for (var i = 0, l = this.bundles.length; i < l; i++) {
                bundleConfig = App.Bundle[this.bundles[i]].Config;

                if (!bundleConfig || !bundleConfig.Validation) {
                    continue;
                }

                bundleConfig = new bundleConfig.Validation();
                bundleConfig.define(validator);

                this.logger && this.logger.debug('Validation rules loaded from ' + this.bundles[i] + ' bundle');
            }

            return this;
        }
    }

});
<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');
var DataviewModelBase = require('./dataview-model-base');

module.exports = DataviewModelBase.extend({

  defaults: _.extend(
    {
      type: 'histogram',
      bins: 10
    },
    DataviewModelBase.prototype.defaults
  ),

  url: function () {
    var params = [];

    if (this.get('column_type')) {
      params.push('column_type=' + this.get('column_type'));
    }
    if (_.isNumber(this.get('own_filter'))) {
      params.push('own_filter=' + this.get('own_filter'));
    } else {
      if (_.isNumber(this.get('start'))) {
        params.push('start=' + this.get('start'));
      }
      if (_.isNumber(this.get('end'))) {
        params.push('end=' + this.get('end'));
      }
      if (_.isNumber(this.get('bins'))) {
        params.push('bins=' + this.get('bins'));
      }
    }
    if (this.get('boundingBox') && this.get('submitBBox')) {
      params.push('bbox=' + this.get('boundingBox'));
    }

    var url = this.get('url');
    if (params.length > 0) {
      url += '?' + params.join('&');
    }
    return url;
  },

  initialize: function (attrs, opts) {
    DataviewModelBase.prototype.initialize.apply(this, arguments);
    this._data = new Backbone.Collection(this.get('data'));

    // BBox should only be included until after the first fetch, since we want to get the range of the full dataset
    this.once('change:data', function () {
      this.set('submitBBox', true);

      var data = this.getData();
      if (data && data.length > 0) {
        this.set({
          start: data[0].start,
          end: data[data.length - 1].end,
          bins: data.length
        }, { silent: true });
      }
    }, this);
    this.listenTo(this.layer, 'change:meta', this._onChangeLayerMeta);
    this.on('change:column', this._reloadMap, this);
    this.on('change:bins change:start change:end', this._refreshAndResetFilter, this);
  },

  enableFilter: function () {
    this.set('own_filter', 1);
  },

  disableFilter: function () {
    this.unset('own_filter');
  },

  getData: function () {
    return this._data.toJSON();
  },

  getSize: function () {
    return this._data.size();
  },

  parse: function (data) {
    var numberOfBins = data.bins_count;
    var width = data.bin_width;
    var start = data.bins_start;

    var buckets = new Array(numberOfBins);

    _.each(data.bins, function (b) {
      buckets[b.bin] = b;
    });

    for (var i = 0; i < numberOfBins; i++) {
      buckets[i] = _.extend({
        bin: i,
        start: start + (i * width),
        end: start + ((i + 1) * width),
        freq: 0
      }, buckets[i]);
    }

    // FIXME - Update the end of last bin due https://github.com/CartoDB/cartodb.js/issues/926
    var lastBucket = buckets[numberOfBins - 1];
    if (lastBucket && lastBucket.end < lastBucket.max) {
      lastBucket.end = lastBucket.max;
    }

    this._data.reset(buckets);

    return {
      data: buckets,
      nulls: data.nulls
    };
  },

  toJSON: function (d) {
    return {
      type: 'histogram',
      options: {
        column: this.get('column'),
        bins: this.get('bins')
      }
    };
  },

  _onChangeLayerMeta: function () {
    this.filter.set('column_type', this.layer.get('meta').column_type);
  },

  _onChangeBinds: function () {
    DataviewModelBase.prototype._onChangeBinds.call(this);
    this.bind('change:histogram_sizes', function (mdl, isSizesApplied, d) {
      if (isSizesApplied) {
        this.trigger('histogram_sizes', this);
      }
    }, this);
  },

  _refreshAndResetFilter: function () {
    this.refresh();
    this.disableFilter();
    this.filter.unsetRange();
  }
},

  // Class props
  {
    ATTRS_NAMES: DataviewModelBase.ATTRS_NAMES.concat([
      'column',
      'column_type',
      'bins',
      'start',
      'end'
    ])
  }
);
<commit_msg>Use fetch instead of refresh method<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var DataviewModelBase = require('./dataview-model-base');

module.exports = DataviewModelBase.extend({

  defaults: _.extend(
    {
      type: 'histogram',
      bins: 10
    },
    DataviewModelBase.prototype.defaults
  ),

  url: function () {
    var params = [];

    if (this.get('column_type')) {
      params.push('column_type=' + this.get('column_type'));
    }
    if (_.isNumber(this.get('own_filter'))) {
      params.push('own_filter=' + this.get('own_filter'));
    } else {
      if (_.isNumber(this.get('start'))) {
        params.push('start=' + this.get('start'));
      }
      if (_.isNumber(this.get('end'))) {
        params.push('end=' + this.get('end'));
      }
      if (_.isNumber(this.get('bins'))) {
        params.push('bins=' + this.get('bins'));
      }
    }
    if (this.get('boundingBox') && this.get('submitBBox')) {
      params.push('bbox=' + this.get('boundingBox'));
    }

    var url = this.get('url');
    if (params.length > 0) {
      url += '?' + params.join('&');
    }
    return url;
  },

  initialize: function (attrs, opts) {
    DataviewModelBase.prototype.initialize.apply(this, arguments);
    this._data = new Backbone.Collection(this.get('data'));

    // BBox should only be included until after the first fetch, since we want to get the range of the full dataset
    this.once('change:data', function () {
      this.set('submitBBox', true);

      var data = this.getData();
      if (data && data.length > 0) {
        this.set({
          start: data[0].start,
          end: data[data.length - 1].end,
          bins: data.length
        }, { silent: true });
      }
    }, this);
    this.listenTo(this.layer, 'change:meta', this._onChangeLayerMeta);
    this.on('change:column', this._reloadMap, this);
    this.on('change:bins change:start change:end', this._fetchAndResetFilter, this);
  },

  enableFilter: function () {
    this.set('own_filter', 1);
  },

  disableFilter: function () {
    this.unset('own_filter');
  },

  getData: function () {
    return this._data.toJSON();
  },

  getSize: function () {
    return this._data.size();
  },

  parse: function (data) {
    var numberOfBins = data.bins_count;
    var width = data.bin_width;
    var start = data.bins_start;

    var buckets = new Array(numberOfBins);

    _.each(data.bins, function (b) {
      buckets[b.bin] = b;
    });

    for (var i = 0; i < numberOfBins; i++) {
      buckets[i] = _.extend({
        bin: i,
        start: start + (i * width),
        end: start + ((i + 1) * width),
        freq: 0
      }, buckets[i]);
    }

    // FIXME - Update the end of last bin due https://github.com/CartoDB/cartodb.js/issues/926
    var lastBucket = buckets[numberOfBins - 1];
    if (lastBucket && lastBucket.end < lastBucket.max) {
      lastBucket.end = lastBucket.max;
    }

    this._data.reset(buckets);

    return {
      data: buckets,
      nulls: data.nulls
    };
  },

  toJSON: function (d) {
    return {
      type: 'histogram',
      options: {
        column: this.get('column'),
        bins: this.get('bins')
      }
    };
  },

  _onChangeLayerMeta: function () {
    this.filter.set('column_type', this.layer.get('meta').column_type);
  },

  _onChangeBinds: function () {
    DataviewModelBase.prototype._onChangeBinds.call(this);
    this.bind('change:histogram_sizes', function (mdl, isSizesApplied, d) {
      if (isSizesApplied) {
        this.trigger('histogram_sizes', this);
      }
    }, this);
  },

  _fetchAndResetFilter: function () {
    this.fetch();
    this.disableFilter();
    this.filter.unsetRange();
  }
},

  // Class props
  {
    ATTRS_NAMES: DataviewModelBase.ATTRS_NAMES.concat([
      'column',
      'column_type',
      'bins',
      'start',
      'end'
    ])
  }
);
<|endoftext|>


<commit_before>// Essential
var MailParser	= require("mailparser").MailParser;
var PassThrough	= require('stream').PassThrough;
var fs			= require('fs');
var path		= require('path');

// Functions
var create = require("./create");

//
/* -------------- Module Human description -------------- */
/*

		Processor creates a function that handles
	processing of a stream and session through parsers
	and spam detectors. The final product is then
	recorded in the database.

		Note that this module is mostly stream based
	and any function placed here that does not involve
	direct database interaction should be entirely
	based on NodeJS streams.

*/

module.exports = function (context, databaseConnection, Spamc) {
	return function INCOMING_EMAIL_PROCESSOR(stream, session, callback) {
		var SpamcPassThrough, fileStream;
		/* Find/Create a Spamc module with streaming capability */
		// Will not use SPAMASSASIN if the process is not available
		var mailparser = new MailParser({
			showAttachmentLinks: true,
		});

		mailparser.on("end", function (parsed) {
			/* Fix naming issues */
			// Return an error if we don't know who the envelope is sent to
			if((!session.envelope) && (!parsed.envelope)) {
				return callback({
					responseCode: 451,
					message: "Failed to process Envelope headers"
				});
			}
			parsed.envelopeTo = (session.envelope)?session.envelope.rcptTo:parsed.envelope.rcptTo;
			create(context, databaseConnection, session, parsed, function (error) {
				// Respond to SMTP Connection (WITH OR WITHOUT ERROR)
				callback(error);

				var reporter = Spamc.report();
				SpamcPassThrough.pipe(reporter);
				// Once report is obtained
				reporter.once('report', function (report) {
					if (!report) return console.error("SPAMC-STREAM-ERROR::NO_REPORT");
					// Update Email from EID
					databaseConnection.collections.mail.update({ eID: session.eID }, {
						isSpam: report.isSpam || false,
						spamScore: report.spamScore || false
					}, function (error, models) {
						if (error || (models.length < 1)) {
							return console.error("SPAMC-STREAM-ERROR::NO_RECORD")
						}
					})
				});

				reporter.on('error', function (error) {
					console.error("SPAMC-STREAM-ERROR::", error)
				})
			});
		});

		mailparser.on("error", function () {
			if (context.environment.verbose) console.log("PARSER-STREAM-ERROR", arguments)
			callback(new Error("FAILED TO STORE EMAIL"));
		})

		// Set Stream Encoding
		stream.setEncoding('utf8');
		SpamcPassThrough = new PassThrough;
		// Create new FS Write stream
		if(session.store) fileStream = fs.createWriteStream(session.path);
		// Pipe to FS Write Stream
		if(session.store) stream.pipe(fileStream);
		// Pipe to MailParser Stream
		stream.pipe(mailparser);
		// Pipe to PassThrough for Spamc-stream
		stream.pipe(SpamcPassThrough);
	}
}<commit_msg>Replaced On with Once<commit_after>// Essential
var MailParser	= require("mailparser").MailParser;
var PassThrough	= require('stream').PassThrough;
var fs			= require('fs');
var path		= require('path');

// Functions
var create = require("./create");

//
/* -------------- Module Human description -------------- */
/*

		Processor creates a function that handles
	processing of a stream and session through parsers
	and spam detectors. The final product is then
	recorded in the database.

		Note that this module is mostly stream based
	and any function placed here that does not involve
	direct database interaction should be entirely
	based on NodeJS streams.

*/

module.exports = function (context, databaseConnection, Spamc) {
	return function INCOMING_EMAIL_PROCESSOR(stream, session, callback) {
		var SpamcPassThrough, fileStream;
		/* Find/Create a Spamc module with streaming capability */
		// Will not use SPAMASSASIN if the process is not available
		var mailparser = new MailParser({
			showAttachmentLinks: true,
		});

		mailparser.once("end", function (parsed) {
			/* Fix naming issues */
			// Return an error if we don't know who the envelope is sent to
			if((!session.envelope) && (!parsed.envelope)) {
				return callback({
					responseCode: 451,
					message: "Failed to process Envelope headers"
				});
			}
			parsed.envelopeTo = (session.envelope)?session.envelope.rcptTo:parsed.envelope.rcptTo;
			create(context, databaseConnection, session, parsed, function (error) {
				// Respond to SMTP Connection (WITH OR WITHOUT ERROR)
				callback(error);

				var reporter = Spamc.report();
				SpamcPassThrough.pipe(reporter);
				// Once report is obtained
				reporter.once('report', function (report) {
					if (!report) return console.error("SPAMC-STREAM-ERROR::NO_REPORT");
					// Update Email from EID
					databaseConnection.collections.mail.update({ eID: session.eID }, {
						isSpam: report.isSpam || false,
						spamScore: report.spamScore || false
					}, function (error, models) {
						if (error || (models.length < 1)) {
							return console.error("SPAMC-STREAM-ERROR::NO_RECORD")
						}
					})
				});

				reporter.on('error', function (error) {
					console.error("SPAMC-STREAM-ERROR::", error)
				})
			});
		});

		mailparser.once("error", function () {
			if (context.environment.verbose) console.log("PARSER-STREAM-ERROR", arguments)
			callback(new Error("FAILED TO STORE EMAIL"));
		})

		// Set Stream Encoding
		stream.setEncoding('utf8');
		SpamcPassThrough = new PassThrough;
		// Create new FS Write stream
		if(session.store) fileStream = fs.createWriteStream(session.path);
		// Pipe to FS Write Stream
		if(session.store) stream.pipe(fileStream);
		// Pipe to MailParser Stream
		stream.pipe(mailparser);
		// Pipe to PassThrough for Spamc-stream
		stream.pipe(SpamcPassThrough);
	}
}<|endoftext|>


<commit_before>'use strict';
var async = require('async');
var _     = require('lodash');
var moment = require('moment');
var fs = require('fs');
var path = require('path');

function applyForEvent(args, callback) {
  var seneca = this;
  var plugin = args.role;
  var ENTITY_NS = 'cd/applications';
  var eventId = args.applyData.eventId;
  var user = args.applyData.user;
  var children = args.applyData.children;
  var emailSubject = args.applyData.emailSubject;
  var applications = [];
  var so = seneca.options();

  async.waterfall([
    buildApplications,
    sendApplications
  ], callback);

  function buildApplications(done) {
    if(children) {
      async.each(children, function (child, cb) {
        seneca.act({role: 'cd-users', cmd: 'load'}, {id: child}, function (err, response) {
          if(err) return cb(err);
          var childUser = response;
          //Query cd-profiles with user.id to apply permissions.
          seneca.act({role: 'cd-profiles', cmd: 'list', query:{userId:childUser.id}}, function (err, response) {
            if(err) return cb(err);
            var childProfile = response;
            var application = {
              eventId: eventId,
              parentId: user.id,
              userId: childUser.id,
              name: childUser.name,
              dateOfBirth: childProfile.dob,
              status: 'pending'
            };
            applications.push(application);
            cb();
          });
        });
      }, done);
    } else {
      seneca.act({role: 'cd-profiles', cmd: 'list', query:{userId:user.id}}, function (err, response) {
        if(err) return cb(err);
        var userProfile = response;
        var application = {
          eventId: eventId,
          userId: user.id,
          name: user.name,
          dateOfBirth: userProfile.dob,
          status: 'pending'
        };
        applications.push(application);
        done();
      });
    }
  }

  function sendApplications(done) {
    async.eachSeries(applications, function (application, cb) {
      async.waterfall([
        isMemberOfDojo,
        checkForApplication,
        applyForEvent,
        sendConfirmationEmail
      ], cb);

      function isMemberOfDojo(done) {
        var userId = application.parentId || application.userId; //Make sure that the parent is a member.

        seneca.act({role:plugin, cmd:'getEvent', id:eventId}, function (err, response) {
          if(err) return done(err);
          var dojoId = response.dojoId;
          seneca.act({role:'cd-dojos', cmd:'dojos_for_user', id:userId}, function (err, response) {
            if(err) return done(err);
            var dojos = response;
            var isMember = _.find(dojos, function (dojo) {
              return dojo.id === dojoId;
            });
            if(isMember) return done(null, {});
            return done(null, {error: 'User is not member of Dojo.'});
          });
        });

      }

      //Make sure this user has not already applied for this event
      function checkForApplication(status, done) {
        if(status.error) return done(null, status);
        var applicationsEntities = seneca.make$(ENTITY_NS);
        applicationsEntities.list$({userId:application.userId, eventId:eventId}, function (err, response) {
          if(err) return done(err);
          if(response.length > 0) {
            return done(null, {error: 'User has already applied for this event.'});
          }
          return done(null, {});
        });
      }

      function applyForEvent(status, done) {
        if(status.error) return done(null, status, {});
        if(application.parentId) delete application.parentId;
        var applicationsEntities = seneca.make$(ENTITY_NS);
        applicationsEntities.save$(application, function (err, response) {
          if(err) return done(err);
          return done(null, {}, response);
        });
      }

      function sendConfirmationEmail(status, application, done) {
        if(status.error) return done(null, status);
        seneca.act({role: plugin, cmd: 'getEvent', id:application.eventId}, function (err, response) {
          if(err) return done(err);
          var event = response;
          var payload;
          var eventTime = '';
          var locality = args.locality || 'en_US';

          if(event.dates.length > 1) {
            //Send email for recurring event
            var firstDate = _.first(event.dates).startTime;
            var lastDate = _.last(event.dates).startTime;
            var eventStartDate = moment.utc(firstDate).format('MMMM Do YYYY');
            var eventEndDate = moment.utc(lastDate).format('MMMM Do YYYY');
            eventTime = moment.utc(firstDate).format('HH:mm') + ' - ' + moment.utc(lastDate).format('HH:mm');
            //TODO: Translate weekdays.
            var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            var eventDay = weekdays[moment.utc(firstDate).weekday()];

            payload = {
              to:user.email,
              code: 'recurring-event-application-received-',
              locality: locality,
              subject: emailSubject,
              content:{
                userName: application.name,
                eventName: event.name,
                eventStartDate: eventStartDate,
                eventEndDate: eventEndDate,
                eventDay: eventDay,
                eventTime: eventTime,
                year: moment.utc(new Date()).format('YYYY')
              }
            };
          } else {
            //Send email for one-off event
            var eventDate = moment.utc(_.first(event.dates).startTime).format('MMMM Do YYYY');
            eventTime = moment.utc(_.first(event.dates).startTime).format('HH:mm') + ' - ' + moment.utc(_.first(event.dates).endTime).format('HH:mm');

            payload = {
              to: user.email,
              code: 'one-off-event-application-received-',
              locality: locality,
              subject: emailSubject,
              content: {
                userName: application.name,
                eventName: event.name,
                eventDate: eventDate,
                eventTime: eventTime,
                year: moment.utc(new Date()).format('YYYY')
              }
            };
          }

          seneca.act({role:'cd-dojos', cmd:'send_email', payload:payload}, done);
        });
      }
    }, done);

  }

}

module.exports = applyForEvent;
<commit_msg>small fix to email hour<commit_after>'use strict';
var async = require('async');
var _     = require('lodash');
var moment = require('moment');
var fs = require('fs');
var path = require('path');

function applyForEvent(args, callback) {
  var seneca = this;
  var plugin = args.role;
  var ENTITY_NS = 'cd/applications';
  var eventId = args.applyData.eventId;
  var user = args.applyData.user;
  var children = args.applyData.children;
  var emailSubject = args.applyData.emailSubject;
  var applications = [];
  var so = seneca.options();

  async.waterfall([
    buildApplications,
    sendApplications
  ], callback);

  function buildApplications(done) {
    if(children) {
      async.each(children, function (child, cb) {
        seneca.act({role: 'cd-users', cmd: 'load'}, {id: child}, function (err, response) {
          if(err) return cb(err);
          var childUser = response;
          //Query cd-profiles with user.id to apply permissions.
          seneca.act({role: 'cd-profiles', cmd: 'list', query:{userId:childUser.id}}, function (err, response) {
            if(err) return cb(err);
            var childProfile = response;
            var application = {
              eventId: eventId,
              parentId: user.id,
              userId: childUser.id,
              name: childUser.name,
              dateOfBirth: childProfile.dob,
              status: 'pending'
            };
            applications.push(application);
            cb();
          });
        });
      }, done);
    } else {
      seneca.act({role: 'cd-profiles', cmd: 'list', query:{userId:user.id}}, function (err, response) {
        if(err) return cb(err);
        var userProfile = response;
        var application = {
          eventId: eventId,
          userId: user.id,
          name: user.name,
          dateOfBirth: userProfile.dob,
          status: 'pending'
        };
        applications.push(application);
        done();
      });
    }
  }

  function sendApplications(done) {
    async.eachSeries(applications, function (application, cb) {
      async.waterfall([
        isMemberOfDojo,
        checkForApplication,
        applyForEvent,
        sendConfirmationEmail
      ], cb);

      function isMemberOfDojo(done) {
        var userId = application.parentId || application.userId; //Make sure that the parent is a member.

        seneca.act({role:plugin, cmd:'getEvent', id:eventId}, function (err, response) {
          if(err) return done(err);
          var dojoId = response.dojoId;
          seneca.act({role:'cd-dojos', cmd:'dojos_for_user', id:userId}, function (err, response) {
            if(err) return done(err);
            var dojos = response;
            var isMember = _.find(dojos, function (dojo) {
              return dojo.id === dojoId;
            });
            if(isMember) return done(null, {});
            return done(null, {error: 'User is not member of Dojo.'});
          });
        });

      }

      //Make sure this user has not already applied for this event
      function checkForApplication(status, done) {
        if(status.error) return done(null, status);
        var applicationsEntities = seneca.make$(ENTITY_NS);
        applicationsEntities.list$({userId:application.userId, eventId:eventId}, function (err, response) {
          if(err) return done(err);
          if(response.length > 0) {
            return done(null, {error: 'User has already applied for this event.'});
          }
          return done(null, {});
        });
      }

      function applyForEvent(status, done) {
        if(status.error) return done(null, status, {});
        if(application.parentId) delete application.parentId;
        var applicationsEntities = seneca.make$(ENTITY_NS);
        applicationsEntities.save$(application, function (err, response) {
          if(err) return done(err);
          return done(null, {}, response);
        });
      }

      function sendConfirmationEmail(status, application, done) {
        if(status.error) return done(null, status);
        seneca.act({role: plugin, cmd: 'getEvent', id:application.eventId}, function (err, response) {
          if(err) return done(err);
          var event = response;
          var payload;
          var eventTime = '';
          var locality = args.locality || 'en_US';

          if(event.dates.length > 1) {
            //Send email for recurring event
            var firstDate = _.first(event.dates).startTime;
            var lastDate = _.last(event.dates).startTime;
            var eventStartDate = moment.utc(firstDate).format('MMMM Do YYYY');
            var eventEndDate = moment.utc(lastDate).format('MMMM Do YYYY');
            eventTime = moment.utc(firstDate).format('HH:mm') + ' - ' + moment.utc(_.first(event.dates).endTime).format('HH:mm');
            //TODO: Translate weekdays.
            var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            var eventDay = weekdays[moment.utc(firstDate).weekday()];

            payload = {
              to:user.email,
              code: 'recurring-event-application-received-',
              locality: locality,
              subject: emailSubject,
              content:{
                userName: application.name,
                eventName: event.name,
                eventStartDate: eventStartDate,
                eventEndDate: eventEndDate,
                eventDay: eventDay,
                eventTime: eventTime,
                year: moment.utc(new Date()).format('YYYY')
              }
            };
          } else {
            //Send email for one-off event
            var eventDate = moment.utc(_.first(event.dates).startTime).format('MMMM Do YYYY');
            eventTime = moment.utc(_.first(event.dates).startTime).format('HH:mm') + ' - ' + moment.utc(_.first(event.dates).endTime).format('HH:mm');

            payload = {
              to: user.email,
              code: 'one-off-event-application-received-',
              locality: locality,
              subject: emailSubject,
              content: {
                userName: application.name,
                eventName: event.name,
                eventDate: eventDate,
                eventTime: eventTime,
                year: moment.utc(new Date()).format('YYYY')
              }
            };
          }

          seneca.act({role:'cd-dojos', cmd:'send_email', payload:payload}, done);
        });
      }
    }, done);

  }

}

module.exports = applyForEvent;
<|endoftext|>


<commit_before>/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var fs = require('fs');

var template = fs.readFileSync(__dirname + '/login.html', 'utf8');

var $ = require('jquery');

var Controller = [
  '$scope',
  '$rootScope',
  'AuthenticationService',
  'Notifications',
  '$location',
  '$translate',
  'widgetLocalConf',
  '$sce',
  'configuration',
  function(
    $scope,
    $rootScope,
    AuthenticationService,
    Notifications,
    $location,
    $translate,
    localConf,
    $sce,
    configuration
  ) {
    $scope.status = 'INIT';
    if ($rootScope.authentication) {
      return $location.path('/');
    }

    $rootScope.showBreadcrumbs = false;

    $scope.showFirstLogin =
      !configuration.getDisableWelcomeMessage() &&
      localConf.get('firstVisit', true);

    $scope.FirstLoginMessage = $sce.trustAsHtml(
      $translate.instant('FIRST_LOGIN_INFO')
    );

    $scope.dismissInfoBox = function() {
      $scope.showFirstLogin = false;
      localConf.set('firstVisit', false);
    };

    // ensure focus on username input
    var autofocusField = $('form[name="signinForm"] [autofocus]')[0];
    if (autofocusField) {
      autofocusField.focus();
    }

    $scope.login = function() {
      $scope.status = 'LOADING';
      return AuthenticationService.login($scope.username, $scope.password)
        .then(function() {
          $scope.status = 'DONE';
          Notifications.clearAll();
          $scope.dismissInfoBox();
        })
        .catch(function(error) {
          $scope.status = 'ERROR';
          delete $scope.username;
          delete $scope.password;

          Notifications.addError({
            status: $translate.instant('PAGE_LOGIN_FAILED'),
            message:
              (error.data && error.data.message) ||
              $translate.instant('PAGE_LOGIN_ERROR_MSG'),
            scope: $scope,
            exclusive: true
          });
        });
    };
  }
];

module.exports = [
  '$routeProvider',
  function($routeProvider) {
    $routeProvider.when('/login', {
      template: template,
      controller: Controller
    });
  }
];
<commit_msg>chore(login): check if camunda-welcome is deployed<commit_after>/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var fs = require('fs');

var template = fs.readFileSync(__dirname + '/login.html', 'utf8');

var $ = require('jquery');

var Controller = [
  '$scope',
  '$rootScope',
  'AuthenticationService',
  'Notifications',
  '$location',
  '$translate',
  'widgetLocalConf',
  '$sce',
  'configuration',
  '$http',
  function(
    $scope,
    $rootScope,
    AuthenticationService,
    Notifications,
    $location,
    $translate,
    localConf,
    $sce,
    configuration,
    $http
  ) {
    $scope.status = 'INIT';
    if ($rootScope.authentication) {
      return $location.path('/');
    }

    $rootScope.showBreadcrumbs = false;

    $scope.showFirstLogin = false;
    var showFirstLogin =
      !configuration.getDisableWelcomeMessage() &&
      localConf.get('firstVisit', true);

    if (showFirstLogin) {
      $http({
        method: 'GET',
        url: '/camunda-welcome'
      })
        .then(function(res) {
          if (res.status !== 200) {
            $scope.dismissInfoBox();
          }
          localConf.set('firstVisit', true);
          $scope.showFirstLogin = true;
        })
        .catch($scope.dismissInfoBox);
    }

    $scope.FirstLoginMessage = $sce.trustAsHtml(
      $translate.instant('FIRST_LOGIN_INFO')
    );

    $scope.dismissInfoBox = function() {
      $scope.showFirstLogin = false;
      localConf.set('firstVisit', false);
    };

    // ensure focus on username input
    var autofocusField = $('form[name="signinForm"] [autofocus]')[0];
    if (autofocusField) {
      autofocusField.focus();
    }

    $scope.login = function() {
      $scope.status = 'LOADING';
      return AuthenticationService.login($scope.username, $scope.password)
        .then(function() {
          $scope.status = 'DONE';
          Notifications.clearAll();
          $scope.dismissInfoBox();
        })
        .catch(function(error) {
          $scope.status = 'ERROR';
          delete $scope.username;
          delete $scope.password;

          Notifications.addError({
            status: $translate.instant('PAGE_LOGIN_FAILED'),
            message:
              (error.data && error.data.message) ||
              $translate.instant('PAGE_LOGIN_ERROR_MSG'),
            scope: $scope,
            exclusive: true
          });
        });
    };
  }
];

module.exports = [
  '$routeProvider',
  function($routeProvider) {
    $routeProvider.when('/login', {
      template: template,
      controller: Controller
    });
  }
];
<|endoftext|>


<commit_before>'use strict';

var index = require('directory-index');
var RawSource = require('webpack-sources').RawSource;

var createRenderer = require('../renderer');

var Plugin = function Plugin (locations, webpackConfig, watchOptions) {
  this.locations = locations || [];
  this.render = createRenderer(webpackConfig, watchOptions);
};

Plugin.prototype.generate = function generate (location) {
  return this.render(location).then(function (result) {
    return result && {
      fileName: index(location).replace(/^\//, ''),
      assetObject: new RawSource(result)
    };
  });
};

Plugin.prototype.generateAll = function generateAll () {
  var generate = this.generate.bind(this);
  return Promise.all(this.locations.map(generate))
  .then(function (results) {
    return results.reduce(function (htmlAssets, result) {
      if (result) {
        htmlAssets[result.fileName] = result.assetObject;
      }
      return htmlAssets;
    }, {});
  });
};

Plugin.prototype.apply = function (compiler) {
  var generateAll = this.generateAll.bind(this);
  compiler.plugin('emit', function (compilation, callback) {
    generateAll()
    .then(function (htmlAssets) {
      Object.assign(compilation.assets, htmlAssets);
      callback();
    })
    .catch(callback);
  });
};

module.exports = Plugin;
<commit_msg>simplify plugin even further<commit_after>'use strict';

var index = require('directory-index');
var RawSource = require('webpack-sources').RawSource;

var createRenderer = require('../renderer');

function getFileName (location) {
  return index(location).replace(/^\//, '');
}

var Plugin = function Plugin (locations, webpackConfig, watchOptions) {
  this.render = createRenderer(webpackConfig, watchOptions);
  this.locations = locations || [];
};

Plugin.prototype.apply = function apply (compiler) {
  var render = this.render;
  var locations = this.locations;
  compiler.plugin('emit', function (compilation, callback) {
    Promise.all(locations.map(function (location) {
      return render(location).then(function (html) {
        if (html) {
          compilation.assets[getFileName(location)] = new RawSource(html);
        }
      });
    }))
    .then(function () { callback(); })
    .catch(callback);
  });
};

module.exports = Plugin;
<|endoftext|>


<commit_before>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else {
    root.avent = factory();
  }
}(this, function () {
  var EventDispatcherUtils = {
    _anonymousId: 0
  };

  EventDispatcherUtils.generateLoggerName = function () {
    return 'Anonymous Avent ' + (++this._anonymousId);
  };

  EventDispatcherUtils.isCallbackEqualToFn = function (cb, fn) {
    return (cb.fn === fn) || (cb.fn.originalFn && cb.fn.originalFn === fn);
  };

  EventDispatcherUtils.isCallbackInContext = function (cb, ctx) {
    return cb.ctx === ctx;
  };

  var EventDispatcher = function () {
    this._queue = [];
    this._callbacks = {};
    this._loggers = {};
  };

  EventDispatcher.prototype.callbackExists = function (name, fn, ctx) {
    var ret = false;
    var callbacks = this._callbacks[name] || [];

    for (var it = 0; !ret && it < callbacks.length; ++it) {
      var cb = callbacks[it];
      ret = EventDispatcherUtils.isCallbackEqualToFn(cb, fn) && EventDispatcherUtils.isCallbackInContext(cb, ctx);
    }

    return ret;
  };

  EventDispatcher.prototype.addCallback = function (name, fn, ctx) {
    if (!this.callbackExists(name, fn, ctx)) {
      this.log('add callback for', name, [fn, ctx]);

      var callbacks = this._callbacks[name] = this._callbacks[name] || [];

      callbacks.push({
        fn: fn,
        ctx: ctx
      });
    }
  };

  EventDispatcher.prototype.removeAllCallbacks = function (fn, ctx) {
    if (fn || ctx) {
      var names = Object.keys(this._callbacks);

      for (var it = 0; it < names.length; ++it) {
        this.removeCallbacks(names[it], fn, ctx);
      }
    }
    else {
      this.log('remove all callbacks');
      this._callbacks = {};
    }
  };

  EventDispatcher.prototype.filterOutDeadCallbacks = function (name, fn, ctx) {
    var keptCallbacks = [];
    var currentCallbacks = this._callbacks[name] || [];

    for (var it = 0; it < currentCallbacks.length; ++it) {
      var cb = currentCallbacks[it];
      var sameFn = EventDispatcherUtils.isCallbackEqualToFn(cb, fn);
      var sameCtx = EventDispatcherUtils.isCallbackInContext(cb, ctx);
      var isDeadCb = (fn && sameFn && ctx && sameCtx) || (fn && sameFn && !ctx) || (!fn && ctx && sameCtx);

      if (!isDeadCb) {
        keptCallbacks.push(cb);
      }
    }

    return keptCallbacks;
  };

  EventDispatcher.prototype.removeCallbacks = function (name, fn, ctx) {
    this.log('remove callbacks for', name, [fn, ctx]);

    var keptCallbacks = [];

    if (fn || ctx) {
      keptCallbacks = this.filterOutDeadCallbacks(name, fn, ctx);
    }

    if (keptCallbacks.length === 0) {
      delete this._callbacks[name];
    }
    else {
      this._callbacks[name] = keptCallbacks;
    }
  };

  EventDispatcher.prototype.cloneCallbacks = function (name) {
    var callbacks = this._callbacks[name] || [];

    return callbacks.slice(0);
  };

  EventDispatcher.prototype.scheduleDispatching = function (name, args) {
    this.log('schedule dispatching for', name, args);

    if (this._callbacks[name]) {
      this._queue.push({
        name: name,
        args: args
      });

      if (!this._timer) {
        this._timer = setTimeout(this.dispatchEvents.bind(this), 0);
      }
    }
  };

  EventDispatcher.prototype.dispatchEvents = function () {
    delete this._timer;

    var queue = this._queue;
    this._queue = [];

    for (var it = 0; it < queue.length; ++it) {
      var dispatchingEvent = queue[it];
      this.log('dispatching', dispatchingEvent.name, dispatchingEvent.args);
      var callbacks = this.cloneCallbacks(dispatchingEvent.name);

      for (var cbIt = 0; cbIt < callbacks.length; ++cbIt) {
        var cb = callbacks[cbIt];
        cb.fn.apply(cb.ctx, dispatchingEvent.args);
      }

      this.log('dispatched', dispatchingEvent.name, dispatchingEvent.args);
    }
  };

  EventDispatcher.prototype.setLogger = function (logger) {
    logger = logger || {};
    logger.name = logger.name || EventDispatcherUtils.generateLoggerName();
    logger.filters = logger.filters || ['*'];
    logger.log = logger.log || console.log.bind(console);

    for (var it = 0; it < logger.filters.length; ++it) {
      this._loggers[logger.filters[it]] = logger;
    }
  };

  EventDispatcher.prototype.clearLogger = function (filters) {
    if (filters) {
      for (var it = 0; it < filters.length; ++it) {
        var eventName = filters[it];
        this.log('clear logger for', eventName);
        delete this._loggers[eventName];
      }
    }
    else {
      this.log('clear all loggers');
      this._loggers = {};
    }
  };

  EventDispatcher.prototype.log = function (description, eventName, extraArgs) {
    var filters = eventName? ['*', eventName]: Object.keys(this._loggers);
    eventName = eventName || [];
    extraArgs = extraArgs || [];

    for (var it = 0; it < filters.length; ++it) {
      var logger = this._loggers[filters[it]];

      if (logger) {
        var args = ['[' + logger.name + '] ' + description + ':'].concat(eventName, extraArgs);
        logger.log.apply(null, args);
      }
    }
  };

  var EventEmitter = function () {};
  var eep = EventEmitter.prototype;

  eep.on = function (name, fn, ctx) {
    eep._eventDispatcher.call(this).addCallback(name, fn, ctx);

    return this;
  };

  eep.once = function (name, fn, ctx) {
    var off = eep.off.bind(this);
    var wrappedFn = function () {
      off(name, fn, ctx);
      fn.apply(ctx, arguments);
    };

    wrappedFn.originalFn = fn;

    return eep.on.call(this, name, wrappedFn, ctx);
  };

  eep.off = function (name, fn, ctx) {
    var dispatcher = eep._eventDispatcher.call(this);

    if (name) {
      dispatcher.removeCallbacks(name, fn, ctx);
    }
    else {
      dispatcher.removeAllCallbacks(fn, ctx);
    }
  };

  eep.trigger = function (name) {
    var args = [];

    for (var it = 1; it < arguments.length; ++it) {
      args.push(arguments[it]);
    }

    eep._eventDispatcher.call(this).scheduleDispatching(name, args);
  };

  eep.setLogger = function (logger) {
    eep._eventDispatcher.call(this).setLogger(logger);
  };

  eep.clearLogger = function (logger) {
    eep._eventDispatcher.call(this).clearLogger(logger);
  };

  eep.eventify = function (obj) {
    obj.on = eep.on.bind(this);
    obj.once = eep.once.bind(this);
    obj.off = eep.off.bind(this);
  };

  eep._eventDispatcher = function () {
    if (!this._dispatcher) {
      this._dispatcher = new EventDispatcher();
    }

    return this._dispatcher;
  };

  var initEventEmitter = function () {
    this._eventEmitter = new EventEmitter();
    this._eventEmitter.eventify(this);
  };

  var Avent = {};

  Avent.EventEmitter = EventEmitter;

  Avent.eventify = function (obj, emitter) {
    if (typeof obj === 'function') {
      obj = obj.prototype;
      obj._initEventEmitter = initEventEmitter;
    }
    else {
      if (!emitter) {
        emitter = obj._eventEmitter = new EventEmitter();
      }

      emitter.eventify(obj);
    }
  };

  return Avent;
}));
<commit_msg>Disable warning about max-statements in function which is factory for module<commit_after>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else {
    root.avent = factory();
  }
}(this, function () { // eslint-disable-line max-statements
  var EventDispatcherUtils = {
    _anonymousId: 0
  };

  EventDispatcherUtils.generateLoggerName = function () {
    return 'Anonymous Avent ' + (++this._anonymousId);
  };

  EventDispatcherUtils.isCallbackEqualToFn = function (cb, fn) {
    return (cb.fn === fn) || (cb.fn.originalFn && cb.fn.originalFn === fn);
  };

  EventDispatcherUtils.isCallbackInContext = function (cb, ctx) {
    return cb.ctx === ctx;
  };

  var EventDispatcher = function () {
    this._queue = [];
    this._callbacks = {};
    this._loggers = {};
  };

  EventDispatcher.prototype.callbackExists = function (name, fn, ctx) {
    var ret = false;
    var callbacks = this._callbacks[name] || [];

    for (var it = 0; !ret && it < callbacks.length; ++it) {
      var cb = callbacks[it];
      ret = EventDispatcherUtils.isCallbackEqualToFn(cb, fn) && EventDispatcherUtils.isCallbackInContext(cb, ctx);
    }

    return ret;
  };

  EventDispatcher.prototype.addCallback = function (name, fn, ctx) {
    if (!this.callbackExists(name, fn, ctx)) {
      this.log('add callback for', name, [fn, ctx]);

      var callbacks = this._callbacks[name] = this._callbacks[name] || [];

      callbacks.push({
        fn: fn,
        ctx: ctx
      });
    }
  };

  EventDispatcher.prototype.removeAllCallbacks = function (fn, ctx) {
    if (fn || ctx) {
      var names = Object.keys(this._callbacks);

      for (var it = 0; it < names.length; ++it) {
        this.removeCallbacks(names[it], fn, ctx);
      }
    }
    else {
      this.log('remove all callbacks');
      this._callbacks = {};
    }
  };

  EventDispatcher.prototype.filterOutDeadCallbacks = function (name, fn, ctx) {
    var keptCallbacks = [];
    var currentCallbacks = this._callbacks[name] || [];

    for (var it = 0; it < currentCallbacks.length; ++it) {
      var cb = currentCallbacks[it];
      var sameFn = EventDispatcherUtils.isCallbackEqualToFn(cb, fn);
      var sameCtx = EventDispatcherUtils.isCallbackInContext(cb, ctx);
      var isDeadCb = (fn && sameFn && ctx && sameCtx) || (fn && sameFn && !ctx) || (!fn && ctx && sameCtx);

      if (!isDeadCb) {
        keptCallbacks.push(cb);
      }
    }

    return keptCallbacks;
  };

  EventDispatcher.prototype.removeCallbacks = function (name, fn, ctx) {
    this.log('remove callbacks for', name, [fn, ctx]);

    var keptCallbacks = [];

    if (fn || ctx) {
      keptCallbacks = this.filterOutDeadCallbacks(name, fn, ctx);
    }

    if (keptCallbacks.length === 0) {
      delete this._callbacks[name];
    }
    else {
      this._callbacks[name] = keptCallbacks;
    }
  };

  EventDispatcher.prototype.cloneCallbacks = function (name) {
    var callbacks = this._callbacks[name] || [];

    return callbacks.slice(0);
  };

  EventDispatcher.prototype.scheduleDispatching = function (name, args) {
    this.log('schedule dispatching for', name, args);

    if (this._callbacks[name]) {
      this._queue.push({
        name: name,
        args: args
      });

      if (!this._timer) {
        this._timer = setTimeout(this.dispatchEvents.bind(this), 0);
      }
    }
  };

  EventDispatcher.prototype.dispatchEvents = function () {
    delete this._timer;

    var queue = this._queue;
    this._queue = [];

    for (var it = 0; it < queue.length; ++it) {
      var dispatchingEvent = queue[it];
      this.log('dispatching', dispatchingEvent.name, dispatchingEvent.args);
      var callbacks = this.cloneCallbacks(dispatchingEvent.name);

      for (var cbIt = 0; cbIt < callbacks.length; ++cbIt) {
        var cb = callbacks[cbIt];
        cb.fn.apply(cb.ctx, dispatchingEvent.args);
      }

      this.log('dispatched', dispatchingEvent.name, dispatchingEvent.args);
    }
  };

  EventDispatcher.prototype.setLogger = function (logger) {
    logger = logger || {};
    logger.name = logger.name || EventDispatcherUtils.generateLoggerName();
    logger.filters = logger.filters || ['*'];
    logger.log = logger.log || console.log.bind(console);

    for (var it = 0; it < logger.filters.length; ++it) {
      this._loggers[logger.filters[it]] = logger;
    }
  };

  EventDispatcher.prototype.clearLogger = function (filters) {
    if (filters) {
      for (var it = 0; it < filters.length; ++it) {
        var eventName = filters[it];
        this.log('clear logger for', eventName);
        delete this._loggers[eventName];
      }
    }
    else {
      this.log('clear all loggers');
      this._loggers = {};
    }
  };

  EventDispatcher.prototype.log = function (description, eventName, extraArgs) {
    var filters = eventName? ['*', eventName]: Object.keys(this._loggers);
    eventName = eventName || [];
    extraArgs = extraArgs || [];

    for (var it = 0; it < filters.length; ++it) {
      var logger = this._loggers[filters[it]];

      if (logger) {
        var args = ['[' + logger.name + '] ' + description + ':'].concat(eventName, extraArgs);
        logger.log.apply(null, args);
      }
    }
  };

  var EventEmitter = function () {};
  var eep = EventEmitter.prototype;

  eep.on = function (name, fn, ctx) {
    eep._eventDispatcher.call(this).addCallback(name, fn, ctx);

    return this;
  };

  eep.once = function (name, fn, ctx) {
    var off = eep.off.bind(this);
    var wrappedFn = function () {
      off(name, fn, ctx);
      fn.apply(ctx, arguments);
    };

    wrappedFn.originalFn = fn;

    return eep.on.call(this, name, wrappedFn, ctx);
  };

  eep.off = function (name, fn, ctx) {
    var dispatcher = eep._eventDispatcher.call(this);

    if (name) {
      dispatcher.removeCallbacks(name, fn, ctx);
    }
    else {
      dispatcher.removeAllCallbacks(fn, ctx);
    }
  };

  eep.trigger = function (name) {
    var args = [];

    for (var it = 1; it < arguments.length; ++it) {
      args.push(arguments[it]);
    }

    eep._eventDispatcher.call(this).scheduleDispatching(name, args);
  };

  eep.setLogger = function (logger) {
    eep._eventDispatcher.call(this).setLogger(logger);
  };

  eep.clearLogger = function (logger) {
    eep._eventDispatcher.call(this).clearLogger(logger);
  };

  eep.eventify = function (obj) {
    obj.on = eep.on.bind(this);
    obj.once = eep.once.bind(this);
    obj.off = eep.off.bind(this);
  };

  eep._eventDispatcher = function () {
    if (!this._dispatcher) {
      this._dispatcher = new EventDispatcher();
    }

    return this._dispatcher;
  };

  var initEventEmitter = function () {
    this._eventEmitter = new EventEmitter();
    this._eventEmitter.eventify(this);
  };

  var Avent = {};

  Avent.EventEmitter = EventEmitter;

  Avent.eventify = function (obj, emitter) {
    if (typeof obj === 'function') {
      obj = obj.prototype;
      obj._initEventEmitter = initEventEmitter;
    }
    else {
      if (!emitter) {
        emitter = obj._eventEmitter = new EventEmitter();
      }

      emitter.eventify(obj);
    }
  };

  return Avent;
}));
<|endoftext|>


<commit_before>'use strict';

var SunCalc = require('suncalc');
var moment = require('moment-timezone');
var exec = require('child_process').exec;

var DRY_RUN = false;

exports.execute = function execute(config){

    DRY_RUN = config.dryRun;

    var reference = new Date(config.date);

    console.log('Reference date:');
    // console.log(config.date);
    console.log(reference);

    var times = SunCalc.getTimes(reference, config.lat, config.lon);

    var sunrise = moment(times.sunrise),
        sunriseDate = sunrise.tz(config.timezone).format('HH:mm MMM D');

    if(sunrise.isAfter(config.date)){
        console.log('=> sunrise', sunriseDate);
        at(sunriseDate, getpath(config.jobPath, config.sunrise));
    } else console.log('=> sunrise if before now. We are not registering the job.');

    var sunset = moment(times.dusk),
        sunsetDate = sunset.tz('America/New_York').format('HH:mm MMM D');

    if(sunset.isAfter(config.date)){
        console.log('=> sunset', sunsetDate);
        at(sunsetDate, getpath(config.jobPath, config.sunset));
    } else console.log('=> sunset if before now. We are not registering the job.');
};

function at(date, filepath){
    //TODO: Make -m so that we mail errors. We have to setup mail thou.
    var cmd = '/usr/bin/at -f ' + filepath + ' ' + date;
    console.log(cmd);

    if(DRY_RUN) return console.log('dry-run: exit');

    exec(cmd, function(err, stdout, stderr){

        var message = '-----------------------------------------\n';
        message += '[' + (new Date()) + '] \n';
        if(stdout) message += 'stdout: ' + stdout + '\n';
        if(stderr) message += 'stderr: ' + stderr + '\n';

        if(err) message += 'exec error: ' + err.message + '\n';

        log(message);

    });
}

function getpath(filepath, action){
    var resolve = require('path').resolve,
        join = require('path').join;

    filepath = filepath ? filepath : resolve(__dirname, '../scripts');

    return join(filepath, action);
}

function log(message){
    console.log(message);
    var logpath = require('path').join(__dirname, 'at-suncalc-date.log');
    require('fs').appendFileSync(logpath, message);
}
<commit_msg>lib suncalc use debug<commit_after>'use strict';

var SunCalc = require('suncalc'),
    moment = require('moment-timezone'),
    debug = require('debug')('at-suncacl-date'),
    exec = require('child_process').exec;

var DRY_RUN = false;

exports.execute = function execute(config){

    DRY_RUN = config.dryRun;

    var reference = new Date(config.date);

    debug('Reference date: %s', reference);

    var times = SunCalc.getTimes(reference, config.lat, config.lon);

    var sunrise = moment(times.sunrise),
        sunriseDate = sunrise.tz(config.timezone).format('HH:mm MMM D');

    if(sunrise.isAfter(config.date)){
        debug('=> sunrise: %s', sunriseDate);
        at(sunriseDate, getpath(config.jobPath, config.sunrise));
    } else debug('=> sunrise if before now. We are not registering the job.');

    var sunset = moment(times.dusk),
        sunsetDate = sunset.tz('America/New_York').format('HH:mm MMM D');

    if(sunset.isAfter(config.date)){
        debug('=> sunset: %s', sunsetDate);
        at(sunsetDate, getpath(config.jobPath, config.sunset));
    } else debug('=> sunset if before now. We are not registering the job.');
};

function at(date, filepath){
    //TODO: Make -m so that we mail errors. We have to setup mail thou.
    var cmd = '/usr/bin/at -f ' + filepath + ' ' + date;

    debug('\t%s', cmd);

    if(DRY_RUN) return debug('\t%s', 'dry-run: exit'); //should this we console.log?

    exec(cmd, function(err, stdout, stderr){

        var message = '-----------------------------------------\n';
        message += '[' + (new Date()) + '] \n';
        if(stdout) message += 'stdout: ' + stdout + '\n';
        if(stderr) message += 'stderr: ' + stderr + '\n';

        if(err) message += 'exec error: ' + err.message + '\n';

        log(message);

    });
}

function getpath(filepath, action){
    var resolve = require('path').resolve,
        join = require('path').join;

    filepath = filepath ? filepath : resolve(__dirname, '../scripts');

    return join(filepath, action);
}

function log(message){
    debug(message);
    var logpath = require('path').join(__dirname, 'at-suncalc-date.log');
    require('fs').appendFileSync(logpath, message);
}
<|endoftext|>


<commit_before>;(function($) {

	// Determine whether the preview JSON/XML button display and functionality should be enabled, based on the given security token.

	function enable(input) {

		var token = input ? input.val() : $('div.apiwesome.admin input.preview.token').val();
		$('div.apiwesome.admin a.preview').each(function() {

			var preview = $(this);
			if(token.length > 0) {
				preview.attr('href', preview.data('url') + '?token=' + token);
				preview.fadeTo(250, 1, function() {

					preview.removeClass('disabled');
				});
			}
			else {
				preview.fadeTo(250, 0.4, function() {

					preview.addClass('disabled');
				});
				preview.attr('href', preview.data('url'));
			}
		});
	};

	// Bind the mouse events dynamically.

	$.entwine('ss', function($) {

		// Trigger a confirmation message for security token regeneration.

		$('div.apiwesome.admin a.regenerate').entwine({
			onclick: function() {

				return confirm('This will INVALIDATE any JSON/XML feeds!');
			}
		});

		// Trigger an interface update on key press.

		$('div.apiwesome.admin input.preview.token').entwine({
			onchange: function() {

				enable($(this));
			}
		});

		// Trigger an interface update and handle any preview request.

		$('div.apiwesome.admin a.preview').entwine({
			onmouseenter: function() {

				enable();
			},
			onclick: function() {

				return !$(this).hasClass('disabled');
			}
		});
	});

})(jQuery);
<commit_msg>Corrected a minor issue when using the token interface before switching pages.<commit_after>;(function($) {

	// Determine whether the preview JSON/XML button display and functionality should be enabled, based on the given security token.

	function enable(input) {

		var token = input ? input.val() : $('div.apiwesome.admin input.preview.token').val();
		$('div.apiwesome.admin a.preview').each(function() {

			var preview = $(this);
			if(token.length > 0) {
				preview.attr('href', preview.data('url') + '?token=' + token);
				preview.fadeTo(250, 1, function() {

					preview.removeClass('disabled');
				});
			}
			else {
				preview.fadeTo(250, 0.4, function() {

					preview.addClass('disabled');
				});
				preview.attr('href', preview.data('url'));
			}
		});
	};

	// Bind the mouse events dynamically.

	$.entwine('ss', function($) {

		// Trigger a confirmation message for security token regeneration.

		$('div.apiwesome.admin a.regenerate').entwine({
			onclick: function() {

				return confirm('This will INVALIDATE any JSON/XML feeds!');
			}
		});

		// Trigger an interface update on key press.

		$('div.apiwesome.admin input.preview.token').entwine({
			onchange: function() {

				enable($(this));
				$('#Form_EditForm').removeClass('changed');
			}
		});

		// Trigger an interface update and handle any preview request.

		$('div.apiwesome.admin a.preview').entwine({
			onmouseenter: function() {

				enable();
			},
			onclick: function() {

				return !$(this).hasClass('disabled');
			}
		});
	});

})(jQuery);
<|endoftext|>