<commit_before>Ext.define("GridExporter", {
    //dateFormat : 'Y-m-d g:i',
    dateFormat : 'Y-m-d',

    inheritableStatics: {
        XmlFileHeader: '<?xml version="1.0"?>',
        XmlFileExtension: '.xml.txt'
    },

    _downloadFiles: function( files ) {
        if ( files.length )
        {
            var data = files.pop();
            var format = files.pop();
            var file = files.pop();

            var href = "";

            var ml = Ext.DomHelper.insertAfter(window.document.getElementById('exportButton'), href);
            ml.click();
//            ml.remove(); //Leaves them behind without this, but there is a timing issue: from click to remove.
            this._downloadFiles(files);
        }
    },

    exportCSV: function(grid) {
        var data = this._getCSV(grid, false);
        // fix: ' character was causing termination of csv file
        data = data.replace(/\'/g, "");
        this._downloadFiles(
            [
                'export.csv', 'data:text/csv;charset=utf8', data
            ]
        );

    },

    _escapeForCSV: function(string) {
        string = "" + string;
        if (string.match(/,/)) {
            if (!string.match(/"/)) {
                string = '"' + string + '"';
            } else {
                string = string.replace(/,/g, ''); // comma's and quotes-- sorry, just lose the commas
            }
        }
        return string;
    },

    _getFieldText: function(fieldData,record,col,index) {
        var text;

        if (fieldData === null || fieldData === undefined) {
            text = '';

        } else if (fieldData._refObjectName && !fieldData.getMonth) {
            text = fieldData._refObjectName;

        } else if (fieldData instanceof Date) {
            text = Ext.Date.format(fieldData, this.dateFormat);

        } else if (typeof fieldData === 'string' ){ //Remove any html formatting coding.
            //Remove all the tags  for now
            text = fieldData.replace(/<[^>]*>/g," ");
            text = text.replace(/&nbsp\;/g," ");

        } /*else if (!fieldData.match) { // not a string or object we recognize...bank it out
            text = '';
        } */ else {
            text = fieldData;
        }

        return text;
    },

    _getFieldTextAndEscape: function(fieldData,record,col,index) {
        var string  = this._getFieldText(fieldData,record,col,index);

        return this._escapeForCSV(string);
    },

    // have to add the colIdx to the count of locked columns
    fixedColumnCount : function(columns) {
        var cols = _.filter(columns,function(c) {
            return c!==undefined && c!==null && c.locked === true;
        });
        return cols.length;
    },

    _stripDivs: function(text) {

        var retval = text.replace('
','');
        retval = retval.replace('
','');
        retval = retval.replace('
','');
        return retval;
    },

    _getCSV: function (grid) {
        var cols    = grid.columns;
        var store   = grid.store;
        var hdrData    = '';
        var rowData = '';
        var valid = true;

        var that = this;
        Ext.Array.each(cols, function(col, index) {
            if (col.hidden !== true) {

                // fix the issue with the "SYLK" warning in excel by prepending "Item" to the ID column
//                var colLabel = (index === 0 ? "Item " : "") + col.dataIndex;

                var colLabel = col && col.dataIndex;
                if ( colLabel && colLabel.replace(/
/,'') ){
                    if ( col.editor && col.editor.xtype === 'apprichtexteditor') {
                        hdrData += that._getFieldTextAndEscape(col.text) + ',';
                    }
                    else {
                        hdrData += that._getFieldTextAndEscape(colLabel) + ',';
                    }
                }
            }
        });
        hdrData += "\n";

        _.each( store.data.items, function(record,i) {
            Ext.Array.each(cols, function(col, index) {

                if (col.hidden !== true) {
                    var fieldName   = col && col.dataIndex;
                    if (fieldName ) {
                        var text = record.get(fieldName);

                        if ( col.editor && col.editor.xtype === 'apprichtexteditor') {
                            var rg = this.up('rallygrid');
                            var rt = rg._findSubText(text, index + 1);  //Adjust for function
                            rt = that._stripDivs(rt);
                            rowData += that._getFieldTextAndEscape(rt) + ',';
                        }
                        else {
                            rowData += that._getFieldTextAndEscape(text,record,col,index) + ',';
                        }
                    }
                }
            });
            rowData += "\n";
        });

        if (rowData.length > 0)
            return hdrData + rowData;
        else
            return null;
    }
});<commit_msg>Improve html to text filter<commit_after>Ext.define("GridExporter", {
    //dateFormat : 'Y-m-d g:i',
    dateFormat : 'Y-m-d',

    inheritableStatics: {
        XmlFileHeader: '<?xml version="1.0"?>',
        XmlFileExtension: '.xml.txt'
    },

    _downloadFiles: function( files ) {
        if ( files.length )
        {
            var data = files.pop();
            var format = files.pop();
            var file = files.pop();

            var href = "";

            var ml = Ext.DomHelper.insertAfter(window.document.getElementById('exportButton'), href);
            ml.click();
//            ml.remove(); //Leaves them behind without this, but there is a timing issue: from click to remove.
            this._downloadFiles(files);
        }
    },

    exportCSV: function(grid) {
        var data = this._getCSV(grid, false);
        // fix: ' character was causing termination of csv file
        data = data.replace(/\'/g, "");
        this._downloadFiles(
            [
                'export.csv', 'data:text/csv;charset=utf8', data
            ]
        );

    },

    _escapeForCSV: function(string) {
        string = "" + string;
        if (string.match(/,/)) {
            if (!string.match(/"/)) {
                string = '"' + string + '"';
            } else {
                string = string.replace(/,/g, ''); // comma's and quotes-- sorry, just lose the commas
            }
        }
        return string;
    },

    _getFieldText: function(fieldData,record,col,index) {
        var text;

        if (fieldData === null || fieldData === undefined) {
            text = '';

        } else if (fieldData._refObjectName && !fieldData.getMonth) {
            text = fieldData._refObjectName;

        } else if (fieldData instanceof Date) {
            text = Ext.Date.format(fieldData, this.dateFormat);

        } else if (typeof fieldData === 'string' ){ //Remove any html formatting coding.

            text = fieldData.replace(/<[^>]*>/g," "); //Remove all the tags  for now
            text = text.replace(/\’/g,"'");              //Remove the MAC back-quote
            text = text.replace(/&nbsp\;/g," ");        //Remove the &nbsp chars

        } /*else if (!fieldData.match) { // not a string or object we recognise...blank it out
            text = '';
        } */ else {
            text = fieldData;
        }

        return text;
    },

    _getFieldTextAndEscape: function(fieldData,record,col,index) {
        var string  = this._getFieldText(fieldData,record,col,index);

        return this._escapeForCSV(string);
    },

    // have to add the colIdx to the count of locked columns
    fixedColumnCount : function(columns) {
        var cols = _.filter(columns,function(c) {
            return c!==undefined && c!==null && c.locked === true;
        });
        return cols.length;
    },

    _stripDivs: function(text) {

        var retval = text.replace('
','');
        retval = retval.replace('
','');
        retval = retval.replace('
','');
        return retval;
    },

    _getCSV: function (grid) {
        var cols    = grid.columns;
        var store   = grid.store;
        var hdrData    = '';
        var rowData = '';
        var valid = true;

        var that = this;
        Ext.Array.each(cols, function(col, index) {
            if (col.hidden !== true) {

                // fix the issue with the "SYLK" warning in excel by prepending "Item" to the ID column
//                var colLabel = (index === 0 ? "Item " : "") + col.dataIndex;

                var colLabel = col && col.dataIndex;
                if ( colLabel && colLabel.replace(/
/,'') ){
                    if ( col.editor && col.editor.xtype === 'apprichtexteditor') {
                        hdrData += that._getFieldTextAndEscape(col.text) + ',';
                    }
                    else {
                        hdrData += that._getFieldTextAndEscape(colLabel) + ',';
                    }
                }
            }
        });
        hdrData += "\n";

        _.each( store.data.items, function(record,i) {
            Ext.Array.each(cols, function(col, index) {

                if (col.hidden !== true) {
                    var fieldName   = col && col.dataIndex;
                    if (fieldName ) {
                        var text = record.get(fieldName);

                        if ( col.editor && col.editor.xtype === 'apprichtexteditor') {
                            var rg = this.up('rallygrid');
                            var rt = rg._findSubText(text, index + 1);  //Adjust for function
                            rt = that._stripDivs(rt);
                            rowData += that._getFieldTextAndEscape(rt) + ',';
                        }
                        else {
                            rowData += that._getFieldTextAndEscape(text,record,col,index) + ',';
                        }
                    }
                }
            });
            rowData += "\n";
        });

        if (rowData.length > 0)
            return hdrData + rowData;
        else
            return null;
    }
});<|endoftext|>


<commit_before>'use strict'

const Joi = require('joi')
const { semver: isSemver } = require('./validators')

/*
  Note:
  Validators defined in this file are used by more than one service.
  Validators which are only used by one service
  should be declared in that service's test file.
*/

const withRegex = re => Joi.string().regex(re)

const isVPlusTripleDottedVersion = withRegex(/^v[0-9]+.[0-9]+.[0-9]+$/)

const isVPlusDottedVersionAtLeastOne = withRegex(/^v\d+(\.\d+)?(\.\d+)?$/)

// matches a version number with N 'clauses' e.g: v1.2 or v1.22.7.392 are valid
const isVPlusDottedVersionNClauses = withRegex(/^v\d+(\.\d+)*$/)

// matches a version number with N 'clauses'
// and an optional text suffix
// e.g: -beta, -preview1, -release-candidate, +beta, ~pre9-12 etc
const isVPlusDottedVersionNClausesWithOptionalSuffix = withRegex(
  /^v\d+(\.\d+)*([-+~].*)?$/
)

// same as above, but also accepts an optional 'epoch' prefix that can be
// found e.g. in distro package versions, like 4:6.3.0-4
const isVPlusDottedVersionNClausesWithOptionalSuffixAndEpoch = withRegex(
  /^v(\d+:)?\d+(\.\d+)*([-+~].*)?$/
)

// Simple regex for test Composer versions rule
// https://getcomposer.org/doc/articles/versions.md
// Examples:
// 7.1
// >=5.6
// >1.0 <2.0
// !=1.0 <1.1 || >=1.2
// 7.1.*
// 7.* || 5.6.*
// This regex not support branches, minimum-stability, ref and any (*)
// https://getcomposer.org/doc/04-schema.md#package-links
// https://getcomposer.org/doc/04-schema.md#minimum-stability
const isComposerVersion = withRegex(
  /^\s*(>=|>|<|<=|!=|\^|~)?\d+(\.(\*|(\d+(\.(\d+|\*))?)))?((\s*\|\|)?\s*(>=|>|<|<=|!=|\^|~)?\d+(\.(\*|(\d+(\.(\d+|\*))?)))?)*\s*$/
)

// Regex for validate php-version.versionReduction()
// >= 7
// >= 7.1
// 5.4, 5.6, 7.2
// 5.4 - 7.1, HHVM
const isPhpVersionReduction = withRegex(
  /^((>= \d+(\.\d+)?)|(\d+\.\d+(, \d+\.\d+)*)|(\d+\.\d+ - \d+\.\d+))(, HHVM)?$/
)

const isStarRating = withRegex(
  /^(?=.{5}$)(\u2605{0,5}[\u00BC\u00BD\u00BE]?\u2606{0,5})$/
)

// Required to be > 0, because accepting zero masks many problems.
const isMetric = withRegex(/^([1-9][0-9]*[kMGTPEZY]?|[1-9]\.[1-9][kMGTPEZY])$/)

const isMetricOpenIssues = withRegex(
  /^([1-9][0-9]*[kMGTPEZY]?|[1-9]\.[1-9][kMGTPEZY]) open$/
)

const isMetricOverMetric = withRegex(
  /^([1-9][0-9]*[kMGTPEZY]?|[1-9]\.[1-9][kMGTPEZY])\/([1-9][0-9]*[kMGTPEZY]?|[1-9]\.[1-9][kMGTPEZY])$/
)

const isMetricOverTimePeriod = withRegex(
  /^([1-9][0-9]*[kMGTPEZY]?|[1-9]\.[1-9][kMGTPEZY])\/(year|month|four weeks|quarter|week|day)$/
)

const isZeroOverTimePeriod = withRegex(
  /^0\/(year|month|four weeks|quarter|week|day)$/
)

const isIntegerPercentage = withRegex(/^[1-9][0-9]?%|^100%|^0%$/)
const isDecimalPercentage = withRegex(/^[0-9]+\.[0-9]*%$/)
const isPercentage = Joi.alternatives().try(
  isIntegerPercentage,
  isDecimalPercentage
)

const isFileSize = withRegex(/^[0-9]*[.]?[0-9]+\s(B|kB|MB|GB|TB|PB|EB|ZB|YB)$/)

const isFormattedDate = Joi.alternatives().try(
  Joi.equal('today', 'yesterday'),
  Joi.string().regex(/^last (sun|mon|tues|wednes|thurs|fri|satur)day$/),
  Joi.string().regex(
    /^(january|february|march|april|may|june|july|august|september|october|november|december)( \d{4})?$/
  )
)

const isRelativeFormattedDate = Joi.alternatives().try(
  Joi.string().regex(
    /^(in |)([0-9]+|a few|a|an|)(| )(second|minute|hour|day|month|year)(s|)( ago|)$/
  )
)

const isDependencyState = withRegex(
  /^(\d+ out of date|\d+ deprecated|up to date)$/
)

const makeTestTotalsValidator = ({ passed, failed, skipped }) =>
  withRegex(
    new RegExp(`^[0-9]+ ${passed}(, [0-9]+ ${failed})?(, [0-9]+ ${skipped})?$`)
  )

const makeCompactTestTotalsValidator = ({ passed, failed, skipped }) =>
  withRegex(
    new RegExp(
      `^${passed} [0-9]+( \\| ${failed} [0-9]+)?( \\| ${skipped} [0-9]+)?$`
    )
  )

const isDefaultTestTotals = makeTestTotalsValidator({
  passed: 'passed',
  failed: 'failed',
  skipped: 'skipped',
})
const isDefaultCompactTestTotals = makeCompactTestTotalsValidator({
  passed: '✔',
  failed: '✘',
  skipped: '➟',
})
const isCustomTestTotals = makeTestTotalsValidator({
  passed: 'good',
  failed: 'bad',
  skipped: 'n/a',
})
const isCustomCompactTestTotals = makeCompactTestTotalsValidator({
  passed: '💃',
  failed: '🤦♀',
  skipped: '🤷',
})

module.exports = {
  isSemver,
  isVPlusTripleDottedVersion,
  isVPlusDottedVersionAtLeastOne,
  isVPlusDottedVersionNClauses,
  isVPlusDottedVersionNClausesWithOptionalSuffix,
  isVPlusDottedVersionNClausesWithOptionalSuffixAndEpoch,
  isComposerVersion,
  isPhpVersionReduction,
  isStarRating,
  isMetric,
  isMetricOpenIssues,
  isMetricOverMetric,
  isMetricOverTimePeriod,
  isZeroOverTimePeriod,
  isPercentage,
  isIntegerPercentage,
  isDecimalPercentage,
  isFileSize,
  isFormattedDate,
  isRelativeFormattedDate,
  isDependencyState,
  withRegex,
  isDefaultTestTotals,
  isDefaultCompactTestTotals,
  isCustomTestTotals,
  isCustomCompactTestTotals,
  makeTestTotalsValidator,
  makeCompactTestTotalsValidator,
}
<commit_msg>test: add generic metric helper (#6684)<commit_after>'use strict'

const Joi = require('joi')
const { semver: isSemver } = require('./validators')

/*
  Note:
  Validators defined in this file are used by more than one service.
  Validators which are only used by one service
  should be declared in that service's test file.
*/

const withRegex = re => Joi.string().regex(re)

const isVPlusTripleDottedVersion = withRegex(/^v[0-9]+.[0-9]+.[0-9]+$/)

const isVPlusDottedVersionAtLeastOne = withRegex(/^v\d+(\.\d+)?(\.\d+)?$/)

// matches a version number with N 'clauses' e.g: v1.2 or v1.22.7.392 are valid
const isVPlusDottedVersionNClauses = withRegex(/^v\d+(\.\d+)*$/)

// matches a version number with N 'clauses'
// and an optional text suffix
// e.g: -beta, -preview1, -release-candidate, +beta, ~pre9-12 etc
const isVPlusDottedVersionNClausesWithOptionalSuffix = withRegex(
  /^v\d+(\.\d+)*([-+~].*)?$/
)

// same as above, but also accepts an optional 'epoch' prefix that can be
// found e.g. in distro package versions, like 4:6.3.0-4
const isVPlusDottedVersionNClausesWithOptionalSuffixAndEpoch = withRegex(
  /^v(\d+:)?\d+(\.\d+)*([-+~].*)?$/
)

// Simple regex for test Composer versions rule
// https://getcomposer.org/doc/articles/versions.md
// Examples:
// 7.1
// >=5.6
// >1.0 <2.0
// !=1.0 <1.1 || >=1.2
// 7.1.*
// 7.* || 5.6.*
// This regex not support branches, minimum-stability, ref and any (*)
// https://getcomposer.org/doc/04-schema.md#package-links
// https://getcomposer.org/doc/04-schema.md#minimum-stability
const isComposerVersion = withRegex(
  /^\s*(>=|>|<|<=|!=|\^|~)?\d+(\.(\*|(\d+(\.(\d+|\*))?)))?((\s*\|\|)?\s*(>=|>|<|<=|!=|\^|~)?\d+(\.(\*|(\d+(\.(\d+|\*))?)))?)*\s*$/
)

// Regex for validate php-version.versionReduction()
// >= 7
// >= 7.1
// 5.4, 5.6, 7.2
// 5.4 - 7.1, HHVM
const isPhpVersionReduction = withRegex(
  /^((>= \d+(\.\d+)?)|(\d+\.\d+(, \d+\.\d+)*)|(\d+\.\d+ - \d+\.\d+))(, HHVM)?$/
)

const isStarRating = withRegex(
  /^(?=.{5}$)(\u2605{0,5}[\u00BC\u00BD\u00BE]?\u2606{0,5})$/
)

// Required to be > 0, because accepting zero masks many problems.
const isMetric = withRegex(/^([1-9][0-9]*[kMGTPEZY]?|[1-9]\.[1-9][kMGTPEZY])$/)

/**
 * @param {RegExp} nestedRegexp Pattern that must appear after the metric.
 * @returns {Function} A function that returns a RegExp that matches a metric followed by another pattern.
 */
const isMetricWithPattern = nestedRegexp => {
  const pattern = `^([1-9][0-9]*[kMGTPEZY]?|[1-9]\\.[1-9][kMGTPEZY])${nestedRegexp.source}$`
  const regexp = new RegExp(pattern)
  return withRegex(regexp)
}

const isMetricOpenIssues = isMetricWithPattern(/ open/)

const isMetricOverMetric = isMetricWithPattern(
  /\/([1-9][0-9]*[kMGTPEZY]?|[1-9]\.[1-9][kMGTPEZY])/
)

const isMetricOverTimePeriod = isMetricWithPattern(
  /\/(year|month|four weeks|quarter|week|day)/
)

const isZeroOverTimePeriod = withRegex(
  /^0\/(year|month|four weeks|quarter|week|day)$/
)

const isIntegerPercentage = withRegex(/^[1-9][0-9]?%|^100%|^0%$/)
const isDecimalPercentage = withRegex(/^[0-9]+\.[0-9]*%$/)
const isPercentage = Joi.alternatives().try(
  isIntegerPercentage,
  isDecimalPercentage
)

const isFileSize = withRegex(/^[0-9]*[.]?[0-9]+\s(B|kB|MB|GB|TB|PB|EB|ZB|YB)$/)

const isFormattedDate = Joi.alternatives().try(
  Joi.equal('today', 'yesterday'),
  Joi.string().regex(/^last (sun|mon|tues|wednes|thurs|fri|satur)day$/),
  Joi.string().regex(
    /^(january|february|march|april|may|june|july|august|september|october|november|december)( \d{4})?$/
  )
)

const isRelativeFormattedDate = Joi.alternatives().try(
  Joi.string().regex(
    /^(in |)([0-9]+|a few|a|an|)(| )(second|minute|hour|day|month|year)(s|)( ago|)$/
  )
)

const isDependencyState = withRegex(
  /^(\d+ out of date|\d+ deprecated|up to date)$/
)

const makeTestTotalsValidator = ({ passed, failed, skipped }) =>
  withRegex(
    new RegExp(`^[0-9]+ ${passed}(, [0-9]+ ${failed})?(, [0-9]+ ${skipped})?$`)
  )

const makeCompactTestTotalsValidator = ({ passed, failed, skipped }) =>
  withRegex(
    new RegExp(
      `^${passed} [0-9]+( \\| ${failed} [0-9]+)?( \\| ${skipped} [0-9]+)?$`
    )
  )

const isDefaultTestTotals = makeTestTotalsValidator({
  passed: 'passed',
  failed: 'failed',
  skipped: 'skipped',
})
const isDefaultCompactTestTotals = makeCompactTestTotalsValidator({
  passed: '✔',
  failed: '✘',
  skipped: '➟',
})
const isCustomTestTotals = makeTestTotalsValidator({
  passed: 'good',
  failed: 'bad',
  skipped: 'n/a',
})
const isCustomCompactTestTotals = makeCompactTestTotalsValidator({
  passed: '💃',
  failed: '🤦♀',
  skipped: '🤷',
})

module.exports = {
  isSemver,
  isVPlusTripleDottedVersion,
  isVPlusDottedVersionAtLeastOne,
  isVPlusDottedVersionNClauses,
  isVPlusDottedVersionNClausesWithOptionalSuffix,
  isVPlusDottedVersionNClausesWithOptionalSuffixAndEpoch,
  isComposerVersion,
  isPhpVersionReduction,
  isStarRating,
  isMetric,
  isMetricWithPattern,
  isMetricOpenIssues,
  isMetricOverMetric,
  isMetricOverTimePeriod,
  isZeroOverTimePeriod,
  isPercentage,
  isIntegerPercentage,
  isDecimalPercentage,
  isFileSize,
  isFormattedDate,
  isRelativeFormattedDate,
  isDependencyState,
  withRegex,
  isDefaultTestTotals,
  isDefaultCompactTestTotals,
  isCustomTestTotals,
  isCustomCompactTestTotals,
  makeTestTotalsValidator,
  makeCompactTestTotalsValidator,
}
<|endoftext|>


<commit_before>'use strict'

var _ = require('lodash')
  , raf = require('raf')
  , Ribcage
  , extendView

Ribcage = {
  initialize: function initialize(opts){
    opts = opts || {}

    // if we need to load data before rendering, do it
    // otherwise, assume we have the data already
    this._dataLoaded = typeof this.loadData !== 'function'

    this._nukeOnRender = opts._nukeOnRender
    // delete would turn this into a "slow object" in V8
    // we can't set to null, b/c a state model can reject extra properties
    if (_.has(opts, '_nukeOnRender')) opts = _.omit(opts, '_nukeOnRender')

    // backbone 1.1+ doesn't auto-set this.options
    this.options = opts

    if (this.beforeInit) this.beforeInit(opts)

    this.template = this.template || opts.template

    if (!this.template) {
      this.template = function template(){
        return ''
      }
    }

    if (this.afterInit) this.afterInit(opts)

    this.render()
  }

, context: function context(){
    var model = this.model ? this.model.toJSON() : {}
      , state = this.state ? this.state.toJSON() : {}

    return _.extend({}, this.options, model, state)
  }

, render: function render(){
    var self = this
      , model = this.model

    if (typeof this.bindEvents === 'function') {
      this.bindEvents()
    }

    if (!this._dataLoaded && typeof this.loadData === 'function') {
      return this.loadData(function dataLoaded(){
        self._dataLoaded = true
        self.render()
      })
    }

    // closing destroys the el, might need to recreate it
    if (!this.el) {
      this._ensureElement()
    }

    if (this.beforeRender) {
      this.beforeRender()
    }

    // Maintainers of legacy code might want to use this
    // but certainly not YOU, young grasshopper!
    if (this._nukeOnRender) {
      this.closeSubviews()
      this.$el.empty()
    }

    if (this.beforeTemplating) {
      model = this.beforeTemplating()
    }

    if (this.context) {
      model = this.context()
    }

    this.$el.html(this.template(model))

    // As soon as the view is bound to DOM, we need to delegate events and re-render all
    // subviews to keep events intact. -cstumph
    this.delegateEvents()
    this.eachSubview(function eachSubviewInRender(view){
      view.render()
    })

    // I'm not happy deferring here, but backbone's
    // event system is based on the DOM, so my hands
    // are tied. - Daniel
    _.defer(function deferSoTheDOMCanCatchup(){
      self.trigger('afterRender')
    })

    if (this.afterRender) {
      this.afterRender()
    }

    return this
  }

, proxy: function proxy(name, view){
    this.listenTo(view, name, function proxiedEventCallback(){
      var args = Array.prototype.slice.call(arguments, 0)
      args.splice(0, 0, name)
      this.trigger.apply(this, args)
    })
  }

, eachSubview: function eachSubview(iterator, context){
    _.each(this.subviews, iterator, context || this)
  }

, _attachSubView: function _attachSubView(view){
    var viewId

    this.subviews = this.subviews || {}
    this.subviewByModelId = this.subviewByModelId || {}

    this.subviews[view.cid] = view

    if (view.model) {
      viewId = view.model.id || view.model.cid
      if (!this.subviewByModelId[viewId]) this.subviewByModelId[viewId] = []

      this.subviewByModelId[viewId].push(view)
    }

    return view
  }

, appendSubview: function appendSubview(view, el){
    el || (el = this.$el)

    this._attachSubView(view)

    // closing a view will remove the el, so ensure we have one before re-attaching
    if (view.options.render || !view.el) view.render()
    el.append(view.el)

    _.defer(function deferSoTheDOMCanCatchup(){
      view.trigger('afterAppend', view)
    })

    if (view.afterAppend) {
      view.afterAppend()
    }
  }

, prependSubview: function prependSubview(view, el){
    el || (el = this.$el)

    this._attachSubView(view)

    // closing a view will remove the el, so ensure we have one before re-attaching
    if (view.options.renderOnAppend || !view.el) view.render()
    el.prepend(view.el)

    _.defer(function deferSoTheDOMCanCatchup(){
      view.trigger('afterPrepend', view)
    })

    if (view.afterPrepend) {
      view.afterPrepend()
    }
  }

, appendSubviews: function appendSubviews(views, el, callback){
    var fragment = document.createDocumentFragment()

    el || (el = this.$el)

    _.each(views, function appendEachView(view){
      this._attachSubView(view)

      // closing a view will remove the el, so ensure we have one before re-attaching
      if (view.options.renderOnAppend || !view.el) view.render()
      fragment.appendChild(view.el)

      _.defer(function deferSoTheDOMCanCatchup(){
        view.trigger('afterAppend', view)
      })

      if (view.afterAppend) {
        view.afterAppend()
      }
    }, this)

    raf(function onFrame(){
      el[0].appendChild(fragment)
      if (_.isFunction(callback)) callback(views)
    })
  }

, batchAppendSubviews: function batchAppendSubviews(views, el, batchCount, batchCallback, callback){
    var self = this
      , batches = _(views)
                  .groupBy(function groupIntoBatches(view, index){
                    return Math.floor(index / batchCount)
                  })
                  .toArray()
                  .valueOf()
      , appendNextBatch = function appendNextBatch(){
      var batchesLeft = batches.length
        , viewBatch = batchesLeft ? batches.shift() : false

      // with no batches left, just return early
      if (!batchesLeft) {
        // if we have a final callback, call that.
        return typeof callback === 'function'
          ? void callback()
          : void 0
      }

      self.appendSubviews(viewBatch, el, function subviewsAppended(){
        if (typeof batchCallback === 'function') {
          batchCallback(viewBatch)
        }

        appendNextBatch()
      })
    }

    appendNextBatch()
  }

, close: function close(options, callback){
    options || (options = {})

    if (this.beforeClose) this.beforeClose()

    this.closeSubviews({keepDom: true}, _.bind(function onSubviewsClosed(){
      this.stopListening()

      // when the subviews are closed, close the parent
      // keep the DOM elements, b/c it's save to assume that all child DOM
      // is containted by the parent DOM container. This allows us to reduce
      // many DOM removal calls to just one.
      if (!options.keepDom) {
        raf(function onFrame(){
          // remove the from the DOM
          if (this.$el) this.$el.remove()
          // destroy our reference to the DOM node
          this.$el = null
          this.el = null
          if (_.isFunction(callback)) callback()
        }.bind(this))
      }
      else if (_.isFunction(callback)) callback()
    }, this))
  }

, closeSubviews: function closeSubviews(options, callback){
    var subviewCount = _.size(this.subviews)
      , done

    if (_.isFunction(callback)){
      // if there are no subviews to close, just call the callback
      if (!subviewCount) return void callback()
      else done = _.after(subviewCount, callback)
    }

    this.eachSubview(function closeEachSubview(subview){
      subview.close(options, done)
    })

    // empty out our lists of subviews
    this.subviews = {}
    this.subviewByModelId = {}
  }

, detachSubview: function detachSubview(view){
    var msg

    if (this.subviews) {
      if (view && !this.subviews[view.cid]) {
        msg = 'View not found in ' + this.className + '\'s subviews: ' + view.className

        if (view.model) msg += '\n\n' + view.model.toJSON()

        throw new Error(msg)
      }

      // delete makes this into a "slow object" in V8
      // but that's okay b/c any perf gains we'd get would be lost by having to
      // itterate over subviews to remove falsey values.
      delete this.subviews[view.cid]
    }

    view.$el.detach()
  }

, _removeSubviewByModel: function _removeSubviewByModel(model, method){
    var id = model.id

    if (this.subviewByModelId){
      if (!id || !this.subviewByModelId[id]){
        throw new Error('No views with ' + id + ' model id found in ' + this.className + ' subviews')
      }

      _.each(this.subviewByModelId[id], function eachSubviewById(view){
        method.call(this, view)
      }, this)

      // delete would turn this into a "slow object" in V8, so just set to null
      this.subviewByModelId[id] = null
    }
  }

, closeSubviewsByModel: function closeSubviewsByModel(model){
    this._removeSubviewByModel(model, this.close)
  }

, detachSubviewByModel: function detachSubviewByModel(model){
    this._removeSubviewByModel(model, this.detachSubview)
  }

}

extendView = function extendView(view){
  return view.extend(Ribcage)
}

module.exports = extendView
<commit_msg>Error when a view isn’t passed to {app,pre}pend<commit_after>'use strict'

var _ = require('lodash')
  , raf = require('raf')
  , Ribcage
  , extendView

Ribcage = {
  initialize: function initialize(opts){
    opts = opts || {}

    // if we need to load data before rendering, do it
    // otherwise, assume we have the data already
    this._dataLoaded = typeof this.loadData !== 'function'

    this._nukeOnRender = opts._nukeOnRender
    // delete would turn this into a "slow object" in V8
    // we can't set to null, b/c a state model can reject extra properties
    if (_.has(opts, '_nukeOnRender')) opts = _.omit(opts, '_nukeOnRender')

    // backbone 1.1+ doesn't auto-set this.options
    this.options = opts

    if (this.beforeInit) this.beforeInit(opts)

    this.template = this.template || opts.template

    if (!this.template) {
      this.template = function template(){
        return ''
      }
    }

    if (this.afterInit) this.afterInit(opts)

    this.render()
  }

, context: function context(){
    var model = this.model ? this.model.toJSON() : {}
      , state = this.state ? this.state.toJSON() : {}

    return _.extend({}, this.options, model, state)
  }

, render: function render(){
    var self = this
      , model = this.model

    if (typeof this.bindEvents === 'function') {
      this.bindEvents()
    }

    if (!this._dataLoaded && typeof this.loadData === 'function') {
      return this.loadData(function dataLoaded(){
        self._dataLoaded = true
        self.render()
      })
    }

    // closing destroys the el, might need to recreate it
    if (!this.el) {
      this._ensureElement()
    }

    if (this.beforeRender) {
      this.beforeRender()
    }

    // Maintainers of legacy code might want to use this
    // but certainly not YOU, young grasshopper!
    if (this._nukeOnRender) {
      this.closeSubviews()
      this.$el.empty()
    }

    if (this.beforeTemplating) {
      model = this.beforeTemplating()
    }

    if (this.context) {
      model = this.context()
    }

    this.$el.html(this.template(model))

    // As soon as the view is bound to DOM, we need to delegate events and re-render all
    // subviews to keep events intact. -cstumph
    this.delegateEvents()
    this.eachSubview(function eachSubviewInRender(view){
      view.render()
    })

    // I'm not happy deferring here, but backbone's
    // event system is based on the DOM, so my hands
    // are tied. - Daniel
    _.defer(function deferSoTheDOMCanCatchup(){
      self.trigger('afterRender')
    })

    if (this.afterRender) {
      this.afterRender()
    }

    return this
  }

, proxy: function proxy(name, view){
    this.listenTo(view, name, function proxiedEventCallback(){
      var args = Array.prototype.slice.call(arguments, 0)
      args.splice(0, 0, name)
      this.trigger.apply(this, args)
    })
  }

, eachSubview: function eachSubview(iterator, context){
    _.each(this.subviews, iterator, context || this)
  }

, _attachSubView: function _attachSubView(view){
    var viewId

    if (!view) throw new Error('view must be passed.')
    this.subviews = this.subviews || {}
    this.subviewByModelId = this.subviewByModelId || {}

    this.subviews[view.cid] = view

    if (view.model) {
      viewId = view.model.id || view.model.cid
      if (!this.subviewByModelId[viewId]) this.subviewByModelId[viewId] = []

      this.subviewByModelId[viewId].push(view)
    }

    return view
  }

, appendSubview: function appendSubview(view, el){
    el || (el = this.$el)

    this._attachSubView(view)

    // closing a view will remove the el, so ensure we have one before re-attaching
    if (view.options.render || !view.el) view.render()
    el.append(view.el)

    _.defer(function deferSoTheDOMCanCatchup(){
      view.trigger('afterAppend', view)
    })

    if (view.afterAppend) {
      view.afterAppend()
    }
  }

, prependSubview: function prependSubview(view, el){
    el || (el = this.$el)

    this._attachSubView(view)

    // closing a view will remove the el, so ensure we have one before re-attaching
    if (view.options.renderOnAppend || !view.el) view.render()
    el.prepend(view.el)

    _.defer(function deferSoTheDOMCanCatchup(){
      view.trigger('afterPrepend', view)
    })

    if (view.afterPrepend) {
      view.afterPrepend()
    }
  }

, appendSubviews: function appendSubviews(views, el, callback){
    var fragment = document.createDocumentFragment()

    el || (el = this.$el)

    _.each(views, function appendEachView(view){
      this._attachSubView(view)

      // closing a view will remove the el, so ensure we have one before re-attaching
      if (view.options.renderOnAppend || !view.el) view.render()
      fragment.appendChild(view.el)

      _.defer(function deferSoTheDOMCanCatchup(){
        view.trigger('afterAppend', view)
      })

      if (view.afterAppend) {
        view.afterAppend()
      }
    }, this)

    raf(function onFrame(){
      el[0].appendChild(fragment)
      if (_.isFunction(callback)) callback(views)
    })
  }

, batchAppendSubviews: function batchAppendSubviews(views, el, batchCount, batchCallback, callback){
    var self = this
      , batches = _(views)
                  .groupBy(function groupIntoBatches(view, index){
                    return Math.floor(index / batchCount)
                  })
                  .toArray()
                  .valueOf()
      , appendNextBatch = function appendNextBatch(){
      var batchesLeft = batches.length
        , viewBatch = batchesLeft ? batches.shift() : false

      // with no batches left, just return early
      if (!batchesLeft) {
        // if we have a final callback, call that.
        return typeof callback === 'function'
          ? void callback()
          : void 0
      }

      self.appendSubviews(viewBatch, el, function subviewsAppended(){
        if (typeof batchCallback === 'function') {
          batchCallback(viewBatch)
        }

        appendNextBatch()
      })
    }

    appendNextBatch()
  }

, close: function close(options, callback){
    options || (options = {})

    if (this.beforeClose) this.beforeClose()

    this.closeSubviews({keepDom: true}, _.bind(function onSubviewsClosed(){
      this.stopListening()

      // when the subviews are closed, close the parent
      // keep the DOM elements, b/c it's save to assume that all child DOM
      // is containted by the parent DOM container. This allows us to reduce
      // many DOM removal calls to just one.
      if (!options.keepDom) {
        raf(function onFrame(){
          // remove the from the DOM
          if (this.$el) this.$el.remove()
          // destroy our reference to the DOM node
          this.$el = null
          this.el = null
          if (_.isFunction(callback)) callback()
        }.bind(this))
      }
      else if (_.isFunction(callback)) callback()
    }, this))
  }

, closeSubviews: function closeSubviews(options, callback){
    var subviewCount = _.size(this.subviews)
      , done

    if (_.isFunction(callback)){
      // if there are no subviews to close, just call the callback
      if (!subviewCount) return void callback()
      else done = _.after(subviewCount, callback)
    }

    this.eachSubview(function closeEachSubview(subview){
      subview.close(options, done)
    })

    // empty out our lists of subviews
    this.subviews = {}
    this.subviewByModelId = {}
  }

, detachSubview: function detachSubview(view){
    var msg

    if (this.subviews) {
      if (view && !this.subviews[view.cid]) {
        msg = 'View not found in ' + this.className + '\'s subviews: ' + view.className

        if (view.model) msg += '\n\n' + view.model.toJSON()

        throw new Error(msg)
      }

      // delete makes this into a "slow object" in V8
      // but that's okay b/c any perf gains we'd get would be lost by having to
      // itterate over subviews to remove falsey values.
      delete this.subviews[view.cid]
    }

    view.$el.detach()
  }

, _removeSubviewByModel: function _removeSubviewByModel(model, method){
    var id = model.id

    if (this.subviewByModelId){
      if (!id || !this.subviewByModelId[id]){
        throw new Error('No views with ' + id + ' model id found in ' + this.className + ' subviews')
      }

      _.each(this.subviewByModelId[id], function eachSubviewById(view){
        method.call(this, view)
      }, this)

      // delete would turn this into a "slow object" in V8, so just set to null
      this.subviewByModelId[id] = null
    }
  }

, closeSubviewsByModel: function closeSubviewsByModel(model){
    this._removeSubviewByModel(model, this.close)
  }

, detachSubviewByModel: function detachSubviewByModel(model){
    this._removeSubviewByModel(model, this.detachSubview)
  }

}

extendView = function extendView(view){
  return view.extend(Ribcage)
}

module.exports = extendView
<|endoftext|>


<commit_before>var elementList = [];

function init() {

  var elementNumber = 0;

  $('.fanoos').each(function() {

    $(this).addClass('animated').css("animation-play-state", "paused");

    if ( $(this).attr('data-fanoos-id') == null || $(this).attr('data-fanoos-id').length == 0) {
      var fanoosId = 'fanoosElement' + elementNumber;
      $(this).attr('data-fanoos-id', fanoosId);
    } else {
      var fanoosId = $(this).attr('data-fanoos-id');
    };

    console.log(fanoosId)
    console.log($(this).offset().top);

    elementNumber++;
  })

}

function action(element) {
  element.css("animation-play-state", "running");
}

init()

$('#action1').on('click', function(e) {

  var element = $('.fadeInLeft');

  action(element);
  e.preventDefault();
})

$('#action2').on('click', function(e) {

    var element = $('.tada');

    action(element);
  e.preventDefault();
})

$('#action3').on('click', function(e) {

    var element = $('.fadeInRight');

    action(element);
  e.preventDefault();
})
<commit_msg>MVP script<commit_after>function init() {

  $('.fanoos').each(function() {
    $(this).addClass('animated').css("animation-play-state", "paused");
  })

}

function action(element) {
  element.css("animation-play-state", "running");
}

init()

$('#action').on('click', function(e) {

  var element = $('.fadeInLeft');

  action(element);
  e.preventDefault();
})
<|endoftext|>


<commit_before>/**
 * libjass
 *
 * https://github.com/Arnavion/libjass
 *
 * Copyright 2013 Arnav Singh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var childProcess = require("child_process");
var fs = require("fs");
var path = require("path");

namespace("_watch", function () {
	task("runTask", ["_test:run[false]", "_default:writeSourceMap"], function () { });

	task("run", [], function () {
		console.log("[" + this.fullName + "]");

		var spawnSubProcess = function () {
			var pathToJake = path.resolve("./node_modules/.bin/jake");
			var subProcess = childProcess.exec(pathToJake + " _watch:runUntilError --trace", { stdio: "inherit" });
			subProcess.stdout.pipe(process.stdout);
			subProcess.stderr.pipe(process.stderr);
			subProcess.addListener("exit", function (code, signal) {
				spawnSubProcess();
			});
		};

		spawnSubProcess();
	}, { async: true });

	task("runUntilError", ["_typescript:getCompilerFactory"], function () {
		console.log("[" + this.fullName + "]");

		var tasksToReEnable = [];
		var stack = ["_watch:runTask"];
		while (stack.length > 0) {
			var next = stack.shift();
			if (next.indexOf("[") !== -1) {
				next = next.substr(0, next.indexOf("["));
			}

			if (next !== "_typescript:getCompilerFactory" && tasksToReEnable.indexOf(jake.Task[next]) === -1) {
				tasksToReEnable.push(jake.Task[next]);

				stack.push.apply(stack, jake.Task[next].prereqs);
			}
		}

		var timeoutId = null;

		fs.watch(".", function (event, filename) {
			if (filename === null) {
				return;
			}

			var extension = path.extname(filename);
			if (extension !== ".ts") {
				return;
			}

			console.log(event, filename, JSON.stringify([].slice.call(arguments, 0)));

			clearTimeout(timeoutId);

			timeoutId = setTimeout(function () {
				tasksToReEnable.forEach(function (task) { task.reenable(); });
				jake.Task["_watch:runTask"].invoke();
			}, 1000);
		});
	});
});
<commit_msg>Revert "Run watch sub-process and mocha with inherited stdio handles for colored output."<commit_after>/**
 * libjass
 *
 * https://github.com/Arnavion/libjass
 *
 * Copyright 2013 Arnav Singh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var childProcess = require("child_process");
var fs = require("fs");
var path = require("path");

namespace("_watch", function () {
	task("runTask", ["_test:run[false]", "_default:writeSourceMap"], function () { });

	task("run", [], function () {
		console.log("[" + this.fullName + "]");

		var spawnSubProcess = function () {
			var pathToJake = path.resolve("./node_modules/.bin/jake");
			var subProcess = childProcess.exec(pathToJake + " _watch:runUntilError --trace");
			subProcess.stdout.pipe(process.stdout);
			subProcess.stderr.pipe(process.stderr);
			subProcess.addListener("exit", function (code, signal) {
				spawnSubProcess();
			});
		};

		spawnSubProcess();
	}, { async: true });

	task("runUntilError", ["_typescript:getCompilerFactory"], function () {
		console.log("[" + this.fullName + "]");

		var tasksToReEnable = [];
		var stack = ["_watch:runTask"];
		while (stack.length > 0) {
			var next = stack.shift();
			if (next.indexOf("[") !== -1) {
				next = next.substr(0, next.indexOf("["));
			}

			if (next !== "_typescript:getCompilerFactory" && tasksToReEnable.indexOf(jake.Task[next]) === -1) {
				tasksToReEnable.push(jake.Task[next]);

				stack.push.apply(stack, jake.Task[next].prereqs);
			}
		}

		var timeoutId = null;

		fs.watch(".", function (event, filename) {
			if (filename === null) {
				return;
			}

			var extension = path.extname(filename);
			if (extension !== ".ts") {
				return;
			}

			console.log(event, filename, JSON.stringify([].slice.call(arguments, 0)));

			clearTimeout(timeoutId);

			timeoutId = setTimeout(function () {
				tasksToReEnable.forEach(function (task) { task.reenable(); });
				jake.Task["_watch:runTask"].invoke();
			}, 1000);
		});
	});
});
<|endoftext|>


<commit_before>require(['jquery',
    'underscore',
    'backbone',
    'bootstrap',
    'arches',
    'select2',
    'views/search/term-filter',
    'views/search/map-filter',
    'views/search/time-filter',
    'views/search/search-results',
    'knockout',
    'plugins/bootstrap-slider/bootstrap-slider.min',
    'views/forms/sections/branch-list',
    'resource-types',
    'openlayers',
    'bootstrap-datetimepicker',
    'plugins/knockout-select2'],
    function($, _, Backbone, bootstrap, arches, select2, TermFilter, MapFilter, TimeFilter, SearchResults, ko, Slider, BranchList, resourceTypes, ol) {
    $(document).ready(function() {
        var wkt = new ol.format.WKT();

        var SearchView = Backbone.View.extend({
            el: $('body'),
            updateRequest: '',

            events: {
                'click #view-saved-searches': 'showSavedSearches',
                'click #clear-search': 'clear',
                'click #map-filter-button': 'toggleMapFilter',
                'click #time-filter-button': 'toggleTimeFilter',
                'click a.dataexport': 'exportSearch'
            },

            initialize: function(options) {
                var mapFilterText, timeFilterText;
                var self = this;

                this.termFilter = new TermFilter({
                    el: $.find('input.resource_search_widget')[0]
                });
                this.termFilter.on('change', function(){
                    if($('#saved-searches').is(":visible")){
                        this.hideSavedSearches();
                    }
                }, this);
                this.termFilter.on('filter-removed', function(item){
                    if(item.text === mapFilterText){
                        this.mapFilter.clear();
                    }
                    if(item.text === timeFilterText){
                        this.timeFilter.clear();
                    }
                }, this);
                this.termFilter.on('filter-inverted', function(item){
                    if(item.text === mapFilterText){
                        this.mapFilter.query.filter.inverted(item.inverted);
                    }
                    if(item.text === timeFilterText){
                        this.timeFilter.query.filter.inverted(item.inverted);
                    }
                }, this);

                this.mapFilter = new MapFilter({
                    el: $('#map-filter-container')[0]
                });
                this.mapFilter.on('enabled', function(enabled, inverted){
                    if(enabled){
                        this.termFilter.addTag(mapFilterText, inverted);
                    }else{
                        this.termFilter.removeTag(mapFilterText);
                    }
                }, this);

                this.timeFilter = new TimeFilter({
                    el: $('#time-filter-container')[0]
                });
                this.timeFilter.on('enabled', function(enabled, inverted){
                    if(enabled){
                        this.termFilter.addTag(timeFilterText, inverted);
                    }else{
                        this.termFilter.removeTag(timeFilterText);
                    }
                }, this);

                this.searchResults = new SearchResults({
                    el: $('#search-results-container')[0]
                });
                this.searchResults.on('mouseover', function(resourceid){
                    this.mapFilter.selectFeatureById(resourceid);
                }, this);
                this.searchResults.on('mouseout', function(){
                    this.mapFilter.unselectAllFeatures();
                }, this);
                this.searchResults.on('find_on_map', function(resourceid, data){
                    var extent,
                        expand = !this.mapFilter.expanded();
                    if (expand) {
                        this.mapFilter.expanded(true);
                    }

                    _.each(data.geometries, function (geometryData) {
                        var geomExtent = wkt.readGeometry(geometryData.label).getExtent();
                        geomExtent = ol.extent.applyTransform(geomExtent, ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
                        extent = extent ? ol.extent.extend(extent, geomExtent) : geomExtent;
                    });
                    if (extent) {
                        _.delay(function() {
                            self.mapFilter.zoomToExtent(extent);
                        }, expand ? 600 : 0);
                    }
                }, this);

                mapFilterText = this.mapFilter.$el.data().filtertext;
                timeFilterText = this.timeFilter.$el.data().filtertext;

                self.isNewQuery = true;
                this.searchQuery = {
                    queryString: function(){
                        var params = {
                            page: self.searchResults.page(),
                            termFilter: ko.toJSON(self.termFilter.query.filter.terms()),
                            temporalFilter: ko.toJSON({
                                year_min_max: self.timeFilter.query.filter.year_min_max(),
                                filters: self.timeFilter.query.filter.filters(),
                                inverted: self.timeFilter.query.filter.inverted()
                            }),
                            spatialFilter: ko.toJSON(self.mapFilter.query.filter),
                            mapExpanded: self.mapFilter.expanded(),
                            timeExpanded: self.timeFilter.expanded()
                        };
                        if (self.termFilter.query.filter.terms().length === 0 &&
                            self.timeFilter.query.filter.year_min_max().length === 0 &&
                            self.timeFilter.query.filter.filters().length === 0 &&
                            self.mapFilter.query.filter.geometry.coordinates().length === 0) {
                            params.no_filters = true;
                        }

                        params.include_ids = self.isNewQuery;
                        return $.param(params).split('+').join('%20');
                    },
                    changed: ko.pureComputed(function(){
                        var ret = ko.toJSON(this.termFilter.query.changed()) +
                            ko.toJSON(this.timeFilter.query.changed()) +
                            ko.toJSON(this.mapFilter.query.changed());
                        return ret;
                    }, this).extend({ rateLimit: 200 })
                };

                this.getSearchQuery();

                this.searchResults.page.subscribe(function(){
                    self.doQuery();
                });

                this.searchQuery.changed.subscribe(function(){
                    self.isNewQuery = true;
                    self.searchResults.page(1);
                    self.doQuery();
                });
            },

            doQuery: function () {
                var self = this;
                var queryString = this.searchQuery.queryString();
                if (this.updateRequest) {
                    this.updateRequest.abort();
                }

                $('.loading-mask').show();
                window.history.pushState({}, '', '?'+queryString);

                this.updateRequest = $.ajax({
                    type: "GET",
                    url: arches.urls.search_results,
                    data: queryString,
                    success: function(results){
                        var data = self.searchResults.updateResults(results);
                        self.mapFilter.highlightFeatures(data, $('.search-result-all-ids').data('results'));
                        self.mapFilter.applyBuffer();
                        self.isNewQuery = false;
                        $('.loading-mask').hide();
                    },
                    error: function(){}
                });
            },

            showSavedSearches: function(){
                this.clear();
                $('#saved-searches').slideDown('slow');
                $('#search-results').slideUp('slow');
                this.mapFilter.expanded(false);
                this.timeFilter.expanded(false);
            },

            hideSavedSearches: function(){
                $('#saved-searches').slideUp('slow');
                $('#search-results').slideDown('slow');
            },

            toggleMapFilter: function(){
                if($('#saved-searches').is(":visible")){
                    this.doQuery();
                    this.hideSavedSearches();
                }
                this.mapFilter.expanded(!this.mapFilter.expanded());
                window.history.pushState({}, '', '?'+this.searchQuery.queryString());
            },

            toggleTimeFilter: function(){
                if($('#saved-searches').is(":visible")){
                    this.doQuery();
                    this.hideSavedSearches();
                }
                this.timeFilter.expanded(!this.timeFilter.expanded());
                window.history.pushState({}, '', '?'+this.searchQuery.queryString());
            },

            getSearchQuery: function(){
                var doQuery = false;
                var query = _.chain(decodeURIComponent(location.search).slice(1).split('&') )
                    // Split each array item into [key, value]
                    // ignore empty string if search is empty
                    .map(function(item) { if (item) return item.split('='); })
                    // Remove undefined in the case the search is empty
                    .compact()
                    // Turn [key, value] arrays into object parameters
                    .object()
                    // Return the value of the chain operation
                    .value();

                if('page' in query){
                    query.page = JSON.parse(query.page);
                    doQuery = true;
                }
                this.searchResults.restoreState(query.page);

                if('termFilter' in query){
                    query.termFilter = JSON.parse(query.termFilter);
                    doQuery = true;
                }
                this.termFilter.restoreState(query.termFilter);

                if('temporalFilter' in query){
                    query.temporalFilter = JSON.parse(query.temporalFilter);
                    doQuery = true;
                }
                if('timeExpanded' in query){
                    query.timeExpanded = JSON.parse(query.timeExpanded);
                    doQuery = true;
                }
                this.timeFilter.restoreState(query.temporalFilter, query.timeExpanded);

                if('spatialFilter' in query){
                    query.spatialFilter = JSON.parse(query.spatialFilter);
                    doQuery = true;
                }
                if('mapExpanded' in query){
                    query.mapExpanded = JSON.parse(query.mapExpanded);
                    doQuery = true;
                }
                this.mapFilter.restoreState(query.spatialFilter, query.mapExpanded);

                if(doQuery){
                    this.doQuery();
                    this.hideSavedSearches();
                }

            },

            clear: function(){
                this.mapFilter.clear();
                this.timeFilter.clear();
                this.termFilter.clear();
            },

            exportSearch: function(e) {
                var export_format = e.currentTarget.id,
                    _href = $("a.dataexport").attr("href"),
                    format = 'export=' + export_format,
                    params_with_page = this.searchQuery.queryString(),
                    page_number_regex = /page=[0-9]+/;
                    params = params_with_page.replace(page_number_regex, format);
                $("a.dataexport").attr("href", arches.urls.search_results_export + '?' + params);
            }
        });
        new SearchView();
    });
});<commit_msg>increasing delay...<commit_after>require(['jquery',
    'underscore',
    'backbone',
    'bootstrap',
    'arches',
    'select2',
    'views/search/term-filter',
    'views/search/map-filter',
    'views/search/time-filter',
    'views/search/search-results',
    'knockout',
    'plugins/bootstrap-slider/bootstrap-slider.min',
    'views/forms/sections/branch-list',
    'resource-types',
    'openlayers',
    'bootstrap-datetimepicker',
    'plugins/knockout-select2'],
    function($, _, Backbone, bootstrap, arches, select2, TermFilter, MapFilter, TimeFilter, SearchResults, ko, Slider, BranchList, resourceTypes, ol) {
    $(document).ready(function() {
        var wkt = new ol.format.WKT();

        var SearchView = Backbone.View.extend({
            el: $('body'),
            updateRequest: '',

            events: {
                'click #view-saved-searches': 'showSavedSearches',
                'click #clear-search': 'clear',
                'click #map-filter-button': 'toggleMapFilter',
                'click #time-filter-button': 'toggleTimeFilter',
                'click a.dataexport': 'exportSearch'
            },

            initialize: function(options) {
                var mapFilterText, timeFilterText;
                var self = this;

                this.termFilter = new TermFilter({
                    el: $.find('input.resource_search_widget')[0]
                });
                this.termFilter.on('change', function(){
                    if($('#saved-searches').is(":visible")){
                        this.hideSavedSearches();
                    }
                }, this);
                this.termFilter.on('filter-removed', function(item){
                    if(item.text === mapFilterText){
                        this.mapFilter.clear();
                    }
                    if(item.text === timeFilterText){
                        this.timeFilter.clear();
                    }
                }, this);
                this.termFilter.on('filter-inverted', function(item){
                    if(item.text === mapFilterText){
                        this.mapFilter.query.filter.inverted(item.inverted);
                    }
                    if(item.text === timeFilterText){
                        this.timeFilter.query.filter.inverted(item.inverted);
                    }
                }, this);

                this.mapFilter = new MapFilter({
                    el: $('#map-filter-container')[0]
                });
                this.mapFilter.on('enabled', function(enabled, inverted){
                    if(enabled){
                        this.termFilter.addTag(mapFilterText, inverted);
                    }else{
                        this.termFilter.removeTag(mapFilterText);
                    }
                }, this);

                this.timeFilter = new TimeFilter({
                    el: $('#time-filter-container')[0]
                });
                this.timeFilter.on('enabled', function(enabled, inverted){
                    if(enabled){
                        this.termFilter.addTag(timeFilterText, inverted);
                    }else{
                        this.termFilter.removeTag(timeFilterText);
                    }
                }, this);

                this.searchResults = new SearchResults({
                    el: $('#search-results-container')[0]
                });
                this.searchResults.on('mouseover', function(resourceid){
                    this.mapFilter.selectFeatureById(resourceid);
                }, this);
                this.searchResults.on('mouseout', function(){
                    this.mapFilter.unselectAllFeatures();
                }, this);
                this.searchResults.on('find_on_map', function(resourceid, data){
                    var extent,
                        expand = !this.mapFilter.expanded();
                    if (expand) {
                        this.mapFilter.expanded(true);
                    }

                    _.each(data.geometries, function (geometryData) {
                        var geomExtent = wkt.readGeometry(geometryData.label).getExtent();
                        geomExtent = ol.extent.applyTransform(geomExtent, ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
                        extent = extent ? ol.extent.extend(extent, geomExtent) : geomExtent;
                    });
                    if (extent) {
                        _.delay(function() {
                            self.mapFilter.zoomToExtent(extent);
                        }, expand ? 700 : 0);
                    }
                }, this);

                mapFilterText = this.mapFilter.$el.data().filtertext;
                timeFilterText = this.timeFilter.$el.data().filtertext;

                self.isNewQuery = true;
                this.searchQuery = {
                    queryString: function(){
                        var params = {
                            page: self.searchResults.page(),
                            termFilter: ko.toJSON(self.termFilter.query.filter.terms()),
                            temporalFilter: ko.toJSON({
                                year_min_max: self.timeFilter.query.filter.year_min_max(),
                                filters: self.timeFilter.query.filter.filters(),
                                inverted: self.timeFilter.query.filter.inverted()
                            }),
                            spatialFilter: ko.toJSON(self.mapFilter.query.filter),
                            mapExpanded: self.mapFilter.expanded(),
                            timeExpanded: self.timeFilter.expanded()
                        };
                        if (self.termFilter.query.filter.terms().length === 0 &&
                            self.timeFilter.query.filter.year_min_max().length === 0 &&
                            self.timeFilter.query.filter.filters().length === 0 &&
                            self.mapFilter.query.filter.geometry.coordinates().length === 0) {
                            params.no_filters = true;
                        }

                        params.include_ids = self.isNewQuery;
                        return $.param(params).split('+').join('%20');
                    },
                    changed: ko.pureComputed(function(){
                        var ret = ko.toJSON(this.termFilter.query.changed()) +
                            ko.toJSON(this.timeFilter.query.changed()) +
                            ko.toJSON(this.mapFilter.query.changed());
                        return ret;
                    }, this).extend({ rateLimit: 200 })
                };

                this.getSearchQuery();

                this.searchResults.page.subscribe(function(){
                    self.doQuery();
                });

                this.searchQuery.changed.subscribe(function(){
                    self.isNewQuery = true;
                    self.searchResults.page(1);
                    self.doQuery();
                });
            },

            doQuery: function () {
                var self = this;
                var queryString = this.searchQuery.queryString();
                if (this.updateRequest) {
                    this.updateRequest.abort();
                }

                $('.loading-mask').show();
                window.history.pushState({}, '', '?'+queryString);

                this.updateRequest = $.ajax({
                    type: "GET",
                    url: arches.urls.search_results,
                    data: queryString,
                    success: function(results){
                        var data = self.searchResults.updateResults(results);
                        self.mapFilter.highlightFeatures(data, $('.search-result-all-ids').data('results'));
                        self.mapFilter.applyBuffer();
                        self.isNewQuery = false;
                        $('.loading-mask').hide();
                    },
                    error: function(){}
                });
            },

            showSavedSearches: function(){
                this.clear();
                $('#saved-searches').slideDown('slow');
                $('#search-results').slideUp('slow');
                this.mapFilter.expanded(false);
                this.timeFilter.expanded(false);
            },

            hideSavedSearches: function(){
                $('#saved-searches').slideUp('slow');
                $('#search-results').slideDown('slow');
            },

            toggleMapFilter: function(){
                if($('#saved-searches').is(":visible")){
                    this.doQuery();
                    this.hideSavedSearches();
                }
                this.mapFilter.expanded(!this.mapFilter.expanded());
                window.history.pushState({}, '', '?'+this.searchQuery.queryString());
            },

            toggleTimeFilter: function(){
                if($('#saved-searches').is(":visible")){
                    this.doQuery();
                    this.hideSavedSearches();
                }
                this.timeFilter.expanded(!this.timeFilter.expanded());
                window.history.pushState({}, '', '?'+this.searchQuery.queryString());
            },

            getSearchQuery: function(){
                var doQuery = false;
                var query = _.chain(decodeURIComponent(location.search).slice(1).split('&') )
                    // Split each array item into [key, value]
                    // ignore empty string if search is empty
                    .map(function(item) { if (item) return item.split('='); })
                    // Remove undefined in the case the search is empty
                    .compact()
                    // Turn [key, value] arrays into object parameters
                    .object()
                    // Return the value of the chain operation
                    .value();

                if('page' in query){
                    query.page = JSON.parse(query.page);
                    doQuery = true;
                }
                this.searchResults.restoreState(query.page);

                if('termFilter' in query){
                    query.termFilter = JSON.parse(query.termFilter);
                    doQuery = true;
                }
                this.termFilter.restoreState(query.termFilter);

                if('temporalFilter' in query){
                    query.temporalFilter = JSON.parse(query.temporalFilter);
                    doQuery = true;
                }
                if('timeExpanded' in query){
                    query.timeExpanded = JSON.parse(query.timeExpanded);
                    doQuery = true;
                }
                this.timeFilter.restoreState(query.temporalFilter, query.timeExpanded);

                if('spatialFilter' in query){
                    query.spatialFilter = JSON.parse(query.spatialFilter);
                    doQuery = true;
                }
                if('mapExpanded' in query){
                    query.mapExpanded = JSON.parse(query.mapExpanded);
                    doQuery = true;
                }
                this.mapFilter.restoreState(query.spatialFilter, query.mapExpanded);

                if(doQuery){
                    this.doQuery();
                    this.hideSavedSearches();
                }

            },

            clear: function(){
                this.mapFilter.clear();
                this.timeFilter.clear();
                this.termFilter.clear();
            },

            exportSearch: function(e) {
                var export_format = e.currentTarget.id,
                    _href = $("a.dataexport").attr("href"),
                    format = 'export=' + export_format,
                    params_with_page = this.searchQuery.queryString(),
                    page_number_regex = /page=[0-9]+/;
                    params = params_with_page.replace(page_number_regex, format);
                $("a.dataexport").attr("href", arches.urls.search_results_export + '?' + params);
            }
        });
        new SearchView();
    });
});<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
module.exports = function addStyle(cssCode) {
	if(typeof DEBUG !== "undefined" && DEBUG) {
		if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
	}
	var styleElement = document.createElement("style");
	styleElement.type = "text/css";
	var head = document.getElementsByTagName("head")[0];
	head.appendChild(styleElement);
	if (styleElement.styleSheet) {
		styleElement.styleSheet.cssText = cssCode;
	} else {
		styleElement.appendChild(document.createTextNode(cssCode));
	}
	if(module.hot) {
		return function(cssCode) {
			if(typeof cssCode === "string") {
				if (styleElement.styleSheet) {
					styleElement.styleSheet.cssText = cssCode;
				} else {
					styleElement.childNodes[0].nodeValue = cssCode;
				}
			} else {
				head.removeChild(styleElement);
			}
		};
	}
}
<commit_msg>Add missing semicolon<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
module.exports = function addStyle(cssCode) {
	if(typeof DEBUG !== "undefined" && DEBUG) {
		if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
	}
	var styleElement = document.createElement("style");
	styleElement.type = "text/css";
	var head = document.getElementsByTagName("head")[0];
	head.appendChild(styleElement);
	if (styleElement.styleSheet) {
		styleElement.styleSheet.cssText = cssCode;
	} else {
		styleElement.appendChild(document.createTextNode(cssCode));
	}
	if(module.hot) {
		return function(cssCode) {
			if(typeof cssCode === "string") {
				if (styleElement.styleSheet) {
					styleElement.styleSheet.cssText = cssCode;
				} else {
					styleElement.childNodes[0].nodeValue = cssCode;
				}
			} else {
				head.removeChild(styleElement);
			}
		};
	}
};
<|endoftext|>


<commit_before>/*!
 Author: Stephen Korecky
 Website: http://stephenkorecky.com
 Plugin Website: http://github.com/skorecky/Add-Clear
 Version: 2.0.6

 The MIT License (MIT)

 Copyright (c) 2015 Stephen Korecky

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

;(function($, window, document, undefined) {

	// Create the defaults once
	var pluginName = "addClear",
		defaults = {
			closeSymbol: "✖",
			color: "#CCC",
			top: 1,
			right: 4,
			returnFocus: true,
			showOnLoad: false,
			onClear: null,
			hideOnBlur: false,
			tabbable: true,
			paddingRight: '20px'
		};

	// The actual plugin constructor
	function Plugin(element, options) {
		this.element = element;

		this.options = $.extend({}, defaults, options);

		this._defaults = defaults;
		this._name = pluginName;

		this.init();
	}

	Plugin.prototype = {

		init: function() {
			var $this = $(this.element),
					$clearButton,
					me = this,
					options = this.options;

			$this.wrap("");
			var tabIndex = options.tabbable ? "" : " tabindex='-1'";
			$clearButton = $("" + options.closeSymbol + "");
			$this.after($clearButton);
			$this.next().css({
				color: options.color,
				'text-decoration': 'none',
				display: 'none',
				'line-height': 1,
				overflow: 'hidden',
				position: 'absolute',
				right: options.right,
				top: options.top
			}, this);

			if (options.paddingRight) {
				$this.css({
					'padding-right': options.paddingRight
				});
			}

			if ($this.val().length >= 1 && options.showOnLoad === true) {
				$clearButton.css({display: 'block'});
			}

			$this.focus(function() {
				if ($(this).val().length >= 1) {
					$clearButton.css({display: 'block'});
				}
			});

			$this.blur(function(e) {
				if (options.hideOnBlur) {
					setTimeout(function() {
						var relatedTarget = e.relatedTarget || e.explicitOriginalTarget || document.activeElement;
						if (relatedTarget !== $clearButton[0]) {
							$clearButton.css({display: 'none'});
						}
					}, 0);
				}
			});

			var handleUserInput = function() {
				if ($(this).val().length >= 1) {
					$clearButton.css({display: 'block'});
				} else {
					$clearButton.css({display: 'none'});
				}
			};

			var handleInput = function () {
			    $this.off('keyup', handleUserInput);
				$this.off('cut', handleUserInput);
				handleInput = handleUserInput;
				handleUserInput.call(this);
			};

			$this.on('keyup', handleUserInput);

			$this.on('cut', function () {
				var self = this;
				setTimeout(function () {
					handleUserInput.call(self);
				}, 0);
			});

			$this.on('input', function () {
				handleInput.call(this);
			});

			if (options.hideOnBlur) {
				$clearButton.blur(function () {
					$clearButton.css({display: 'none'});
				});
			}

			$clearButton.click(function(e) {
				var $input = $(me.element);
				$input.val("");
				$(this).css({display: 'none'});
				if (options.returnFocus === true) {
					$input.focus();
				}
				if (options.onClear) {
					options.onClear($input);
				}
				e.preventDefault();
			});
		}

	};

	$.fn[pluginName] = function(options) {
		return this.each(function() {
			if (!$.data(this, "plugin_" + pluginName)) {
				$.data(this, "plugin_" + pluginName,
					new Plugin(this, options));
			}
		});
	};

})(jQuery, window, document);
<commit_msg>- added default settings: lineHeight, display<commit_after>/*!
 Author: Stephen Korecky
 Website: http://stephenkorecky.com
 Plugin Website: http://github.com/skorecky/Add-Clear
 Version: 2.0.6

 The MIT License (MIT)

 Copyright (c) 2015 Stephen Korecky

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

;(function($, window, document, undefined) {

	// Create the defaults once
	var pluginName = "addClear",
		defaults = {
			closeSymbol: "✖",
			color: "#CCC",
			top: 1,
			right: 4,
			returnFocus: true,
			showOnLoad: false,
			onClear: null,
			hideOnBlur: false,
			tabbable: true,
			paddingRight: '20px',
			lineHeight: 1,
			display: "block"
		};

	// The actual plugin constructor
	function Plugin(element, options) {
		this.element = element;

		this.options = $.extend({}, defaults, options);

		this._defaults = defaults;
		this._name = pluginName;

		this.init();
	}

	Plugin.prototype = {

		init: function() {
			var $this = $(this.element),
					$clearButton,
					me = this,
					options = this.options;

			$this.wrap("");
			var tabIndex = options.tabbable ? "" : " tabindex='-1'";
			$clearButton = $("" + options.closeSymbol + "");
			$this.after($clearButton);
			$this.next().css({
				color: options.color,
				'text-decoration': 'none',
				display: 'none',
				overflow: 'hidden',
				position: 'absolute',
				right: options.right,
				top: options.top
			}, this);

			if (options.paddingRight) {
				$this.css({
					'padding-right': options.paddingRight
				});
			}

			if ($this.val().length >= 1 && options.showOnLoad === true) {
				$clearButton.css({display: display});
			}

			$this.focus(function() {
				if ($(this).val().length >= 1) {
					$clearButton.css({display: display});
				}
			});

			$this.blur(function(e) {
				if (options.hideOnBlur) {
					setTimeout(function() {
						var relatedTarget = e.relatedTarget || e.explicitOriginalTarget || document.activeElement;
						if (relatedTarget !== $clearButton[0]) {
							$clearButton.css({display: 'none'});
						}
					}, 0);
				}
			});

			var handleUserInput = function() {
				if ($(this).val().length >= 1) {
					$clearButton.css({display: display});
				} else {
					$clearButton.css({display: 'none'});
				}
			};

			var handleInput = function () {
			    $this.off('keyup', handleUserInput);
				$this.off('cut', handleUserInput);
				handleInput = handleUserInput;
				handleUserInput.call(this);
			};

			$this.on('keyup', handleUserInput);

			$this.on('cut', function () {
				var self = this;
				setTimeout(function () {
					handleUserInput.call(self);
				}, 0);
			});

			$this.on('input', function () {
				handleInput.call(this);
			});

			if (options.hideOnBlur) {
				$clearButton.blur(function () {
					$clearButton.css({display: 'none'});
				});
			}

			$clearButton.click(function(e) {
				var $input = $(me.element);
				$input.val("");
				$(this).css({display: 'none'});
				if (options.returnFocus === true) {
					$input.focus();
				}
				if (options.onClear) {
					options.onClear($input);
				}
				e.preventDefault();
			});
		}

	};

	$.fn[pluginName] = function(options) {
		return this.each(function() {
			if (!$.data(this, "plugin_" + pluginName)) {
				$.data(this, "plugin_" + pluginName,
					new Plugin(this, options));
			}
		});
	};

})(jQuery, window, document);
<|endoftext|>


<commit_before>var assert = require('assert')
var fs = require('fs')
var hexpp = require('hexpp')
var path = require('path')

var source = fs.readFileSync(path.join(__dirname, 'parquet.thrift'), 'ascii');

var thrift = require('thrift')
  var types = require('./gen-nodejs/parquet_types')

//the key is CompactProtocol!
function parse(buffer, type) {
  var transport = new thrift.TFramedTransport(buffer)
  var protocol = new thrift.TCompactProtocol(transport)
  type.read(protocol)
  parse.bytes = protocol.trans.readPos
  return type
}

module.exports = function (buffer) {

  assert.equal(buffer.slice(buffer.length - 4, buffer.length).toString('ascii'), 'PAR1', 'correct magic number')

  var footerLength = buffer.readInt32LE(buffer.length - 8)
  var footer = buffer.slice(buffer.length - (footerLength + 8), buffer.length)

  var fmd = parse(footer, new types.FileMetaData())

  console.log("FileMetaData", require('util').inspect(fmd, {depth: 10}))

  for(var i in fmd.row_groups[0].columns) {
//    if(fmd.row_groups[0].columns[i].encoding == 0)
//      fmd.row_groups[0]
      column_chunk(fmd.row_groups[0].columns[i], i)
  //  column_chunk(fmd.row_groups[0].columns[1])
  }

  function column_chunk(cc) {
    console.log('ColumnChunk', cc)
    var start = cc.file_offset, length = cc.meta_data.total_compressed_size
    var page_header = parse(buffer.slice(start, start+length), new types.PageHeader())
    console.log('PageHeader', page_header)
    if(page_header.data_page_header && page_header.data_page_header.encoding === 0) {
      console.log(hexpp(buffer.slice(start+parse.bytes, start+length)))
      var values = buffer.slice(start+parse.bytes, start+length)

      //read out strings. why is there an 6 byte offset?
      console.log('HEAD', values.slice(0, 6))
      var offset =  6, ary = []
      while(offset < values.length) {
        //for BYTE_ARRAY length is 32LE, then that many bytes.
        var length = values.readUInt32LE(offset)
        console.log('length', length)
        offset += 4
        ary.push(values.slice(offset, offset+length).toString())
        offset += length
      }
      console.log(ary)
    }
  }

}

if(!module.parent)
  module.exports(require('fs').readFileSync(process.argv[2]))

<commit_msg>dump dict encoded files<commit_after>var assert = require('assert')
var fs = require('fs')
var hexpp = require('hexpp')
var path = require('path')

var source = fs.readFileSync(path.join(__dirname, 'parquet.thrift'), 'ascii');

var thrift = require('thrift')
  var types = require('./gen-nodejs/parquet_types')

//the key is CompactProtocol!
function parse(buffer, type) {
  var transport = new thrift.TFramedTransport(buffer)
  var protocol = new thrift.TCompactProtocol(transport)
  type.read(protocol)
  parse.bytes = protocol.trans.readPos
  return type
}

module.exports = function (buffer) {

  assert.equal(buffer.slice(buffer.length - 4, buffer.length).toString('ascii'), 'PAR1', 'correct magic number')

  var footerLength = buffer.readInt32LE(buffer.length - 8)
  var footer = buffer.slice(buffer.length - (footerLength + 8), buffer.length)

  var fmd = parse(footer, new types.FileMetaData())

//  console.log("FileMetaData", require('util').inspect(fmd, {depth: 10}))

  for(var i in fmd.row_groups[0].columns) {
//    if(fmd.row_groups[0].columns[i].encoding == 0)
//      fmd.row_groups[0]
      column_chunk(fmd.row_groups[0].columns[i], i)
  //  column_chunk(fmd.row_groups[0].columns[1])
  }

  function column_chunk(cc) {
//    console.log('ColumnChunk', cc)
    var start = cc.file_offset, length = cc.meta_data.total_compressed_size
    var page_header = parse(buffer.slice(start, start+length), new types.PageHeader())
  //  console.log('PageHeader', page_header)

    //plain encoding.
    if(false && page_header.data_page_header && page_header.data_page_header.encoding === 0) {
      return
      console.log(hexpp(buffer.slice(start+parse.bytes, start+length)))
      var values = buffer.slice(start+parse.bytes, start+length)

      //read out strings. why is there an 6 byte offset?
      console.log('HEAD', values.slice(0, 6))
      var offset =  6, ary = []
      while(offset < values.length) {
        //for BYTE_ARRAY length is 32LE, then that many bytes.
        var length = values.readUInt32LE(offset)
        console.log('length', length)
        offset += 4
        ary.push(values.slice(offset, offset+length).toString())
        offset += length
      }
      console.log(ary)
    }
    else {
//      console.log('-----------------------------------')
      console.log(cc.meta_data.path_in_schema)
      if(page_header.data_page_header)
        console.log('DPH', page_header.data_page_header.encoding)
      else {
        console.log('DICT', page_header)
        console.log(hexpp(buffer.slice(start+parse.bytes, start+length)))
      }
//      console.log(start, length)
//      console.log(page_header.data_page_header && page_header.data_page_header.encoding)
//      console.log(hexpp(buffer.slice(start+parse.bytes, start+length)))
    }
  }

}

if(!module.parent)
  module.exports(require('fs').readFileSync(process.argv[2]))

<|endoftext|>


<commit_before>/**
 * Created by hariharaselvam on 7/12/16.
 */
window[appName].controller('sdn_edit_flow_controller',function($rootScope,$scope,$state,$stateParams,$http,$window,$location,$q,$filter)	{

	console.log("Called");

	if($scope.logged_in==undefined || $scope.logged_in=="")
	{
		window.location = "index.html";
	}
    $scope.id = $stateParams.id;

	$scope.itemperpage = 10;
	$scope.sw_pagination = {};
	$scope.sw_pagination.current = 1;

	function HttpRequest(method,action, URL, parameter) {

		$rootScope.showLoader = true;

		var $promise = '';
		if(method==="post") {
			$promise = $http.post(URL, parameter);
		} else {
			$promise = $http.get(URL, parameter);
		}
		$promise.then(function (response) {
			var result = angular.fromJson(response.data);
			processTheData(action, result);

			$rootScope.showLoader = false;

		});
	};

	function processTheData(action, response) {

		switch (action) {

			case 'add_flow':

				console.log(response);
				break;

            case 'get_flow_info':
                $scope.flow = response.toSource();
                break;

		}

	}

	$scope.flow_delete = function(id,rev) {

		var param = {"cancel":true};

		bootbox.confirm("Are you sure you want to delete the flow "+id+ "?" , function (result) {
            if (result) {
				param = {"id":id,"rev":rev};
                HttpRequest('post','delete_flow',window.flaskURL+'delete_flow',param);
            }
        });

	}

    HttpRequest('post','get_flow_info',window.flaskURL+'get_flow_info',{"flow_id": $scope.id});

    $scope.add_flow=function()
    {
        HttpRequest('post','add_flow',window.flaskURL+'add_flow',JSON.parse($scope.flow));
    }

});

<commit_msg>update flow bug fix<commit_after>/**
 * Created by hariharaselvam on 7/12/16.
 */
window[appName].controller('sdn_edit_flow_controller',function($rootScope,$scope,$state,$stateParams,$http,$window,$location,$q,$filter)	{

	console.log("Called");

	if($scope.logged_in==undefined || $scope.logged_in=="")
	{
		window.location = "index.html";
	}
    $scope.id = $stateParams.id;

	$scope.itemperpage = 10;
	$scope.sw_pagination = {};
	$scope.sw_pagination.current = 1;

	function HttpRequest(method,action, URL, parameter) {

		$rootScope.showLoader = true;

		var $promise = '';
		if(method==="post") {
			$promise = $http.post(URL, parameter);
		} else {
			$promise = $http.get(URL, parameter);
		}
		$promise.then(function (response) {
			var result = angular.fromJson(response.data);
			processTheData(action, result);

			$rootScope.showLoader = false;

		});
	};

	function processTheData(action, response) {

		switch (action) {

			case 'update_flow':

				console.log(response);
				break;

            case 'get_flow_info':
                $scope.flow = response.toSource();
                break;

		}

	}

	$scope.flow_delete = function(id,rev) {

		var param = {"cancel":true};

		bootbox.confirm("Are you sure you want to delete the flow "+id+ "?" , function (result) {
            if (result) {
				param = {"id":id,"rev":rev};
                HttpRequest('post','delete_flow',window.flaskURL+'delete_flow',param);
            }
        });

	}

    HttpRequest('post','get_flow_info',window.flaskURL+'get_flow_info',{"flow_id": $scope.id});

    $scope.edit_flow=function()
    {
        HttpRequest('post','update_flow',window.flaskURL+'update_flow',JSON.parse($scope.flow));
    }

});

<|endoftext|>


<commit_before>var io = require('socket.io');
var events = require("events");
var util = require("util");
var ValidateObjectController = require("./ValidateObjectController.js");

util.inherits(exports.ChatSocketController, events.EventEmitter);

exports.ChatSocketController = function(port) {
	this.socketIO = io.listen(port);
	this.SetupConnectionEvents();

	function SetupConnectionEvents() {
	this.socketIO.sockets.on('connection', function(socket) {
		this.socketIO.sockets.on('chatCreated', function(user, gameInstanceID) {
			socket.join('chat/' + gameInstanceID);
		});
	});

	this.socketIO.sockets.on('receiveMessage', function(move) {
		this.emit('receiveMessage', move);
	});
}
}

exports.ChatSocketController.prototype.SendDataToUser = function(userID, data) {
	ValidateObjectController.ValidateNumber(userID);
	this.socketIO.sockets.socket(clientSocketIDHashTable[userID].id).emit('receivePlayResult', data);
}

exports.ChatSocketController.prototype.SendDataToAllUsersInGame = function(gameInstanceID, data) {
	ValidateObjectController.ValidateNumber(gameInstanceID);
	this.io.sockets.in(room).emit('chat/' + gameInstanceID, data);
}
<commit_msg>Created ChatSocketController<commit_after>var io = require('socket.io');
var events = require("events");
var util = require("util");
var ValidateObjectController = require("./ValidateObjectController.js");

exports.ChatSocketController = function(port) {
	this.socketIO = io.listen(port);
	this.SetupConnectionEvents();

	function SetupConnectionEvents() {
	this.socketIO.sockets.on('connection', function(socket) {
		socket.on('createChatRoom', function(user, gameInstanceID) {
			socket.join('chat/' + gameInstanceID);
		});

		socket.on('receiveMessage', function(message) {
			this.emit('receiveMessage', message);
		});
	});

	this.SendDataToUser = function(userID, data) {
		ValidateObjectController.ValidateNumber(userID);
		ValidateObjectController.ValidateString(clientSocketIDHashTable[userID]);
		this.socketIO.sockets.socket(clientSocketIDHashTable[userID]).emit('receivePlayResult', data);
	};

	this.SendDataToAllUsersInGame = function(gameInstanceID, data) {
		ValidateObjectController.ValidateNumber(gameInstanceID);
		ValidateObjectController.ValidateObject(this.socketIO.sockets.manager.rooms[('/chat/' + gameInstanceID)]);
		this.socketIO.sockets.in('chat/' + gameInstanceID).emit('receivePlayResult', data);
	};
}

util.inherits(exports.ChatSocketController, events.EventEmitter);<|endoftext|>


<commit_before>import Email from '../models/email.model';
import mongoose from 'mongoose';
const ObjectId = mongoose.Types.ObjectId;

function getMonthlyPunchCard(userId){
  return Email.aggregate([
    {$match: { user: ObjectId(userId)}},
    {$project: {
        month: { $month: "$date" },
        day: { $dayOfMonth: "$date" }
      }
    },
    {$group: {_id: {month: '$month', day: '$day'}, count: {$sum:1}}},
    {$sort:{'_id.month':1, '_id.day':1}}
  ]);
}

function getDailyPunchCard(userId){
  return Email.aggregate([
    {$match: { user: ObjectId(userId)}},
    {
      $project: {
        day: { $dayOfMonth: "$date" },
        hour: { $hour: "$date" },
      }
    },
    {$group: {_id: {day: '$day', hour: '$hour'}, count: {$sum:1}}},
    {$sort:{'_id.day':1, '_id.hour':1}}
  ]);
}

function getTopSender(userId){
  return Email.aggregate([
    {$match: { user: ObjectId(userId)}},
    {$unwind: '$from'},
    {$group: {_id: {address: '$from.address', name: '$from.name'}, count: {$sum:1}}},
    {$sort: {'count':-1}}
  ]);
}

function getSummary(req, res) {

  //TODO may consider only the last 12 month not all data ...
  //TODO differentiate between send, received and all mails
  //TODO use id of current user
  const userId = "5836fe8a14272b01c404257c";

  const s = {
    punchcard:{},
    network:{}
  };

  getMonthlyPunchCard(userId)
    .then((monthlySummary)=>{
      s.punchcard.monthly = monthlySummary;
      return getDailyPunchCard(userId);
    })
    .then((dailySummary)=>{
      s.punchcard.daily = dailySummary;
      return getTopSender(userId)
    })
    .then((topSender)=>{
      s.network.topsender = topSender;
      res.status(200).send(s);
    });

}

export default {
  getSummary
};
<commit_msg>dashboard top receiver<commit_after>import Email from '../models/email.model';
import mongoose from 'mongoose';
const ObjectId = mongoose.Types.ObjectId;

function getMonthlyPunchCard(userId){
  return Email.aggregate([
    {$match: { user: ObjectId(userId)}},
    {$project: {
        month: { $month: "$date" },
        day: { $dayOfMonth: "$date" }
      }
    },
    {$group: {_id: {month: '$month', day: '$day'}, count: {$sum:1}}},
    {$sort:{'_id.month':1, '_id.day':1}}
  ]);
}

function getDailyPunchCard(userId){
  return Email.aggregate([
    {$match: { user: ObjectId(userId)}},
    {
      $project: {
        day: { $dayOfMonth: "$date" },
        hour: { $hour: "$date" },
      }
    },
    {$group: {_id: {day: '$day', hour: '$hour'}, count: {$sum:1}}},
    {$sort:{'_id.day':1, '_id.hour':1}}
  ]);
}

function getTopSender(userId){
  return Email.aggregate([
    {$match: { user: ObjectId(userId)}},
    {$unwind: '$from'},
    {$group: {_id: {address: '$from.address', name: '$from.name'}, count: {$sum:1}}},
    {$sort: {'count':-1}}
  ]);
}

function getTopReceiver(userId){
  return Email.aggregate([
    {$match: { user: ObjectId(userId)}},
    {$unwind: '$to'},
    {$group: {_id: {address: '$to.address', name: '$to.name'}, count: {$sum:1}}},
    {$sort: {'count':-1}}
  ]);
}

function getSummary(req, res) {

  //TODO may consider only the last 12 month not all data ...
  //TODO differentiate between send, received and all mails
  //TODO use id of current user
  const userId = "5836fe8a14272b01c404257c";

  const s = {
    punchcard:{},
    network:{}
  };

  getMonthlyPunchCard(userId)
    .then((monthlySummary)=>{
      s.punchcard.monthly = monthlySummary;
      return getDailyPunchCard(userId);
    })
    .then((dailySummary)=>{
      s.punchcard.daily = dailySummary;
      return getTopSender(userId)
    })
    .then((topSender)=>{
      s.network.topsender = topSender;
      return getTopReceiver(userId)
    })
    .then((topReceiver)=>{
      s.network.topreceiver = topReceiver;
      res.status(200).send(s);
  });

}

export default {
  getSummary
};
<|endoftext|>


<commit_before>const { onError } = require('../../errors')

const loginWithFacebook = async ({ context, args }) => {
  const userData = await context.nap.willLoginWithFacebook(context, args.accessToken).catch(onError(context))
  const user = userData && await context.nap.willCreateUser(userData).catch(onError(context))
  return user && await context.nap.willInstallAndAuthen(args, user, 'facebook').catch(onError(context))
}

const login = async ({ context, args }) => {
  const user = await context.nap.willLogin(context, args.email, args.password).catch(onError(context))
  return user && await context.nap.willInstallAndAuthen(args, user, 'local').catch(onError(context))
}

const signup = async ({ context, args }) => {
  const userData = await context.nap.willSignUp(context, args.email, args.password).catch(onError(context))
  const user = userData && await context.nap.willCreateUser(userData).catch(onError(context))
  return user
}

const forget = async ({ context, args }) => await context.nap.willResetPassword(context, args.email)
  .then(({ status }) => ({ user: { status } }))
  .catch(onError(context))

const logout = async ({ context }) => {
  // Logout from cookie
  console.log(context.nap.session)
  context.logout()
  context.session.destroy()

  // Guard
  if (!context.nap.session) {
    return {
      isLoggedIn: false,
      sessionToken: null
    }
  }

  // Logout
  const { installationId, userId } = context.nap.session
  return await context.nap.willLogout(installationId, userId, context.token).catch(onError(context))
}

const authen = async ({ context }) => {
  const _noAuthen = {
    isLoggedIn: false,
    sessionToken: null
  }

  // Guard
  if (!context.nap.session) {
    return _noAuthen
  }

  const { installationId, userId } = context.nap.session
  return await NAP.Authen.findOne({ userId, installationId }).catch(err => onError(context)(err) && _noAuthen)
}

const willAuthen = async (installationId, { _id: userId, verified }, provider) => {
  // Base data
  let authenData = {
    isLoggedIn: false,
    installationId,
    userId
  }

  // Create session token
  const { createSessionToken } = require('../../jwt-token')
  const sessionToken = createSessionToken(installationId, userId)

  // Guard by user local verification if has
  const isVerified = (provider === 'local') ? verified : true
  if (isVerified) {
    authenData = Object.assign(authenData, {
      isLoggedIn: isVerified,
      loggedInAt: new Date().toISOString(),
      loggedInWith: provider,
      sessionToken
    })
  }

  // Allow to authen
  return await NAP.Authen.findOneAndUpdate({ installationId, userId }, authenData, { new: true, upsert: true })
}

module.exports = {
  loginWithFacebook,
  signup,
  forget,
  login,
  logout,
  authen,
  willAuthen
}
<commit_msg>remove unused comment<commit_after>const { onError } = require('../../errors')

const loginWithFacebook = async ({ context, args }) => {
  const userData = await context.nap.willLoginWithFacebook(context, args.accessToken).catch(onError(context))
  const user = userData && await context.nap.willCreateUser(userData).catch(onError(context))
  return user && await context.nap.willInstallAndAuthen(args, user, 'facebook').catch(onError(context))
}

const login = async ({ context, args }) => {
  const user = await context.nap.willLogin(context, args.email, args.password).catch(onError(context))
  return user && await context.nap.willInstallAndAuthen(args, user, 'local').catch(onError(context))
}

const signup = async ({ context, args }) => {
  const userData = await context.nap.willSignUp(context, args.email, args.password).catch(onError(context))
  const user = userData && await context.nap.willCreateUser(userData).catch(onError(context))
  return user
}

const forget = async ({ context, args }) => await context.nap.willResetPassword(context, args.email)
  .then(({ status }) => ({ user: { status } }))
  .catch(onError(context))

const logout = async ({ context }) => {
  // Logout from cookie
  context.logout()
  context.session.destroy()

  // Guard
  if (!context.nap.session) {
    return {
      isLoggedIn: false,
      sessionToken: null
    }
  }

  // Logout
  const { installationId, userId } = context.nap.session
  return await context.nap.willLogout(installationId, userId, context.token).catch(onError(context))
}

const authen = async ({ context }) => {
  const _noAuthen = {
    isLoggedIn: false,
    sessionToken: null
  }

  // Guard
  if (!context.nap.session) {
    return _noAuthen
  }

  const { installationId, userId } = context.nap.session
  return await NAP.Authen.findOne({ userId, installationId }).catch(err => onError(context)(err) && _noAuthen)
}

const willAuthen = async (installationId, { _id: userId, verified }, provider) => {
  // Base data
  let authenData = {
    isLoggedIn: false,
    installationId,
    userId
  }

  // Create session token
  const { createSessionToken } = require('../../jwt-token')
  const sessionToken = createSessionToken(installationId, userId)

  // Guard by user local verification if has
  const isVerified = (provider === 'local') ? verified : true
  if (isVerified) {
    authenData = Object.assign(authenData, {
      isLoggedIn: isVerified,
      loggedInAt: new Date().toISOString(),
      loggedInWith: provider,
      sessionToken
    })
  }

  // Allow to authen
  return await NAP.Authen.findOneAndUpdate({ installationId, userId }, authenData, { new: true, upsert: true })
}

module.exports = {
  loginWithFacebook,
  signup,
  forget,
  login,
  logout,
  authen,
  willAuthen
}
<|endoftext|>