<commit_before>'use strict';

import moment from 'moment';
import _ from 'lodash';

import { CloudProviderRegistry } from 'core/cloudProvider';
import { NameUtils } from 'core/naming';
import { EXECUTION_DETAILS_SECTION_SERVICE } from 'core/pipeline/details/executionDetailsSection.service';
import { ServerGroupReader } from 'core/serverGroup/serverGroupReader.service';
import { URL_BUILDER_SERVICE } from 'core/navigation/urlBuilder.service';
import { ClusterState } from 'core/state';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.core.pipeline.stage.deploy.details.controller', [
    require('@uirouter/angularjs').default,
    EXECUTION_DETAILS_SECTION_SERVICE,
    URL_BUILDER_SERVICE,
  ])
  .controller('DeployExecutionDetailsCtrl', function(
    $scope,
    $stateParams,
    executionDetailsSectionService,
    urlBuilderService,
  ) {
    $scope.configSections = ['deploymentConfig', 'taskStatus', 'artifactStatus'];

    function areJarDiffsEmpty() {
      let result = true;

      const jarDiffs = $scope.stage.context.jarDiffs;
      if (!_.isEmpty(jarDiffs)) {
        result = !Object.keys(jarDiffs).some(key => Array.isArray(jarDiffs[key]) && jarDiffs[key].length);
      }

      return result;
    }

    if ($scope.stage.context) {
      if (
        ($scope.stage.context.commits && $scope.stage.context.commits.length > 0) ||
        !areJarDiffsEmpty($scope.stage.context.jarDiffs)
      ) {
        $scope.configSections.push('changes');
      }
    }

    let initialized = () => {
      $scope.detailsSection = $stateParams.details;

      var context = $scope.stage.context || {},
        results = [];

      function addDeployedArtifacts(key) {
        var deployedArtifacts = _.find(resultObjects, key);
        if (deployedArtifacts) {
          _.forEach(deployedArtifacts[key], function(serverGroupName, region) {
            var result = {
              type: 'serverGroups',
              application: context.application,
              serverGroup: serverGroupName,
              account: context.account,
              region: region,
              provider: context.providerType || context.cloudProvider || 'aws',
              cloudProvider: context.providerType || context.cloudProvider || 'aws',
              project: $stateParams.project,
            };
            result.href = urlBuilderService.buildFromMetadata(result);
            results.push(result);
          });
        }
      }

      if (context && context['kato.tasks'] && context['kato.tasks'].length) {
        var resultObjects = context['kato.tasks'][0].resultObjects;
        if (resultObjects && resultObjects.length) {
          results = [];
          addDeployedArtifacts('serverGroupNameByRegion');
        }
      }
      $scope.deployed = results;
      configureWaitingMessages(results);
      $scope.provider = context.cloudProvider || context.providerType || 'aws';

      $scope.changeConfig = {
        buildInfo: context.buildInfo || {},
        commits: $scope.stage.context.commits,
        jarDiffs: $scope.stage.context.jarDiffs,
      };

      if (_.has(context, 'source.region') && context['deploy.server.groups']) {
        const serverGroupName = context['deploy.server.groups'][context.source.region][0];
        ServerGroupReader.getServerGroup(context.application, context.account, context.source.region, serverGroupName)
          .then(serverGroup => {
            if (_.has(serverGroup, 'buildInfo.jenkins')) {
              $scope.changeConfig.buildInfo.jenkins = serverGroup.buildInfo.jenkins;
            }
          })
          .catch(() => {});
      }
    };

    function configureWaitingMessages(deployedArtifacts) {
      $scope.showWaitingMessage = false;
      $scope.waitingForUpInstances = false;
      $scope.showScalingActivitiesLink = false;
      $scope.showPlatformHealthOverrideMessage = false;

      if (!deployedArtifacts.length) {
        return;
      }
      const deployed = deployedArtifacts[0];
      const stage = $scope.stage;

      const activeWaitTask = (stage.tasks || []).find(
        t => ['RUNNING', 'TERMINAL'].includes(t.status) && t.name === 'waitForUpInstances',
      );

      if (activeWaitTask && stage.context.lastCapacityCheck) {
        $scope.showWaitingMessage = true;
        $scope.waitingForUpInstances = activeWaitTask.status === 'RUNNING';
        const lastCapacity = stage.context.lastCapacityCheck;
        const waitDurationExceeded = activeWaitTask.runningTimeInMs > moment.duration(5, 'minutes').asMilliseconds();
        lastCapacity.total =
          lastCapacity.up +
          lastCapacity.down +
          lastCapacity.outOfService +
          lastCapacity.unknown +
          lastCapacity.succeeded +
          lastCapacity.failed;

        if (CloudProviderRegistry.getValue(stage.context.cloudProvider, 'serverGroup.scalingActivitiesEnabled')) {
          // after three minutes, if desired capacity is less than total number of instances,
          // show the scaling activities link
          if (waitDurationExceeded && lastCapacity.total < stage.context.capacity.desired) {
            $scope.showScalingActivitiesLink = true;
            $scope.scalingActivitiesTarget = {
              name: deployed.serverGroup,
              app: deployed.application,
              account: deployed.account,
              region: deployed.region,
              cluster: NameUtils.getClusterNameFromServerGroupName(deployed.serverGroup),
              cloudProvider: deployed.cloudProvider,
            };
          }
        }
        // Also show platform health warning after three minutes if instances are in an unknown state
        if (
          waitDurationExceeded &&
          stage.context.lastCapacityCheck.unknown > 0 &&
          stage.context.lastCapacityCheck.unknown === stage.context.lastCapacityCheck.total &&
          !stage.context.interestingHealthProviderNames &&
          !_.get($scope.application.attributes, 'platformHealthOverride', false)
        ) {
          $scope.showPlatformHealthOverrideMessage = true;
        }
      }
    }

    this.overrideFiltersForUrl = r => ClusterState.filterService.overrideFiltersForUrl(r);

    let initialize = () => executionDetailsSectionService.synchronizeSection($scope.configSections, initialized);

    initialize();

    $scope.$on('$stateChangeSuccess', initialize);
    if (_.hasIn($scope.application, 'executions.onRefresh')) {
      $scope.application.executions.onRefresh($scope, initialize);
    }
  });
<commit_msg>fix(pipeline/deploy): Fixed missing tab by reevaluating scope after initialization (#5703)<commit_after>'use strict';

import moment from 'moment';
import _ from 'lodash';

import { CloudProviderRegistry } from 'core/cloudProvider';
import { NameUtils } from 'core/naming';
import { EXECUTION_DETAILS_SECTION_SERVICE } from 'core/pipeline/details/executionDetailsSection.service';
import { ServerGroupReader } from 'core/serverGroup/serverGroupReader.service';
import { URL_BUILDER_SERVICE } from 'core/navigation/urlBuilder.service';
import { ClusterState } from 'core/state';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.core.pipeline.stage.deploy.details.controller', [
    require('@uirouter/angularjs').default,
    EXECUTION_DETAILS_SECTION_SERVICE,
    URL_BUILDER_SERVICE,
  ])
  .controller('DeployExecutionDetailsCtrl', function(
    $scope,
    $stateParams,
    executionDetailsSectionService,
    urlBuilderService,
  ) {
    $scope.configSections = ['deploymentConfig', 'taskStatus', 'artifactStatus'];

    function areJarDiffsEmpty() {
      let result = true;

      const jarDiffs = $scope.stage.context.jarDiffs;
      if (!_.isEmpty(jarDiffs)) {
        result = !Object.keys(jarDiffs).some(key => Array.isArray(jarDiffs[key]) && jarDiffs[key].length);
      }

      return result;
    }

    function evaluateSections() {
      $scope.configSections = ['deploymentConfig', 'taskStatus', 'artifactStatus'];

      if ($scope.stage.context) {
        if (
          ($scope.stage.context.commits && $scope.stage.context.commits.length > 0) ||
          !areJarDiffsEmpty($scope.stage.context.jarDiffs)
        ) {
          $scope.configSections.push('changes');
        }
      }
    }

    evaluateSections();

    let initialized = () => {
      evaluateSections();
      $scope.detailsSection = $stateParams.details;

      var context = $scope.stage.context || {},
        results = [];

      function addDeployedArtifacts(key) {
        var deployedArtifacts = _.find(resultObjects, key);
        if (deployedArtifacts) {
          _.forEach(deployedArtifacts[key], function(serverGroupName, region) {
            var result = {
              type: 'serverGroups',
              application: context.application,
              serverGroup: serverGroupName,
              account: context.account,
              region: region,
              provider: context.providerType || context.cloudProvider || 'aws',
              cloudProvider: context.providerType || context.cloudProvider || 'aws',
              project: $stateParams.project,
            };
            result.href = urlBuilderService.buildFromMetadata(result);
            results.push(result);
          });
        }
      }

      if (context && context['kato.tasks'] && context['kato.tasks'].length) {
        var resultObjects = context['kato.tasks'][0].resultObjects;
        if (resultObjects && resultObjects.length) {
          results = [];
          addDeployedArtifacts('serverGroupNameByRegion');
        }
      }
      $scope.deployed = results;
      configureWaitingMessages(results);
      $scope.provider = context.cloudProvider || context.providerType || 'aws';

      $scope.changeConfig = {
        buildInfo: context.buildInfo || {},
        commits: $scope.stage.context.commits,
        jarDiffs: $scope.stage.context.jarDiffs,
      };

      if (_.has(context, 'source.region') && context['deploy.server.groups']) {
        const serverGroupName = context['deploy.server.groups'][context.source.region][0];
        ServerGroupReader.getServerGroup(context.application, context.account, context.source.region, serverGroupName)
          .then(serverGroup => {
            if (_.has(serverGroup, 'buildInfo.jenkins')) {
              $scope.changeConfig.buildInfo.jenkins = serverGroup.buildInfo.jenkins;
            }
          })
          .catch(() => {});
      }
    };

    function configureWaitingMessages(deployedArtifacts) {
      $scope.showWaitingMessage = false;
      $scope.waitingForUpInstances = false;
      $scope.showScalingActivitiesLink = false;
      $scope.showPlatformHealthOverrideMessage = false;

      if (!deployedArtifacts.length) {
        return;
      }
      const deployed = deployedArtifacts[0];
      const stage = $scope.stage;

      const activeWaitTask = (stage.tasks || []).find(
        t => ['RUNNING', 'TERMINAL'].includes(t.status) && t.name === 'waitForUpInstances',
      );

      if (activeWaitTask && stage.context.lastCapacityCheck) {
        $scope.showWaitingMessage = true;
        $scope.waitingForUpInstances = activeWaitTask.status === 'RUNNING';
        const lastCapacity = stage.context.lastCapacityCheck;
        const waitDurationExceeded = activeWaitTask.runningTimeInMs > moment.duration(5, 'minutes').asMilliseconds();
        lastCapacity.total =
          lastCapacity.up +
          lastCapacity.down +
          lastCapacity.outOfService +
          lastCapacity.unknown +
          lastCapacity.succeeded +
          lastCapacity.failed;

        if (CloudProviderRegistry.getValue(stage.context.cloudProvider, 'serverGroup.scalingActivitiesEnabled')) {
          // after three minutes, if desired capacity is less than total number of instances,
          // show the scaling activities link
          if (waitDurationExceeded && lastCapacity.total < stage.context.capacity.desired) {
            $scope.showScalingActivitiesLink = true;
            $scope.scalingActivitiesTarget = {
              name: deployed.serverGroup,
              app: deployed.application,
              account: deployed.account,
              region: deployed.region,
              cluster: NameUtils.getClusterNameFromServerGroupName(deployed.serverGroup),
              cloudProvider: deployed.cloudProvider,
            };
          }
        }
        // Also show platform health warning after three minutes if instances are in an unknown state
        if (
          waitDurationExceeded &&
          stage.context.lastCapacityCheck.unknown > 0 &&
          stage.context.lastCapacityCheck.unknown === stage.context.lastCapacityCheck.total &&
          !stage.context.interestingHealthProviderNames &&
          !_.get($scope.application.attributes, 'platformHealthOverride', false)
        ) {
          $scope.showPlatformHealthOverrideMessage = true;
        }
      }
    }

    this.overrideFiltersForUrl = r => ClusterState.filterService.overrideFiltersForUrl(r);

    let initialize = () => executionDetailsSectionService.synchronizeSection($scope.configSections, initialized);

    initialize();

    $scope.$on('$stateChangeSuccess', initialize);
    if (_.hasIn($scope.application, 'executions.onRefresh')) {
      $scope.application.executions.onRefresh($scope, initialize);
    }
  });
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

define([
    'backbone',
    'jquery',
    'underscore',
    'moment',
    'find/app/model/find-base-collection',
    'find/app/page/search/filters/parametric/numeric-widget',
    'find/app/model/bucketed-parametric-collection',
    'parametric-refinement/prettify-field-name',
    'parametric-refinement/selected-values-collection',
    'i18n!find/nls/bundle'
], function(Backbone, $, _, moment, FindBaseCollection, numericWidget, BucketedParametricCollection, prettifyFieldName, SelectedParametricValuesCollection, i18n) {

    'use strict';

    var GRAPH_HEIGHT = 110;
    var DATE_WIDGET_FORMAT = 'YYYY-MM-DD HH:mm';

    function rangeModelMatching(fieldName, numericRestriction) {
        return function(model) {
            return model.get('field') === fieldName && model.get('range') && model.get('numeric') === numericRestriction;
        };
    }

    function resetSelectedParametricValues(selectedParametricValues, fieldName, numericRestriction) {
        selectedParametricValues.remove(selectedParametricValues.filter(rangeModelMatching(fieldName, numericRestriction)));
    }

    function updateRestrictions(selectedParametricValues, fieldName, numericRestriction, min, max) {
        var existing = selectedParametricValues.find(rangeModelMatching(fieldName, numericRestriction));

        var newAttributes = {
            field: fieldName,
            range: [min, max],
            numeric: numericRestriction
        };

        if (existing) {
            existing.set(newAttributes);
        } else {
            selectedParametricValues.add(newAttributes);
        }
    }

    function roundInputNumber(input) {
        return Math.round(input * 10) / 10;
    }

    function calibrateBuckets(buckets, min, max, bucketSize) {
        // Remove buckets not in range when zooming in
        //noinspection JSUnresolvedFunction
        var calibratedBuckets = _.filter(buckets, function(value) {
            return value.min >= min && value.max <= max;
        });

        if (calibratedBuckets.length > 0) {
            // Add empty buckets to the beginning if zooming out
            while (calibratedBuckets[0].min > min) {
                calibratedBuckets.unshift({
                    min: Math.max(calibratedBuckets[0].min - bucketSize, min),
                    max: calibratedBuckets[0].min,
                    count: 0
                });
            }

            // Add empty buckets to the end if zooming out
            //noinspection JSUnresolvedFunction
            while (_.last(calibratedBuckets).max < max) {
                //noinspection JSUnresolvedFunction
                calibratedBuckets.push({
                    min: _.last(calibratedBuckets).max,
                    max: Math.min(_.last(calibratedBuckets).max + bucketSize, max),
                    count: 0
                });
            }
        } else {
            // Zooming where there are no buckets
            calibratedBuckets = _.range(min, max, bucketSize).map(function(bucketMin) {
                return {
                    min: bucketMin,
                    max: bucketMin + bucketSize,
                    count: 0
                };
            });
        }

        return calibratedBuckets;
    }

    var NumericParametricFieldView = Backbone.View.extend({
        className: 'animated fadeIn',

        events: {
            'click .numeric-parametric-no-min': function() {
                this.updateMinInput(this.absoluteMinValue);
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), this.readMaxInput());
                this.drawSelection();
            },
            'click .numeric-parametric-no-max': function() {
                this.updateMaxInput(this.absoluteMaxValue);
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), this.readMaxInput());
                this.drawSelection();
            },
            'click .numeric-parametric-reset': function() {
                resetSelectedParametricValues(this.selectedParametricValues, this.fieldName, this.numericRestriction);
                this.drawSelection();
                this.updateModel(this.absoluteMinValue, this.absoluteMaxValue);
            },
            'change .numeric-parametric-min-input': function() {
                //noinspection JSUnresolvedVariable,JSUnresolvedFunction
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), this.readMaxInput());
                //noinspection JSUnresolvedFunction
                this.drawSelection();
            },
            'change .numeric-parametric-max-input': function() {
                //noinspection JSUnresolvedVariable,JSUnresolvedFunction
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), this.readMaxInput());
                //noinspection JSUnresolvedFunction
                this.drawSelection();
            },
            'dp.change .results-filter-date[data-date-attribute="min-date"]': function(event) {
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, event.date.unix(), this.readMaxInput());
                this.drawSelection();
            },
            'dp.change .results-filter-date[data-date-attribute="max-date"]': function(event) {
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), event.date.unix());
                this.drawSelection();
            }
        },

        initialize: function(options) {
            this.template = _.template(options.template);
            this.queryModel = options.queryModel;
            this.selectedParametricValues = options.selectedParametricValues;
            this.pixelsPerBucket = options.pixelsPerBucket;
            this.viewWidth = options.viewWidth;
            this.selectionEnabled = options.selectionEnabled;
            this.zoomEnabled = options.zoomEnabled;
            this.buttonsEnabled = options.selectionEnabled && options.buttonsEnabled;
            this.coordinatesEnabled = options.coordinatesEnabled === undefined ? true : options.coordinatesEnabled;
            this.numericRestriction = options.numericRestriction || false;

            this.fieldName = this.model.id;

            var formatting = options.formatting  || NumericParametricFieldView.defaultFormatting;
            this.formatValue = formatting.format;
            this.parseValue = formatting.parse;
            this.renderCustomFormatting = formatting.render;
            this.parseBoundarySelection = formatting.parseBoundarySelection;

            this.widget = numericWidget({formattingFn: this.formatValue});

            this.bucketModel = new BucketedParametricCollection.Model({
                id: this.model.get('id'),
                name: this.model.get('id')
            });

            this.absoluteMinValue = this.model.get('min');
            this.absoluteMaxValue = this.model.get('max');
        },

        render: function() {
            var inputColumnClass = this.selectionEnabled ? (this.coordinatesEnabled ? 'col-xs-4' : 'col-xs-6') : 'hide';
            var coordinatesColumnClass = this.coordinatesEnabled ? (this.selectionEnabled ? 'col-xs-4' : 'col-xs-12') : 'hide';

            this.$el
                .empty()
                .append(this.template({
                    i18n: i18n,
                    fieldName: prettifyFieldName(this.model.get('name')),
                    buttonsEnabled: this.buttonsEnabled,
                    inputsRowClass: this.selectionEnabled || this.coordinatesEnabled ? '' : 'hide',
                    inputColumnClass: inputColumnClass,
                    coordinatesColumnClass: coordinatesColumnClass
                }));

            if (this.selectionEnabled) {
                //noinspection JSUnresolvedVariable
                this.renderCustomFormatting(this.$el);

                //noinspection JSUnresolvedFunction
                this.$minInput = this.$('.numeric-parametric-min-input');
                //noinspection JSUnresolvedFunction
                this.$maxInput = this.$('.numeric-parametric-max-input');

                this.updateMinInput(this.absoluteMinValue);
                this.updateMaxInput(this.absoluteMaxValue);
            }

            var updateCallback = function(x1, x2) {
                // rounding to one decimal place
                this.updateMinInput(Math.max(roundInputNumber(x1), this.model.get('min')));
                this.updateMaxInput(Math.min(roundInputNumber(x2), this.model.get('max')));
            }.bind(this);

            var selectionCallback = function(x1, x2) {
                var newMin = this.parseBoundarySelection(Math.max(x1, this.model.get('min')));
                var newMax = this.parseBoundarySelection(Math.min(x2, this.model.get('max')));
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, newMin, newMax);
            }.bind(this);

            var deselectionCallback = function() {
                this.updateMinInput(this.absoluteMinValue);
                this.updateMaxInput(this.absoluteMaxValue);
                resetSelectedParametricValues(this.selectedParametricValues, this.fieldName, this.numericRestriction);
            }.bind(this);

            var mouseMoveCallback = function(x) {
                //noinspection JSPotentiallyInvalidUsageOfThis
                this.$('.numeric-parametric-co-ordinates').text(this.formatValue(Math.min(roundInputNumber(x), this.model.get('max'))));
            }.bind(this);

            var mouseLeaveCallback = function() {
                //noinspection JSPotentiallyInvalidUsageOfThis
                this.$('.numeric-parametric-co-ordinates').text('');
            }.bind(this);

            //noinspection JSUnresolvedFunction
            var buckets = calibrateBuckets(this.model.get('values'), this.model.get('min'), this.model.get('max'), this.model.get('bucketSize'));

            //noinspection JSUnresolvedFunction
            this.graph = this.widget.drawGraph({
                chart: this.$('.chart')[0],
                data: {
                    buckets: buckets,
                    bucketSize: this.model.get('bucketSize'),
                    maxCount: _.max(_.pluck(buckets, 'count')),
                    minValue: this.model.get('min'),
                    maxValue: this.model.get('max')
                },
                updateCallback: updateCallback,
                selectionCallback: selectionCallback,
                deselectionCallback: deselectionCallback,
                mouseMoveCallback: mouseMoveCallback,
                mouseLeaveCallback: mouseLeaveCallback,
                zoomCallback: this.updateModel.bind(this),
                xRange: this.viewWidth,
                yRange: GRAPH_HEIGHT,
                tooltip: i18n['search.numericParametricFields.tooltip'],
                dragEnabled: this.selectionEnabled,
                zoomEnabled: this.zoomEnabled,
                coordinatesEnabled: this.coordinatesEnabled
            });

            if (this.selectionEnabled) {
                this.drawSelection();
            }
        },

        drawSelection: function() {
            this.graph.selectionRect.remove();

            var rangeModel = this.selectedParametricValues.find(rangeModelMatching(this.fieldName, this.numericRestriction));

            if (rangeModel) {
                var range = rangeModel.get('range');

                if (range) {
                    this.updateMinInput(roundInputNumber(range[0]));
                    this.updateMaxInput(roundInputNumber(range[1]));

                    this.graph.selectionRect.init(this.graph.chart, GRAPH_HEIGHT, this.graph.scale.barWidth(range[0]));
                    this.graph.selectionRect.update(this.graph.scale.barWidth(range[1]));
                    this.graph.selectionRect.focus();
                }
            }
        },

        updateModel: function(newMin, newMax) {
            // immediate update, just rescaling the existing buckets
            this.model.set({
                min: newMin,
                max: newMax
            });

            // proper update, regenerating the buckets from the given bounds
            this.bucketModel.fetch({
                data: {
                    databases: this.queryModel.get('indexes'),
                    targetNumberOfBuckets: Math.floor(this.$el.width() / this.pixelsPerBucket),
                    bucketMin: newMin,
                    bucketMax: newMax
                },
                reset: true,
                remove: true,
                success: function() {
                    this.model.set(this.bucketModel.attributes);
                }.bind(this)
            });
        },

        readMinInput: function() {
            return this.parseValue(this.$minInput.val());
        },

        readMaxInput: function() {
            return this.parseValue(this.$maxInput.val());
        },

        updateMinInput: function(newValue) {
            if (this.selectionEnabled) {
                this.$minInput.val(this.formatValue(newValue));
            }
        },

        updateMaxInput: function(newValue) {
            if (this.selectionEnabled) {
                this.$maxInput.val(this.formatValue(newValue));
            }
        }
    }, {
        defaultFormatting: {
            format: _.identity,
            parse: _.identity,
            parseBoundarySelection: _.identity,
            render: _.noop
        },
        dateFormatting: {
            format: function(unformattedString) {
                return moment(unformattedString * 1000).format(DATE_WIDGET_FORMAT);
            },
            parse: function(formattedString) {
                return moment(formattedString, DATE_WIDGET_FORMAT).unix();
            },
            parseBoundarySelection: function(input) {
                // Epoch seconds are not decimal
                return Math.round(input);
            },
            render: function($el) {
                $el.find('.results-filter-date').datetimepicker({
                    format: DATE_WIDGET_FORMAT,
                    icons: {
                        time: 'hp-icon hp-fw hp-clock',
                        date: 'hp-icon hp-fw hp-calendar',
                        up: 'hp-icon hp-fw hp-chevron-up',
                        down: 'hp-icon hp-fw hp-chevron-down',
                        next: 'hp-icon hp-fw hp-chevron-right',
                        previous: 'hp-icon hp-fw hp-chevron-left'
                    }
                });
            }
        }
    });

    return NumericParametricFieldView;

});<commit_msg>[FIND-273] added a remove listener on to the numeric view to perform the reset when the matching field is removed frem the selectedParametricCollection [rev Matt Gordon]<commit_after>/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

define([
    'backbone',
    'jquery',
    'underscore',
    'moment',
    'find/app/model/find-base-collection',
    'find/app/page/search/filters/parametric/numeric-widget',
    'find/app/model/bucketed-parametric-collection',
    'parametric-refinement/prettify-field-name',
    'parametric-refinement/selected-values-collection',
    'i18n!find/nls/bundle'
], function(Backbone, $, _, moment, FindBaseCollection, numericWidget, BucketedParametricCollection, prettifyFieldName, SelectedParametricValuesCollection, i18n) {

    'use strict';

    var GRAPH_HEIGHT = 110;
    var DATE_WIDGET_FORMAT = 'YYYY-MM-DD HH:mm';

    function rangeModelMatching(fieldName, numericRestriction) {
        return function(model) {
            return model.get('field') === fieldName && model.get('range') && model.get('numeric') === numericRestriction;
        };
    }

    function resetSelectedParametricValues(selectedParametricValues, fieldName, numericRestriction) {
        selectedParametricValues.remove(selectedParametricValues.filter(rangeModelMatching(fieldName, numericRestriction)));
    }

    function updateRestrictions(selectedParametricValues, fieldName, numericRestriction, min, max) {
        var existing = selectedParametricValues.find(rangeModelMatching(fieldName, numericRestriction));

        var newAttributes = {
            field: fieldName,
            range: [min, max],
            numeric: numericRestriction
        };

        if (existing) {
            existing.set(newAttributes);
        } else {
            selectedParametricValues.add(newAttributes);
        }
    }

    function roundInputNumber(input) {
        return Math.round(input * 10) / 10;
    }

    function calibrateBuckets(buckets, min, max, bucketSize) {
        // Remove buckets not in range when zooming in
        //noinspection JSUnresolvedFunction
        var calibratedBuckets = _.filter(buckets, function(value) {
            return value.min >= min && value.max <= max;
        });

        if (calibratedBuckets.length > 0) {
            // Add empty buckets to the beginning if zooming out
            while (calibratedBuckets[0].min > min) {
                calibratedBuckets.unshift({
                    min: Math.max(calibratedBuckets[0].min - bucketSize, min),
                    max: calibratedBuckets[0].min,
                    count: 0
                });
            }

            // Add empty buckets to the end if zooming out
            //noinspection JSUnresolvedFunction
            while (_.last(calibratedBuckets).max < max) {
                //noinspection JSUnresolvedFunction
                calibratedBuckets.push({
                    min: _.last(calibratedBuckets).max,
                    max: Math.min(_.last(calibratedBuckets).max + bucketSize, max),
                    count: 0
                });
            }
        } else {
            // Zooming where there are no buckets
            calibratedBuckets = _.range(min, max, bucketSize).map(function(bucketMin) {
                return {
                    min: bucketMin,
                    max: bucketMin + bucketSize,
                    count: 0
                };
            });
        }

        return calibratedBuckets;
    }

    var NumericParametricFieldView = Backbone.View.extend({
        className: 'animated fadeIn',

        events: {
            'click .numeric-parametric-no-min': function() {
                this.updateMinInput(this.absoluteMinValue);
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), this.readMaxInput());
                this.drawSelection();
            },
            'click .numeric-parametric-no-max': function() {
                this.updateMaxInput(this.absoluteMaxValue);
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), this.readMaxInput());
                this.drawSelection();
            },
            'click .numeric-parametric-reset': function() {
                resetSelectedParametricValues(this.selectedParametricValues, this.fieldName, this.numericRestriction);
            },
            'change .numeric-parametric-min-input': function() {
                //noinspection JSUnresolvedVariable,JSUnresolvedFunction
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), this.readMaxInput());
                //noinspection JSUnresolvedFunction
                this.drawSelection();
            },
            'change .numeric-parametric-max-input': function() {
                //noinspection JSUnresolvedVariable,JSUnresolvedFunction
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), this.readMaxInput());
                //noinspection JSUnresolvedFunction
                this.drawSelection();
            },
            'dp.change .results-filter-date[data-date-attribute="min-date"]': function(event) {
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, event.date.unix(), this.readMaxInput());
                this.drawSelection();
            },
            'dp.change .results-filter-date[data-date-attribute="max-date"]': function(event) {
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, this.readMinInput(), event.date.unix());
                this.drawSelection();
            }
        },

        initialize: function(options) {
            this.template = _.template(options.template);
            this.queryModel = options.queryModel;
            this.selectedParametricValues = options.selectedParametricValues;
            this.pixelsPerBucket = options.pixelsPerBucket;
            this.viewWidth = options.viewWidth;
            this.selectionEnabled = options.selectionEnabled;
            this.zoomEnabled = options.zoomEnabled;
            this.buttonsEnabled = options.selectionEnabled && options.buttonsEnabled;
            this.coordinatesEnabled = options.coordinatesEnabled === undefined ? true : options.coordinatesEnabled;
            this.numericRestriction = options.numericRestriction || false;

            this.fieldName = this.model.id;

            var formatting = options.formatting  || NumericParametricFieldView.defaultFormatting;
            this.formatValue = formatting.format;
            this.parseValue = formatting.parse;
            this.renderCustomFormatting = formatting.render;
            this.parseBoundarySelection = formatting.parseBoundarySelection;

            this.widget = numericWidget({formattingFn: this.formatValue});

            this.bucketModel = new BucketedParametricCollection.Model({
                id: this.model.get('id'),
                name: this.model.get('id')
            });

            this.absoluteMinValue = this.model.get('min');
            this.absoluteMaxValue = this.model.get('max');
        },

        render: function() {
            var inputColumnClass = this.selectionEnabled ? (this.coordinatesEnabled ? 'col-xs-4' : 'col-xs-6') : 'hide';
            var coordinatesColumnClass = this.coordinatesEnabled ? (this.selectionEnabled ? 'col-xs-4' : 'col-xs-12') : 'hide';

            this.$el
                .empty()
                .append(this.template({
                    i18n: i18n,
                    fieldName: prettifyFieldName(this.model.get('name')),
                    buttonsEnabled: this.buttonsEnabled,
                    inputsRowClass: this.selectionEnabled || this.coordinatesEnabled ? '' : 'hide',
                    inputColumnClass: inputColumnClass,
                    coordinatesColumnClass: coordinatesColumnClass
                }));

            if (this.selectionEnabled) {
                //noinspection JSUnresolvedVariable
                this.renderCustomFormatting(this.$el);

                //noinspection JSUnresolvedFunction
                this.$minInput = this.$('.numeric-parametric-min-input');
                //noinspection JSUnresolvedFunction
                this.$maxInput = this.$('.numeric-parametric-max-input');

                this.updateMinInput(this.absoluteMinValue);
                this.updateMaxInput(this.absoluteMaxValue);
            }

            var updateCallback = function(x1, x2) {
                // rounding to one decimal place
                this.updateMinInput(Math.max(roundInputNumber(x1), this.model.get('min')));
                this.updateMaxInput(Math.min(roundInputNumber(x2), this.model.get('max')));
            }.bind(this);

            var selectionCallback = function(x1, x2) {
                var newMin = this.parseBoundarySelection(Math.max(x1, this.model.get('min')));
                var newMax = this.parseBoundarySelection(Math.min(x2, this.model.get('max')));
                updateRestrictions(this.selectedParametricValues, this.fieldName, this.numericRestriction, newMin, newMax);
            }.bind(this);

            var deselectionCallback = function() {
                this.updateMinInput(this.absoluteMinValue);
                this.updateMaxInput(this.absoluteMaxValue);
                resetSelectedParametricValues(this.selectedParametricValues, this.fieldName, this.numericRestriction);
            }.bind(this);

            var mouseMoveCallback = function(x) {
                //noinspection JSPotentiallyInvalidUsageOfThis
                this.$('.numeric-parametric-co-ordinates').text(this.formatValue(Math.min(roundInputNumber(x), this.model.get('max'))));
            }.bind(this);

            var mouseLeaveCallback = function() {
                //noinspection JSPotentiallyInvalidUsageOfThis
                this.$('.numeric-parametric-co-ordinates').text('');
            }.bind(this);

            //noinspection JSUnresolvedFunction
            var buckets = calibrateBuckets(this.model.get('values'), this.model.get('min'), this.model.get('max'), this.model.get('bucketSize'));

            //noinspection JSUnresolvedFunction
            this.graph = this.widget.drawGraph({
                chart: this.$('.chart')[0],
                data: {
                    buckets: buckets,
                    bucketSize: this.model.get('bucketSize'),
                    maxCount: _.max(_.pluck(buckets, 'count')),
                    minValue: this.model.get('min'),
                    maxValue: this.model.get('max')
                },
                updateCallback: updateCallback,
                selectionCallback: selectionCallback,
                deselectionCallback: deselectionCallback,
                mouseMoveCallback: mouseMoveCallback,
                mouseLeaveCallback: mouseLeaveCallback,
                zoomCallback: this.updateModel.bind(this),
                xRange: this.viewWidth,
                yRange: GRAPH_HEIGHT,
                tooltip: i18n['search.numericParametricFields.tooltip'],
                dragEnabled: this.selectionEnabled,
                zoomEnabled: this.zoomEnabled,
                coordinatesEnabled: this.coordinatesEnabled
            });

            if (this.selectionEnabled) {
                this.drawSelection();
            }

            this.listenTo(this.selectedParametricValues, 'remove', function(model) {
                if (model.get('field') == this.fieldName) {
                    this.drawSelection();
                    this.updateModel(this.absoluteMinValue, this.absoluteMaxValue);
                }
            });
        },

        drawSelection: function() {
            this.graph.selectionRect.remove();

            var rangeModel = this.selectedParametricValues.find(rangeModelMatching(this.fieldName, this.numericRestriction));

            if (rangeModel) {
                var range = rangeModel.get('range');

                if (range) {
                    this.updateMinInput(roundInputNumber(range[0]));
                    this.updateMaxInput(roundInputNumber(range[1]));

                    this.graph.selectionRect.init(this.graph.chart, GRAPH_HEIGHT, this.graph.scale.barWidth(range[0]));
                    this.graph.selectionRect.update(this.graph.scale.barWidth(range[1]));
                    this.graph.selectionRect.focus();
                }
            }
        },

        updateModel: function(newMin, newMax) {
            // immediate update, just rescaling the existing buckets
            this.model.set({
                min: newMin,
                max: newMax
            });

            // proper update, regenerating the buckets from the given bounds
            this.bucketModel.fetch({
                data: {
                    databases: this.queryModel.get('indexes'),
                    targetNumberOfBuckets: Math.floor(this.$el.width() / this.pixelsPerBucket),
                    bucketMin: newMin,
                    bucketMax: newMax
                },
                reset: true,
                remove: true,
                success: function() {
                    this.model.set(this.bucketModel.attributes);
                }.bind(this)
            });
        },

        readMinInput: function() {
            return this.parseValue(this.$minInput.val());
        },

        readMaxInput: function() {
            return this.parseValue(this.$maxInput.val());
        },

        updateMinInput: function(newValue) {
            if (this.selectionEnabled) {
                this.$minInput.val(this.formatValue(newValue));
            }
        },

        updateMaxInput: function(newValue) {
            if (this.selectionEnabled) {
                this.$maxInput.val(this.formatValue(newValue));
            }
        }
    }, {
        defaultFormatting: {
            format: _.identity,
            parse: _.identity,
            parseBoundarySelection: _.identity,
            render: _.noop
        },
        dateFormatting: {
            format: function(unformattedString) {
                return moment(unformattedString * 1000).format(DATE_WIDGET_FORMAT);
            },
            parse: function(formattedString) {
                return moment(formattedString, DATE_WIDGET_FORMAT).unix();
            },
            parseBoundarySelection: function(input) {
                // Epoch seconds are not decimal
                return Math.round(input);
            },
            render: function($el) {
                $el.find('.results-filter-date').datetimepicker({
                    format: DATE_WIDGET_FORMAT,
                    icons: {
                        time: 'hp-icon hp-fw hp-clock',
                        date: 'hp-icon hp-fw hp-calendar',
                        up: 'hp-icon hp-fw hp-chevron-up',
                        down: 'hp-icon hp-fw hp-chevron-down',
                        next: 'hp-icon hp-fw hp-chevron-right',
                        previous: 'hp-icon hp-fw hp-chevron-left'
                    }
                });
            }
        }
    });

    return NumericParametricFieldView;

});<|endoftext|>


<commit_before>class DatePickerController {
    constructor ($scope) {
        Object.assign(this, {$scope});
        this.defaultWeekDuration = 7;
        //this.defaultWeekStartDate = moment().startOf('week');
        this.datePickerCallback = this._datePickerCallback.bind(this);
    }

    $onInit() {
        this.targetInput = $('#' + this.name);

        this.refreshDatePicker(this.startDate, this.single);

        this.$scope.$on(EventType.WEEKSTART, (e, date) => {
            this.refreshDatePicker(date, this.single);
        });

        /**
         *
         * @param {Moment} start
         * @param {Moment} end
         */

    }

    _datePickerCallback (start, end) {
        this.onUpdate(start);
        //scope.$apply();
    }

    refreshDatePicker(date, isSingle) {
        this.targetInput.daterangepicker(
            this.setDatePickerSettings(date, isSingle), this.datePickerCallback
        );
    }

    getLocalization() {
        return {
            "format": "DD/MM/YYYY",
            "firstDay": 1
        };
    }

    /**
     *
     * @param {Moment} start
     * @param {string} isSingle
     * @param {Moment || null} end
     * @return {{locale: {Object}|*, singleDatePicker: boolean, showDropdowns: boolean, startDate: *, endDate: null}}
     */
    setDatePickerSettings(start, isSingle, end = null) {
        const endDate = end ? end : !!isSingle ? null : angular.copy(start).add(this.defaultWeekDuration-1, 'day');
        return {
            "locale": this.getLocalization(),
            "singleDatePicker": !!isSingle,
            "showDropdowns": true,
            "startDate": start,
            "endDate": endDate,
            "dateLimit": {
                "weeks": 2
            },
        }
    }
}

Mealpler.controller('DatePickerCtrl', DatePickerController);<commit_msg>MP-54: refactored datepicker ctrl<commit_after>class DatePickerController {
    constructor ($scope) {
        Object.assign(this, {$scope});
        this.datePickerCallback = this._datePickerCallback.bind(this);

        this.$scope.$on(EventType.WEEKSTART, (e, date) => {
            this.refreshDatePicker(date, this.single);
        });
    }

    $onInit() {
        this.targetInput = $('#' + this.name);
        this.refreshDatePicker(this.startDate, this.single);
    }

    _datePickerCallback (start) {
        this.onUpdate(start);
    }

    refreshDatePicker(date, isSingle) {
        this.targetInput.daterangepicker(
            DatePickerController._setDatePickerSettings(date, isSingle), this.datePickerCallback
        );
    }

    static getLocalization() {
        return {
            "format": "DD/MM/YYYY",
            "firstDay": 1
        };
    }

    /**
     *
     * @param {Moment} start
     * @param {string} isSingle
     * @param {Moment || null} end
     * @return {{locale: {Object}|*, singleDatePicker: boolean, showDropdowns: boolean, startDate: *, endDate: null}}
     */
    static _setDatePickerSettings(start, isSingle, end = null) {
        const endDate = end ? end : !!isSingle ? null : angular.copy(start).add(WEEK_DURATION-1, 'day');
        return {
            "locale": DatePickerController.getLocalization(),
            "singleDatePicker": !!isSingle,
            "showDropdowns": true,
            "startDate": start,
            "endDate": endDate,
            "dateLimit": {
                "weeks": 2
            },
        }
    }
}

Mealpler.controller('DatePickerCtrl', DatePickerController);<|endoftext|>


<commit_before>Template.wizardRegistrant.helpers({
  "registrantAgeIsBelow": function (ageThreshold) {
    // Get current age value from form
    let age = AutoForm.getFieldValue("age")

    if (age) {
      // Compare current value versus desired age threshold
      return age < ageThreshold;
    }
  },
  "registrantAgeIsBetween": function (lowerAge, upperAge) {
    /*
    Check if registrant age is within lower age and upper age limits (inclusive)
    */

    // Get current age value from form
    let age = AutoForm.getFieldValue("age")

    if (age) {
      // Compare current value versus desired age range
      return (lowerAge <= age) && (age <= upperAge);
    }
  },
  "yesNoOptions": function () {
    return [
      {label: "Yes", value: true},
      {label: "No", value: false}
    ];
  }
});
<commit_msg>Change yesNoOptions to strings<commit_after>Template.wizardRegistrant.helpers({
  "registrantAgeIsBelow": function (ageThreshold) {
    // Get current age value from form
    let age = AutoForm.getFieldValue("age")

    if (age) {
      // Compare current value versus desired age threshold
      return age < ageThreshold;
    }
  },
  "registrantAgeIsBetween": function (lowerAge, upperAge) {
    /*
    Check if registrant age is within lower age and upper age limits (inclusive)
    */

    // Get current age value from form
    let age = AutoForm.getFieldValue("age")

    if (age) {
      // Compare current value versus desired age range
      return (lowerAge <= age) && (age <= upperAge);
    }
  },
  "yesNoOptions": function () {
    return [
      {label: "Yes", value: "yes"},
      {label: "No", value: "no"}
    ];
  }
});
<|endoftext|>


<commit_before>/* eslint no-unused-expressions:0, max-nested-callbacks: [2, 5] */
"use strict";
import MainHeaderTab from "../../../../src/js/utils/components/TabComponent/MainHeaderTab.jsx";
import { assert } from "chai";
import TestUtils from "react-addons-test-utils";
import React from "react";
import { Link } from "react-router";
import "../../../helper/TestHelper.js";

describe("MainHeaderTab", () => {
    let highlightedTab = null, mainHeaderTab = null, parkCounter = 10;

    before("MainHeaderTab", () => {

        highlightedTab = {
            "tabNames": ["Park"]
        };
    });

    it("should have link to url", () => {
        mainHeaderTab = TestUtils.renderIntoDocument(
            <MainHeaderTab name="Park" url="/park" tabToHighlight={highlightedTab} className="park" parkCounter={ parkCounter } />
        );
        let linkElement = TestUtils.scryRenderedComponentsWithType(mainHeaderTab, Link);
        let linkProps = linkElement[0].props;
        assert.strictEqual("/park", linkProps.to);
        assert.strictEqual("selected", linkProps.className);
        assert.strictEqual("Park", linkProps.children[2].props.children);
        assert.strictEqual("park header-link-image", linkProps.children[1].props.className);
        assert.strictEqual("counter", linkProps.children[0].props.className);
    });

    it("should not add selected class name from park", () => {
        mainHeaderTab = TestUtils.renderIntoDocument(
            <MainHeaderTab name="Surf" url="/surf" tabToHighlight={highlightedTab} className="surf" parkCounter={ parkCounter }/>
        );
        let linkElement = TestUtils.scryRenderedComponentsWithType(mainHeaderTab, Link);
        assert.strictEqual("", linkElement[0].props.className);
    });
});
<commit_msg>Anil | eslint error fixed<commit_after>/* eslint no-unused-expressions:0, max-nested-callbacks: [2, 5] */
"use strict";
import MainHeaderTab from "../../../../src/js/utils/components/TabComponent/MainHeaderTab.jsx";
import { assert } from "chai";
import TestUtils from "react-addons-test-utils";
import React from "react";
import { Link } from "react-router";
import "../../../helper/TestHelper.js";

describe("MainHeaderTab", () => {
    let highlightedTab = null, mainHeaderTab = null, parkCounter = 10;

    before("MainHeaderTab", () => {
        highlightedTab = {
            "tabNames": ["Park"]
        };
    });

    it("should have link to url", () => {
        mainHeaderTab = TestUtils.renderIntoDocument(
            <MainHeaderTab name="Park" url="/park" tabToHighlight={highlightedTab} className="park" parkCounter={parkCounter} />
        );
        let linkElement = TestUtils.scryRenderedComponentsWithType(mainHeaderTab, Link);
        let linkProps = linkElement[0].props;
        assert.strictEqual("/park", linkProps.to);
        assert.strictEqual("selected", linkProps.className);
        assert.strictEqual("Park", linkProps.children[2].props.children);
        assert.strictEqual("park header-link-image", linkProps.children[1].props.className);
        assert.strictEqual("counter", linkProps.children[0].props.className);
    });

    it("should not add selected class name from park", () => {
        mainHeaderTab = TestUtils.renderIntoDocument(
            <MainHeaderTab name="Surf" url="/surf" tabToHighlight={highlightedTab} className="surf" parkCounter={parkCounter}/>
        );
        let linkElement = TestUtils.scryRenderedComponentsWithType(mainHeaderTab, Link);
        assert.strictEqual("", linkElement[0].props.className);
    });
});
<|endoftext|>


<commit_before>var tar = require('tar-fs')
var ignore = require('ignore-file')

var staticland = require('../index')
var addhttps = require('../lib/add-https')
var config = require('../lib/config')()
var error = require('../lib/error')

var ignoreList = `
.git
node_modules
`

module.exports = {
  name: 'deploy',
  command: function deploy (args) {
    var login = config.getLogin()
    var server = addhttps(args.server || login.server)
    var api = staticland({ server: server })
    var token = login.token

    if (args.exclude) {
      args.exclude = typeof args.exclude === 'string' ? args.exclude : args.exclude.join('\n')
      ignoreList = ignoreList.concat(args.exclude)
    }

    var filter = ignore.compile(ignoreList)

    args.path = args._[0]
    args.domain = args._[1]

    var tarstream = tar.pack(args.path, { ignore: filter })
    var headers = { domain: args.domain, authorization: `Bearer ${token}` }

    api.deploy(tarstream, headers, function (err, res, body) {
      if (err && err.message === 'socket hang up') {}
      else if (err) return error(err.message)

      // TODO: show progress/completion
      console.log('domain ' + args.domain + ' successfully deployed')
    })
  },
  options: [
    {
      name: 'exclude',
      abbr: 'e',
      boolean: false,
      help: 'list of files and directories you want to exclude from the deployment'
    }
  ]
}
<commit_msg>better error message for expired token<commit_after>var tar = require('tar-fs')
var ignore = require('ignore-file')

var staticland = require('../index')
var addhttps = require('../lib/add-https')
var config = require('../lib/config')()
var error = require('../lib/error')

var ignoreList = `
.git
node_modules
`

module.exports = {
  name: 'deploy',
  command: function deploy (args) {
    var login = config.getLogin()
    var server = addhttps(args.server || login.server)
    var api = staticland({ server: server })
    var token = login.token

    if (args.exclude) {
      args.exclude = typeof args.exclude === 'string' ? args.exclude : args.exclude.join('\n')
      ignoreList = ignoreList.concat(args.exclude)
    }

    var filter = ignore.compile(ignoreList)

    args.path = args._[0]
    args.domain = args._[1]

    var tarstream = tar.pack(args.path, { ignore: filter })
    var headers = { domain: args.domain, authorization: `Bearer ${token}` }

    api.deploy(tarstream, headers, function (err, res, body) {
      if (err && err.message === 'socket hang up') {
        // ignore (TODO: figure out why deploys work but socket hang up still happens)
      } else if (err && err.message === 'Authorization failed') {
        return error('Your authentication token has expired. Please log in again using `staticland login`')
      } else if (err) {
        return error(err.message)
      }

      // TODO: show progress/completion
      console.log('domain ' + args.domain + ' successfully deployed')
    })
  },
  options: [
    {
      name: 'exclude',
      abbr: 'e',
      boolean: false,
      help: 'list of files and directories you want to exclude from the deployment'
    }
  ]
}
<|endoftext|>


<commit_before>const querystring = require('querystring');

module.exports = {
  name: 'google',
  pattern: '(please )?google (.+)',
  reply: function(message, match, reply) {
    const params = {
      q: match[2],
    };
    const site = match[1] ? 'http://lmgtfy.com/' : 'https://www.google.com/';
    const uri = `${site}?${querystring.stringify(params)}`;
    reply(`See [Google results for "${match[4]}"](${uri})`);
  }
};
<commit_msg>Fix Google command response #5<commit_after>const querystring = require('querystring');

module.exports = {
  name: 'google',
  pattern: '(please )?google (.+)',
  reply: function(message, match, reply) {
    const params = {
      q: match[2],
    };
    const site = match[1] ? 'http://lmgtfy.com/' : 'https://www.google.com/';
    const uri = `${site}?${querystring.stringify(params)}`;
    reply(`See [Google results for "${match[2]}"](${uri})`);
  }
};
<|endoftext|>


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

import React, {Component} from 'react'

import {BrowserRouter as Router, Redirect, Route, Switch} from 'react-router-dom'
// import {Apis, Base, Login, Logout, Endpoints} from './app/components'
import {PageNotFound} from './app/components/Base/Errors'
// import ApiCreate from './app/components/Apis/Create/ApiCreate'
import AuthManager from './app/data/AuthManager'
import qs from 'qs'
import Axios from 'axios';
import LoadingAnimation from './app/components/Base/Loading/Loading.js';
import {getAsyncComponent} from 'async-react-component';
import 'antd/dist/antd.css'
import {message} from 'antd'
import './App.css'
import Utils from "./app/data/Utils";

const Apis = () => import(/* webpackChunkName: "apis" */ './app/components/Apis/Apis');
const Endpoints = () => import(/* webpackChunkName: "endpoints" */ './app/components/Endpoints');
const ApiCreate = () => import(/* webpackChunkName: "create" */ './app/components/Apis/Create/ApiCreate');
const Base = () => import(/* webpackChunkName: "base" */ './app/components/Base');
const BaseLayout = getAsyncComponent(Base);
const Login = () => import(/* webpackChunkName: "login" */  './app/components/Login/Login');
const Logout = () => import(/* webpackChunkName: "logout" */ './app/components/Logout');

/**
 * Render protected application paths
 */
class Protected extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showLeftMenu: false,
            authConfigs: null
        };
        message.config({top: '48px'}); // .custom-header height + some offset
        /* TODO: need to fix the header to avoid conflicting with messages ~tmkb*/
    }

    handleResponse = (response) => {
        this.setState({
            authConfigs: response.data.members
        });
    };

    /**
     * Handle invalid login url in localStorage - environment object
     * @param reject
     */
    handleReject = reject => {
        console.log("Error: Single Sign On:\n", reject);
        Utils.setEnvironment(); //Set Default environment
        Axios.get(Utils.getAppLoginURL()).then(this.handleResponse); //Try login
    };

    /**
     * Change the visibility state of left side navigation menu bar
     * @param {boolean} status : Whether or not to show or hide left side navigation menu
     */
    setLeftMenu(status) {
        this.setState({
            showLeftMenu: status
        });
    }

    render() {
        // Note: AuthManager.getUser() method is a passive check, which simply check the user availability in browser storage,
        // Not actively check validity of access token from backend
        if (AuthManager.getUser()) {
            return (
                <BaseLayout>
                    <Switch>
                        <Redirect exact from="/" to="/apis"/>
                        <Route path={"/apis"} component={getAsyncComponent(Apis)}/>
                        <Route path={"/endpoints"} component={getAsyncComponent(Endpoints)}/>
                        <Route path={"/api/create"} component={getAsyncComponent(ApiCreate)}/>
                        <Route component={PageNotFound}/>
                    </Switch>
                </BaseLayout>
            );
        }

        let params = qs.stringify({referrer: this.props.location.pathname});
        return (
            <Redirect to={{pathname: '/login', search: params}}/>
        );
    }
}

/**
 * Define base routes for the application
 */
class Publisher extends Component {

    render() {
        return (
            <Router basename="/publisher">
                <Switch>
                    <Route path={"/login"} component={getAsyncComponent(Login)}/>
                    <Route path={"/logout"} component={getAsyncComponent(Logout)}/>
                    <Route component={Protected}/>
                </Switch>
            </Router>
        );
    }
}

export default Publisher;
<commit_msg>remove antd message config<commit_after>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React, {Component} from 'react'

import {BrowserRouter as Router, Redirect, Route, Switch} from 'react-router-dom'
// import {Apis, Base, Login, Logout, Endpoints} from './app/components'
import {PageNotFound} from './app/components/Base/Errors'
// import ApiCreate from './app/components/Apis/Create/ApiCreate'
import AuthManager from './app/data/AuthManager'
import qs from 'qs'
import Axios from 'axios';
import LoadingAnimation from './app/components/Base/Loading/Loading.js';
import {getAsyncComponent} from 'async-react-component';
import 'antd/dist/antd.css'
import './App.css'
import Utils from "./app/data/Utils";

const Apis = () => import(/* webpackChunkName: "apis" */ './app/components/Apis/Apis');
const Endpoints = () => import(/* webpackChunkName: "endpoints" */ './app/components/Endpoints');
const ApiCreate = () => import(/* webpackChunkName: "create" */ './app/components/Apis/Create/ApiCreate');
const Base = () => import(/* webpackChunkName: "base" */ './app/components/Base');
const BaseLayout = getAsyncComponent(Base);
const Login = () => import(/* webpackChunkName: "login" */  './app/components/Login/Login');
const Logout = () => import(/* webpackChunkName: "logout" */ './app/components/Logout');

/**
 * Render protected application paths
 */
class Protected extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showLeftMenu: false,
            authConfigs: null
        };
    }

    handleResponse = (response) => {
        this.setState({
            authConfigs: response.data.members
        });
    };

    /**
     * Handle invalid login url in localStorage - environment object
     * @param reject
     */
    handleReject = reject => {
        console.log("Error: Single Sign On:\n", reject);
        Utils.setEnvironment(); //Set Default environment
        Axios.get(Utils.getAppLoginURL()).then(this.handleResponse); //Try login
    };

    /**
     * Change the visibility state of left side navigation menu bar
     * @param {boolean} status : Whether or not to show or hide left side navigation menu
     */
    setLeftMenu(status) {
        this.setState({
            showLeftMenu: status
        });
    }

    render() {
        // Note: AuthManager.getUser() method is a passive check, which simply check the user availability in browser storage,
        // Not actively check validity of access token from backend
        if (AuthManager.getUser()) {
            return (
                <BaseLayout>
                    <Switch>
                        <Redirect exact from="/" to="/apis"/>
                        <Route path={"/apis"} component={getAsyncComponent(Apis)}/>
                        <Route path={"/endpoints"} component={getAsyncComponent(Endpoints)}/>
                        <Route path={"/api/create"} component={getAsyncComponent(ApiCreate)}/>
                        <Route component={PageNotFound}/>
                    </Switch>
                </BaseLayout>
            );
        }

        let params = qs.stringify({referrer: this.props.location.pathname});
        return (
            <Redirect to={{pathname: '/login', search: params}}/>
        );
    }
}

/**
 * Define base routes for the application
 */
class Publisher extends Component {

    render() {
        return (
            <Router basename="/publisher">
                <Switch>
                    <Route path={"/login"} component={getAsyncComponent(Login)}/>
                    <Route path={"/logout"} component={getAsyncComponent(Logout)}/>
                    <Route component={Protected}/>
                </Switch>
            </Router>
        );
    }
}

export default Publisher;
<|endoftext|>


<commit_before>window.AppView = Backbone.View.extend({
  el: $('#container'),

  initialize: function() {
    this.channelCollectionView = new ChannelCollectionView({
      collection: Channels
    }).render();

    this.relatedUsersView = new RelatedUsersView();
    this.channelView = new ChannelView();

    this.setupChannelReloading();

    if ( typeof currentChannel !== "undefined" ) {
      this.changeUser(currentChannel.user);
    } else {
      this.changeUser(currentUser);
    }
  },

  // TODO: This function needs to wait for loading (Of channel contents in main column)
  setupChannelReloading: function(){
    var args = arguments;
    setTimeout(function(){
      Channels.fetch({
        success: args.callee
      });
    }, 7000);
  },

  openChannel: function(channel) {
    var oldChannel = currentChannel;

    window.currentChannel = channel;

    if ( channel.user.id !== oldChannel.user.id ) {
      this.changeUser(channel.user);

      this.channelCollectionView.reload(currentChannel.id);
    }

    this.channelView = this.channelView.reInit({model: channel}).render();

    this.relatedUsersView
          .reInit({model:channel})
          .render();

    return this;
  },

  render: function() {
    $('#main-wrapper').html( this.channelView.el );
  },

  changeUser: function(user) {
    if ( this.userView ) {
      this.userView.close();
    }

    this.userView = new UserView({model: user}).render();
  }
});
<commit_msg>start of generalization<commit_after>window.AppView = Backbone.View.extend({
  el: $('#container'),

  initialize: function() {
    this.channelCollectionView = new ChannelCollectionView({
      collection: Channels
    }).render();

    this.channelView = new ChannelView();
    this.views = [new RelatedUsersView()];

    this.setupChannelReloading();

    if ( typeof currentChannel !== "undefined" ) {
      this.changeUser(currentChannel.user);
    } else {
      this.changeUser(currentUser);
    }
  },

  // TODO: This function needs to wait for loading (Of channel contents in main column)
  setupChannelReloading: function(){
    var args = arguments;
    setTimeout(function(){
      Channels.fetch({
        success: args.callee
      });
    }, 7000);
  },

  openChannel: function(channel) {
    var oldChannel = currentChannel;

    window.currentChannel = channel;

    if ( channel.user.id !== oldChannel.user.id ) {
      this.changeUser(channel.user);

      this.channelCollectionView.reload(currentChannel.id);
    }

    for(var i = 0; i < this.views.length; i++){
      this.views[i] = this.views[i].reInit({model: channel});
      this.views[i].render();
    }

    this.channelView = this.channelView.reInit({model: channel}).render();

    return this;
  },

  render: function() {
    $('#main-wrapper').html( this.channelView.el );
  },

  changeUser: function(user) {
    if ( this.userView ) {
      this.userView.close();
    }

    this.userView = new UserView({model: user}).render();
  }
});
<|endoftext|>


<commit_before>Ext.define('devilry_qualifiesforexam.utils.Breadcrumbs', {
    extend: 'devilry_subjectadmin.utils.Breadcrumbs',

    formatUrl: function (url, meta) {
        if(!Ext.isEmpty(meta) && meta.applocal) {
            return url;
        } else {
            // All breadcrumbs not marked as applocal are assumed to lead to devilry_subjectadmin.
            return Ext.String.format('{0}/devilry_subjectadmin/{1}',
                DevilrySettings.DEVILRY_URLPATH_PREFIX, url);
        }
    }
});<commit_msg>devilry_qualifiesforexam: Breadcrumb work with nodeadmin.<commit_after>Ext.define('devilry_qualifiesforexam.utils.Breadcrumbs', {
    extend: 'devilry_subjectadmin.utils.Breadcrumbs',

    formatUrl: function (url, meta) {
        if(!Ext.isEmpty(meta) && meta.applocal) {
            return url;
        } else if(url.match(/^#.*/)) {
            // All breadcrumbs not marked as applocal are assumed to lead to devilry_subjectadmin.
            return Ext.String.format('{0}/devilry_subjectadmin/{1}',
                DevilrySettings.DEVILRY_URLPATH_PREFIX, url);
        } else {
            return url;
        }
    }
});
<|endoftext|>


<commit_before>var http = require('http');

var servers = {
    init_key: 154669603, //used in initial packet id 255 and POST requests, hardcoded in client

    postRequest: function(opt, cb) {
        var ret = {
            error: null,
            error_source: null,
            res: null,
            data: null,
            server: null,
            key: null
        };

        var options = {
            host: 'm.agar.io',
            port: 80,
            path: opt.url || '/',
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': opt.data.length,
                'Origin': 'http://agar.io',
                'Referer': 'http://agar.io/'
            }
        };

        var req = http.request(options, function(res) {
            var server = '';

            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                server += chunk;
            });
            res.on('end', function() {
                var data = server.split('\n');

                if(res.statusCode != 200) {
                    ret.error = 'WRONG_HTTP_CODE';
                    ret.res = res;
                    ret.data = server;
                }else if(data.length != (opt.res_data_len || 3)) {
                    ret.error = 'WRONG_DATA_FORMAT';
                    ret.res = res;
                    ret.data = server;
                }else{
                    ret.res = res;
                    ret.data = server;
                    ret.server = data[0];
                    ret.key = data[1];
                }

                cb(ret);
            });
        });

        req.on('error', function(e) {
            ret.error = 'REQUEST_ERROR';
            ret.error_source = e;
            return cb(ret);
        });

        req.write(opt.data);
        req.end();
    },

    getFFAServer: function(opt, cb) {
        if(!opt) opt = {};
        var region = opt.region || 'EU-London';
        var post_opt = {
            data: region + '\n' + servers.init_key
        };
        servers.postRequest(post_opt, cb);
    },

    getTeamsServer: function(opt, cb) {
        if(!opt) opt = {};
        var region = opt.region || 'EU-London';
        var post_opt = {
            data: region + ':teams\n' + servers.init_key
        };
        servers.postRequest(post_opt, cb);
    },

    getExperimentalServer: function(opt, cb) {
        if(!opt) opt = {};
        var region = opt.region || 'EU-London';
        var post_opt = {
            data: region + ':experimental\n' + servers.init_key
        };
        servers.postRequest(post_opt, cb);
    },

    createParty: function(opt, cb) {
        if(!opt) opt = {};
        var region = opt.region || 'EU-London';
        var post_opt = {
            data: region + ':party\n' + servers.init_key
        };
        servers.postRequest(post_opt, cb);
    },

    getPartyServer: function(opt, cb) {
        if(!opt.party_key) throw new Error('getPartyServer wants opt.party_key');
        var post_opt = {
            url: '/getToken',
            data: opt.party_key,
            res_data_len: 2
        };
        servers.postRequest(post_opt, function(res) {
            if(!res.server) return cb(res);
            res.key = opt.party_key;
            cb(res);
        });
    }
};

module.exports = servers;<commit_msg>New data format in servers.js<commit_after>var http = require('http');

var servers = {
    init_key: 154669603, //used in initial packet id 255 and POST requests, hardcoded in client

    postRequest: function(opt, cb) {
        var ret = {
            error: null,
            error_source: null,
            res: null,
            data: null,
            server: null,
            key: null
        };

        var options = {
            host: 'm.agar.io',
            port: 80,
            path: opt.url || '/',
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': opt.data.length,
                'Origin': 'http://agar.io',
                'Referer': 'http://agar.io/'
            }
        };

        var req = http.request(options, function(res) {
            var server = '';

            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                server += chunk;
            });
            res.on('end', function() {
                var data = server.split('\n');

                if(res.statusCode != 200) {
                    ret.error = 'WRONG_HTTP_CODE';
                    ret.res = res;
                    ret.data = server;
                }else if(!data[opt.res_data_index || 1]) {
                    ret.error = 'WRONG_DATA_FORMAT';
                    ret.res = res;
                    ret.data = server;
                }else{
                    ret.res = res;
                    ret.data = server;
                    ret.server = data[0];
                    ret.key = data[1];
                }

                cb(ret);
            });
        });

        req.on('error', function(e) {
            ret.error = 'REQUEST_ERROR';
            ret.error_source = e;
            return cb(ret);
        });

        req.write(opt.data);
        req.end();
    },

    getFFAServer: function(opt, cb) {
        if(!opt) opt = {};
        var region = opt.region || 'EU-London';
        var post_opt = {
            data: region + '\n' + servers.init_key
        };
        servers.postRequest(post_opt, cb);
    },

    getTeamsServer: function(opt, cb) {
        if(!opt) opt = {};
        var region = opt.region || 'EU-London';
        var post_opt = {
            data: region + ':teams\n' + servers.init_key
        };
        servers.postRequest(post_opt, cb);
    },

    getExperimentalServer: function(opt, cb) {
        if(!opt) opt = {};
        var region = opt.region || 'EU-London';
        var post_opt = {
            data: region + ':experimental\n' + servers.init_key
        };
        servers.postRequest(post_opt, cb);
    },

    createParty: function(opt, cb) {
        if(!opt) opt = {};
        var region = opt.region || 'EU-London';
        var post_opt = {
            data: region + ':party\n' + servers.init_key
        };
        servers.postRequest(post_opt, cb);
    },

    getPartyServer: function(opt, cb) {
        if(!opt.party_key) throw new Error('getPartyServer wants opt.party_key');
        var post_opt = {
            url: '/getToken',
            data: opt.party_key,
            res_data_index: 0
        };
        servers.postRequest(post_opt, function(res) {
            if(!res.server) return cb(res);
            res.key = opt.party_key;
            cb(res);
        });
    }
};

module.exports = servers;<|endoftext|>


<commit_before>// Texpand
// Unobtrusively resize textarea's height as content is added.
//
// Copyright (c) 2008, Gianni Chiappetta - gianni[at]runlevel6[dot]org
//
// 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.

// Texpand Class
//------------------------------------------------------------------------------
var Texpand = Class.create();
Texpand.version = 0.6;
Texpand.prototype = {
  initialize: function(el, options) {
    this.options = {
      increment: 15,
	  autoShrink: false,
	  fontFamily: 'inherit',//this is neededed to make the font in ie match
      onExpand: Prototype.emptyFunction
    };
    Object.extend(this.options, options || {});

    // INIT
    this.element = $(el);

    // Requirements
    if (this.element.tagName.toLowerCase() != 'textarea') {
      throw ('Texpand: can only be initialized with a <textarea> but got <' + this.element.tagName.toLowerCase() + '>');
    }
    if (typeof Prototype == 'undefined' || (parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]) < 1.6)) {
      throw ('Texpand: requires Prototype 1.6.0+');
    }
    if (typeof Effect == 'undefined') {
      throw ('Textpand: requires Script.aculo.us, specifically Effects');
    }

    // Setup Textarea & mimic
    this.element.insert({after: '

'}).setStyle({resize: 'none', overflow: 'hidden'});
    this.mimic = this.element.next();
    this.mimic.update(this.element.value);

    // Fix default font size if in em's, based on a 10px em unit (This is an IE thing mainly)
    var fontSize = this.element.getStyle('fontSize');
    if (fontSize.search(/em/) >= 0) {
      var pixelSize = parseFloat(fontSize.replace(/em/, ''))*10;
      this.element.setStyle({fontSize: pixelSize+'px'});
    }

    // Duplicate style
    var style = {};
    var properties = $w('borderBottomColor borderBottomStyle borderBottomWidth borderTopColor borderTopStyle borderTopWidth borderRightColor borderRightStyle borderRightWidth borderLeftColor borderLeftStyle borderLeftWidth fontSize fontFamily fontWeight letterSpacing lineHeight marginTop marginRight marginBottom marginLeft paddingTop paddingRight paddingBottom paddingLeft textAlign textIndent width wordSpacing');
    for (var i=0, length=properties.length; i < length; i++) {
      style[properties[i]] = this.element.getStyle(properties[i]);
    }
    this.mimic.setStyle(Object.extend(style, {display: 'block', position: 'absolute', left: '-9999px', top: '-9999px'}));

    // Reset font-family (IE7 & IE8 issue)
    this.element.setStyle({fontFamily: this.options.fontFamily});
	this.mimic.setStyle({fontFamily: this.options.fontFamily});

    // Fix width for browser inconsistencies (Again an IE thing mainly) [Thanks tfluehr]
    var estimatedWidth = this.element.getWidth();
    if (estimatedWidth != this.mimic.getWidth()) {
      var tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('marginLeft'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('marginRight'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('borderLeftWidth'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('borderRightWidth'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('paddingLeft'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('paddingRight'),10)) ? 0 : tmpInt;
      estimatedWidth += 'px';
      this.mimic.setStyle({width: estimatedWidth});
    }

    // Listen
    this.element.observe("keyup", this._autoExpand.bind(this));

    return this.element;
  },

  // Auto expand height if required
  _autoExpand: function(ev) {
    this.mimic.update(this.element.value.replace(/\n/gm, '
') + '
');

    var mimicCurrentHeight    = this.mimic.getHeight();
    var elementCurrentHeight  = this.element.getHeight();
    var differenceHeight      = elementCurrentHeight-mimicCurrentHeight;
    var targetHeight          = elementCurrentHeight + (this.options.increment - differenceHeight);
	var func = function()
	{
		if (differenceHeight < 0 || (this.options.autoShrink && differenceHeight > this.options.increment))
		{
			// Clear queue
			var queue = Effect.Queues.get('texpand' + this.element.identify());
			queue.each(function(effect)
			{
				effect.cancel();
			});

			// Expand
			this.element.morph('height: ' + targetHeight + 'px;',
			{
				duration: 0.05,
				queue:
				{
					position: 'end',
					scope: 'texpand' + this.element.identify(),
					limit: 2
				}
			});
			this.options.onExpand.call(ev);
		}
	};
	if (ev)
	{
		//keeps the keyboard from slowing down ie by only running the
		//morph if the keyboard hasnt been touched for 0.2 seconds
		clearTimeout(this.keypressDelay);
		this.keypressDelay = func.bind(this).delay(0.2);
	}
	else
	{
		func();
	}

  },

  // Add text and resize
  appendText: function(text) {
    this.element.value += text;
    this._autoExpand();
  },

  // Replace text and resize
  setValue: function(text) {
    this.element.value = text;
    this._autoExpand();
  }
};
<commit_msg>timeout for keypress<commit_after>// Texpand
// Unobtrusively resize textarea's height as content is added.
//
// Copyright (c) 2008, Gianni Chiappetta - gianni[at]runlevel6[dot]org
//
// 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.

// Texpand Class
//------------------------------------------------------------------------------
var Texpand = Class.create();
Texpand.version = 0.6;
Texpand.prototype = {
  initialize: function(el, options) {
    this.options = {
      increment: 15,
	  autoShrink: false,
	  fontFamily: 'inherit',//this is neededed to make the font in ie match
      onExpand: Prototype.emptyFunction
    };
    Object.extend(this.options, options || {});

    // INIT
    this.element = $(el);

    // Requirements
    if (this.element.tagName.toLowerCase() != 'textarea') {
      throw ('Texpand: can only be initialized with a <textarea> but got <' + this.element.tagName.toLowerCase() + '>');
    }
    if (typeof Prototype == 'undefined' || (parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]) < 1.6)) {
      throw ('Texpand: requires Prototype 1.6.0+');
    }
    if (typeof Effect == 'undefined') {
      throw ('Textpand: requires Script.aculo.us, specifically Effects');
    }

    // Setup Textarea & mimic
    this.element.insert({after: '

'}).setStyle({resize: 'none', overflow: 'hidden'});
    this.mimic = this.element.next();
    this.mimic.update(this.element.value);

    // Fix default font size if in em's, based on a 10px em unit (This is an IE thing mainly)
    var fontSize = this.element.getStyle('fontSize');
    if (fontSize.search(/em/) >= 0) {
      var pixelSize = parseFloat(fontSize.replace(/em/, ''))*10;
      this.element.setStyle({fontSize: pixelSize+'px'});
    }

    // Duplicate style
    var style = {};
    var properties = $w('borderBottomColor borderBottomStyle borderBottomWidth borderTopColor borderTopStyle borderTopWidth borderRightColor borderRightStyle borderRightWidth borderLeftColor borderLeftStyle borderLeftWidth fontSize fontFamily fontWeight letterSpacing lineHeight marginTop marginRight marginBottom marginLeft paddingTop paddingRight paddingBottom paddingLeft textAlign textIndent width wordSpacing');
    for (var i=0, length=properties.length; i < length; i++) {
      style[properties[i]] = this.element.getStyle(properties[i]);
    }
    this.mimic.setStyle(Object.extend(style, {display: 'block', position: 'absolute', left: '-9999px', top: '-9999px'}));

    // Reset font-family (IE7 & IE8 issue)
    this.element.setStyle({fontFamily: this.options.fontFamily});
	this.mimic.setStyle({fontFamily: this.options.fontFamily});

    // Fix width for browser inconsistencies (Again an IE thing mainly) [Thanks tfluehr]
    var estimatedWidth = this.element.getWidth();
    if (estimatedWidth != this.mimic.getWidth()) {
      var tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('marginLeft'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('marginRight'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('borderLeftWidth'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('borderRightWidth'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('paddingLeft'),10)) ? 0 : tmpInt;
      estimatedWidth -= isNaN(tmpInt = parseInt(this.element.getStyle('paddingRight'),10)) ? 0 : tmpInt;
      estimatedWidth += 'px';
      this.mimic.setStyle({width: estimatedWidth});
    }

    // Listen
    this.element.observe("keyup", this._autoExpand.bind(this));

    return this.element;
  },

  // Auto expand height if required
  _autoExpand: function(ev) {

	var doExpand = function(ev)
	{
	    this.mimic.update(this.element.value.replace(/\n/gm, '
') + '
');
	    var mimicCurrentHeight    = this.mimic.getHeight();
	    var elementCurrentHeight  = this.element.getHeight();
	    var differenceHeight      = elementCurrentHeight-mimicCurrentHeight;
	    var targetHeight          = elementCurrentHeight + (this.options.increment - differenceHeight);
		if (differenceHeight < 0 || (this.options.autoShrink && differenceHeight > this.options.increment))
		{
			// Clear queue
			var queue = Effect.Queues.get('texpand' + this.element.identify());
			queue.each(function(effect)
			{
				effect.cancel();
			});

			// Expand
			this.element.morph('height: ' + targetHeight + 'px;',
			{
				duration: 0.05,
				queue:
				{
					position: 'end',
					scope: 'texpand' + this.element.identify(),
					limit: 2
				}
			});
			this.options.onExpand.call(ev);
		}
	}.bind(this);

	if (ev)
	{
		//keeps the keyboard from slowing down ie by only running the
		//morph if the keyboard hasnt been touched for 0.1 seconds
		clearTimeout(this.keypressDelay);
		this.keypressDelay = doExpand.delay(0.1, ev);
	}
	else
	{
		doExpand();
	}

  },

  // Add text and resize
  appendText: function(text) {
    this.element.value += text;
    this._autoExpand();
  },

  // Replace text and resize
  setValue: function(text) {
    this.element.value = text;
    this._autoExpand();
  }
};
<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */
"use strict";

const http = require('http'),
  https = require('https'),
  address = require('network-address'),
  Koa = require('kronos-koa'),
  IO = require('koa-socket'),
  Service = require('kronos-service').Service,
  ReceiveEndpoint = require('kronos-endpoint').ReceiveEndpoint;

const configAttributes = {
  port: {
    needsRestart: true,
    default: 9898
  },
  hostname: {
    needsRestart: true,
    default: address()
  },
  key: {
    needsRestart: true
  },
  cert: {
    needsRestart: true
  },
  timeout: {
    default: 120000
  },
  io: {
    needsRestart: true
  }
};

/**
 * HTTP server with koa
 */
class ServiceKOA extends Service {

  static get name() {
    return "koa";
  }

  get type() {
    return ServiceKOA.name;
  }

  constructor(config, owner) {
    super(config, owner);

    this.koa = new Koa();

    const props = {};

    Object.keys(configAttributes).forEach(name =>
      props[name] = {
        get() {
          return config[name] || configAttributes[name].default;
        }
      });

    Object.defineProperties(this, props);

    const io = new ReceiveEndpoint('io');
    io.receive = request => {
      if (this.koa.io) {
        this.koa.io.broadcast(request.event, request.data);
      }
      return Promise.resolve();
    };

    this.addEndpoint(io);
  }

  get isSecure() {
    return this.key !== undefined;
  }

  get serverOptions() {
    if (this.isSecure) {
      return {
        key: this.key,
        cert: this.cert
      };
    }

    return undefined;
  }

  get scheme() {
    return this.isSecure ? 'https' : 'http';
  }

  get url() {
    return `${this.scheme}://${this.hostname}:${this.port}`;
  }

  /**
   * apply new configuration.
   * if required restarts the server
   */
  configure(config) {
    const sp = super.configure(config);
    let needsRestart = false;

    if (config.timeout && this.server) {
      this.server.setTimeout(config.timeout);
    }

    Object.keys(configAttributes).forEach(name => {
      if (config[name] !== undefined && this[name] !== config[name]) {
        needsRestart |= configAttributes[name].needsRestart;
        this.config[name] = config[name];
      }
    });

    if (config.io) {
      const io = new IO();
      io.attach(this.koa);
    }

    return needsRestart ? sp.then(p => this.restartIfRunning()) : sp;
  }

  _start() {
    if (!this.server) {
      if (this.isSecure) {
        this.server = https.createServer(this.serverOptions, this.koa.callback());
      } else {
        this.server = http.createServer(this.koa.callback());
      }

      if (this.timeout) {
        this.server.setTimeout(this.timeout);
      }

      return new Promise((fullfill, reject) => {
        this.trace(level => `starting ${this.url}`);

        try {
          this.server.listen(this.port, this.hostname, err => {
            if (err) {
              this.server = undefined;
              reject(err);
            } else {
              fullfill();
            }
          });
        } catch (e) {
          this.error(e);
          reject(e);
        }
      });
    }

    return Promise.resolve();
  }

  _stop() {
    return new Promise((fulfill, reject) => {
      this.trace(level => `stopping ${this.url}`);

      this.server.close(err => {
        if (err) {
          reject(err);
        } else {
          this.server = undefined;
          fulfill();
        }
      });
    });
  }
}

module.exports.Service = ServiceKOA;
module.exports.registerWithManager = manager => manager.registerServiceFactory(ServiceKOA);
<commit_msg>fix(logging): trace websocket io<commit_after>/* jslint node: true, esnext: true */
"use strict";

const http = require('http'),
  https = require('https'),
  address = require('network-address'),
  Koa = require('kronos-koa'),
  IO = require('koa-socket'),
  Service = require('kronos-service').Service,
  ReceiveEndpoint = require('kronos-endpoint').ReceiveEndpoint;

const configAttributes = {
  port: {
    needsRestart: true,
    default: 9898
  },
  hostname: {
    needsRestart: true,
    default: address()
  },
  key: {
    needsRestart: true
  },
  cert: {
    needsRestart: true
  },
  timeout: {
    default: 120000
  },
  io: {
    needsRestart: true
  }
};

/**
 * HTTP server with koa
 */
class ServiceKOA extends Service {

  static get name() {
    return "koa";
  }

  get type() {
    return ServiceKOA.name;
  }

  constructor(config, owner) {
    super(config, owner);

    this.koa = new Koa();

    const props = {};

    Object.keys(configAttributes).forEach(name =>
      props[name] = {
        get() {
          return config[name] || configAttributes[name].default;
        }
      });

    Object.defineProperties(this, props);

    const io = new ReceiveEndpoint('io');
    io.receive = request => {
      this.trace(level => `broadcast ${request.data} to io`);
      if (this.koa.io) {
        this.koa.io.broadcast(request.event, request.data);
      }
      return Promise.resolve();
    };

    this.addEndpoint(io);
  }

  get isSecure() {
    return this.key !== undefined;
  }

  get serverOptions() {
    if (this.isSecure) {
      return {
        key: this.key,
        cert: this.cert
      };
    }

    return undefined;
  }

  get scheme() {
    return this.isSecure ? 'https' : 'http';
  }

  get url() {
    return `${this.scheme}://${this.hostname}:${this.port}`;
  }

  /**
   * apply new configuration.
   * if required restarts the server
   */
  configure(config) {
    const sp = super.configure(config);
    let needsRestart = false;

    if (config.timeout && this.server) {
      this.server.setTimeout(config.timeout);
    }

    Object.keys(configAttributes).forEach(name => {
      if (config[name] !== undefined && this[name] !== config[name]) {
        needsRestart |= configAttributes[name].needsRestart;
        this.config[name] = config[name];
      }
    });

    if (config.io) {
      const io = new IO();
      io.attach(this.koa);
    }

    return needsRestart ? sp.then(p => this.restartIfRunning()) : sp;
  }

  _start() {
    if (!this.server) {
      if (this.isSecure) {
        this.server = https.createServer(this.serverOptions, this.koa.callback());
      } else {
        this.server = http.createServer(this.koa.callback());
      }

      if (this.timeout) {
        this.server.setTimeout(this.timeout);
      }

      return new Promise((fullfill, reject) => {
        this.trace(level => `starting ${this.url}`);

        try {
          this.server.listen(this.port, this.hostname, err => {
            if (err) {
              this.server = undefined;
              reject(err);
            } else {
              fullfill();
            }
          });
        } catch (e) {
          this.error(e);
          reject(e);
        }
      });
    }

    return Promise.resolve();
  }

  _stop() {
    return new Promise((fulfill, reject) => {
      this.trace(level => `stopping ${this.url}`);

      this.server.close(err => {
        if (err) {
          reject(err);
        } else {
          this.server = undefined;
          fulfill();
        }
      });
    });
  }
}

module.exports.Service = ServiceKOA;
module.exports.registerWithManager = manager => manager.registerServiceFactory(ServiceKOA);
<|endoftext|>