<commit_before>import {
  POINTS_COUNT,
  DASHBOARD_QUOTAS,
  PROJECT_DASHBOARD_QUOTAS,
  ORGANIZATION_DASHBOARD_QUOTAS
} from './constants';

// @ngInject
export default class DashboardChartService {
  constructor($q, priceEstimationService, quotasService, $filter, features) {
    this.$q = $q;
    this.priceEstimationService = priceEstimationService;
    this.quotasService = quotasService;
    this.$filter = $filter;
    this.features = features;
  }

  clearServiceCache() {
    this.priceEstimationService.clearAllCacheForCurrentEndpoint();
    this.quotasService.clearAllCacheForCurrentEndpoint();
  }

  getOrganizationCharts(organization) {
    const quotas = this.getDashboardQuotas(ORGANIZATION_DASHBOARD_QUOTAS);
    this.clearServiceCache();
    if (this.features.isVisible('dashboard.total_cost')) {
      return this.$q.all([
        this.getCostChart(organization),
        this.getResourceHistoryCharts(quotas, organization)
      ]).then(charts => [charts[0]].concat(charts[1]));
    } else {
      return this.getResourceHistoryCharts(quotas, organization);
    }
  }

  getProjectCharts(project) {
    const quotas = this.getDashboardQuotas(PROJECT_DASHBOARD_QUOTAS);
    this.clearServiceCache();
    return this.getResourceHistoryCharts(quotas, project);
  }

  getDashboardQuotas(items) {
    return items.map(quota => angular.extend({quota: quota}, DASHBOARD_QUOTAS[quota]));
  }

  getResourceHistoryCharts(charts, scope) {
    charts = charts.filter(chart => !chart.feature || this.features.isVisible(chart.feature));

    var quotaMap = scope.quotas.reduce((map, quota) => {
      map[quota.name] = quota;
      return map;
    }, {});

    var validCharts = charts.filter(chart => !!quotaMap[chart.quota]);

    var promises = validCharts.map(chart => {
      chart.quota = quotaMap[chart.quota];
      return this.getQuotaHistory(chart.quota.url).then(data => {
        chart.current = data[data.length - 1].value;
        chart.data = data;
      });
    });

    return this.$q.all(promises).then(() => {
      angular.forEach(validCharts, chart => {
        if (chart.data && chart.data.length > 1) {
          chart.change = this.getRelativeChange([
            chart.data[chart.data.length - 1].value,
            chart.data[chart.data.length - 2].value
          ]);
        }
      });
      return validCharts;
    });
  }

  getQuotaHistory(url) {
    var end = moment.utc().add(1, 'day').unix();
    var start = moment.utc().subtract(1, 'month').unix();

    return this.quotasService.getHistory(url, start, end, POINTS_COUNT).then(items => {
      items = items.filter(item => {
        return !!item.object;
      }).map(item => {
        return {
          date: moment.unix(item.point).toDate(),
          value: item.object.usage
        };
      });

      items = this.padMissingValues(items);

      return items.map(item => {
        item.label = item.value + ' at ' + this.$filter('date', 'yyyy-MM-dd')(item.date);
        return item;
      });
    });
  }

  getCostChart(scope) {
    return this.priceEstimationService.getList({
      scope: scope.url
    }).then(estimates => {
      estimates = estimates.map(estimate => {
        return {
          value: estimate.total,
          date: new Date(estimate.year, estimate.month - 1, 1)
        };
      });

      estimates.reverse();
      estimates = this.padMissingValues(estimates, 'month');
      estimates = estimates.map(estimate => {
        estimate.label = this.$filter('defaultCurrency')(estimate.value) +  ' at ' +
                         this.$filter('date', 'yyyy-MM')(estimate.date);
        return estimate;
      });
      return {
        title: gettext('Total cost'),
        data: estimates,
        current: this.$filter('defaultCurrency')(estimates[estimates.length - 1].value),
        change: this.getRelativeChange([
          estimates[estimates.length - 1].value,
          estimates[estimates.length - 2].value
        ])
      };
    });
  }

  padMissingValues(items, interval) {
    var i = 1, end = moment();
    if (items.length > 0) {
      end = moment(items[items.length - 1].date);
    }
    while(items.length != POINTS_COUNT) {
      items.unshift({
        value: 0,
        date: new Date(end.subtract(i, interval).toDate())
      });
    }
    return items;
  }

  getRelativeChange(items) {
    if (items.length < 2) {
      return null;
    }
    // Latest values come first
    var last = items[0];
    var prev = items[1];
    var change = Math.round(100 * (last - prev) / prev);
    return Math.min(100, Math.max(-100, change));
  }
}
<commit_msg>Use invoices for customer price estimation chart [WAL-985]<commit_after>import {
  POINTS_COUNT,
  DASHBOARD_QUOTAS,
  PROJECT_DASHBOARD_QUOTAS,
  ORGANIZATION_DASHBOARD_QUOTAS
} from './constants';

// @ngInject
export default class DashboardChartService {
  constructor($q, currentStateService, invoicesService, quotasService, $filter, features) {
    this.$q = $q;
    this.currentStateService = currentStateService;
    this.invoicesService = invoicesService;
    this.quotasService = quotasService;
    this.$filter = $filter;
    this.features = features;
  }

  clearServiceCache() {
    this.invoicesService.clearAllCacheForCurrentEndpoint();
    this.quotasService.clearAllCacheForCurrentEndpoint();
  }

  getOrganizationCharts(organization) {
    const quotas = this.getDashboardQuotas(ORGANIZATION_DASHBOARD_QUOTAS);
    this.clearServiceCache();
    if (this.features.isVisible('dashboard.total_cost')) {
      return this.$q.all([
        this.getCostChart(organization),
        this.getResourceHistoryCharts(quotas, organization)
      ]).then(charts => [charts[0]].concat(charts[1]));
    } else {
      return this.getResourceHistoryCharts(quotas, organization);
    }
  }

  getProjectCharts(project) {
    const quotas = this.getDashboardQuotas(PROJECT_DASHBOARD_QUOTAS);
    this.clearServiceCache();
    return this.getResourceHistoryCharts(quotas, project);
  }

  getDashboardQuotas(items) {
    return items.map(quota => angular.extend({quota: quota}, DASHBOARD_QUOTAS[quota]));
  }

  getResourceHistoryCharts(charts, scope) {
    charts = charts.filter(chart => !chart.feature || this.features.isVisible(chart.feature));

    var quotaMap = scope.quotas.reduce((map, quota) => {
      map[quota.name] = quota;
      return map;
    }, {});

    var validCharts = charts.filter(chart => !!quotaMap[chart.quota]);

    var promises = validCharts.map(chart => {
      chart.quota = quotaMap[chart.quota];
      return this.getQuotaHistory(chart.quota.url).then(data => {
        chart.current = data[data.length - 1].value;
        chart.data = data;
      });
    });

    return this.$q.all(promises).then(() => {
      angular.forEach(validCharts, chart => {
        if (chart.data && chart.data.length > 1) {
          chart.change = this.getRelativeChange([
            chart.data[chart.data.length - 1].value,
            chart.data[chart.data.length - 2].value
          ]);
        }
      });
      return validCharts;
    });
  }

  getQuotaHistory(url) {
    var end = moment.utc().add(1, 'day').unix();
    var start = moment.utc().subtract(1, 'month').unix();

    return this.quotasService.getHistory(url, start, end, POINTS_COUNT).then(items => {
      items = items.filter(item => {
        return !!item.object;
      }).map(item => {
        return {
          date: moment.unix(item.point).toDate(),
          value: item.object.usage
        };
      });

      items = this.padMissingValues(items);

      return items.map(item => {
        item.label = item.value + ' at ' + this.$filter('date', 'yyyy-MM-dd')(item.date);
        return item;
      });
    });
  }

  getCostChart(scope) {
    return this.currentStateService.getCustomer().then(currentCustomer => {
      return this.invoicesService.getList({
        customer: currentCustomer.url
      }).then(invoices => {
        let items = invoices.map(invoice => {
          return {
            value: invoice.total,
            date: new Date(invoice.year, invoice.month - 1, 1)
          };
        });

        items.reverse();
        items = this.padMissingValues(items, 'month');
        items = items.map(item => {
          item.label = this.$filter('defaultCurrency')(item.value) +  ' at ' +
                       this.$filter('date', 'yyyy-MM')(item.date);
          return item;
        });
        return {
          title: gettext('Total cost'),
          data: items,
          current: this.$filter('defaultCurrency')(items[items.length - 1].value),
          change: this.getRelativeChange([
            items[items.length - 1].value,
            items[items.length - 2].value
          ])
        };
      });
    });
  }

  padMissingValues(items, interval) {
    var i = 1, end = moment();
    if (items.length > 0) {
      end = moment(items[items.length - 1].date);
    }
    while(items.length != POINTS_COUNT) {
      items.unshift({
        value: 0,
        date: new Date(end.subtract(i, interval).toDate())
      });
    }
    return items;
  }

  getRelativeChange(items) {
    if (items.length < 2) {
      return null;
    }
    // Latest values come first
    var last = items[0];
    var prev = items[1];
    var change = Math.round(100 * (last - prev) / prev);
    return Math.min(100, Math.max(-100, change));
  }
}
<|endoftext|>


<commit_before>'use strict';

/*globals accounting*/

angular.module('main')
.controller('ComparisonValidationsDashboardCtrl', function($scope, $http, $location, $state, $backend, QueriesService) {
    $scope.service = (new QueriesService($backend.API_URL + '/_queries/public/api'));
    $scope.selection = {};
    $scope.showtab = [];
    $scope.reports = [];
    $scope.reportname = 'FundamentalAccountingConcepts';
    $scope.filings = null;
    $scope.error = false;
    $scope.errormany = false;

    $scope.$on('filterChanged', function(event, selection) {
        $scope.selection = angular.copy(selection);
        if (!selection) { return; }

        $location.search($scope.selection);

        $scope.filings = null;
        $scope.error = false;
        $scope.errormany = false;

        $scope.service.listFilings({
            $method: 'POST',
            cik: selection.cik,
            tag: selection.tag,
            fiscalYear: selection.fiscalYear,
            fiscalPeriod: selection.fiscalPeriod,
            token: $scope.token
        }).then(function(data) {
            $scope.filings = [];
            data.Archives.forEach(function(a) { $scope.filings.push(a.AccessionNumber); });
            if ($scope.filings.length > 30 && !$scope.nomany) {
                $scope.reports = [];
                $scope.errormany = true;
            } else {
                $scope.getInfo();
            }
        },
        function(response) {
            $scope.$emit('error', response.status, response.data);
        });
    });

    $scope.getInfo = function() {

        $scope.reports = [];
        $scope.params = {
                _method: 'POST',
                aid: $scope.filings,
                report: 'FundamentalAccountingConcepts',
                'token' : $scope.token
            };
        var promiseResponse = $backend.getFactsForReport($scope.params);
        promiseResponse.then(
            $scope.prepareReportForUI,
            function (data, status) {
              if (status === 401) {
                $scope.error = true;
              } else {
                $scope.$emit('error', status, data);
              }
            }
          );
    };

    $scope.prepareReportForUI = function(data) {
      $scope.reports = [];
      $scope.showtab = [];

      for (var i = 0; i < data.length; i++)
      {
        var root =
          data[i].Trees['fac:FundamentalAccountingConceptsLineItems']
          .To['fac:FundamentalAccountingConceptsHierarchy'].To;

        var report = {};
        report.entity =
          root["fac:GeneralInformationHierarchy"]
            .To["fac:EntityRegistrantName"].Facts[0].Value;
        report.period =
          root["fac:GeneralInformationHierarchy"]
            .To["fac:FiscalPeriod"].Facts[0].Value;
        report.year =
          root["fac:GeneralInformationHierarchy"]
            .To["fac:FiscalYear"].Facts[0].Value;
        report.passed =
          root["fac:ValidationStatistics"]
            .To["fac:PassedValidations"].Facts[0].Value;
        report.failed =
          root["fac:ValidationStatistics"]
            .To["fac:FailedValidations"].Facts[0].Value;
        report.notApplicable =
          root["fac:ValidationStatistics"]
            .To["fac:NotApplicableValidations"].Facts[0].Value;

        var k = 0;
        var validations =
          root["fac:Validations"].To;
        var details = [];
        for (var key in validations) {
          var detail = {};
          detail.name = validations[key].Name;
          detail.label = validations[key].Label;
          if(validations[key].Facts.length == 0)
          {
            detail.skipped = true;
          }else{
            var fact = validations[key].Facts[0];
            detail.passed = fact.Value;
            detail.message = fact.AuditTrails[0].Message;
          }
          details.push(detail);
        }//for
        report.details = details;

        $scope.reports.push(report);
        // tab should be closed
        $scope.showtab.push(false);
        $scope.$apply()

      }//for

      $scope.error = false;
      $scope.errormany = false;
    };

    $scope.forceShow = function() {
        $scope.nomany=true;
        $scope.getInfo();
    };

    $scope.drill = function(cik, year, period) {
        $state.go('root.entity.information', { cik: cik, year: year, period: period });
    };

    $scope.isBlock = function(string) {
        if (!string) {
            return false;
        }
        return string.length > 60;
    };

    $scope.showText = function(html) {
        $scope.$emit('alert', 'Text Details', html);
    };

    $scope.getUrl = function(format) {
        var str = $backend.API_URL + '/_queries/public/api/facts.jq';
        var params = angular.copy($scope.params);
        if (params) {
          params.cik = $scope.selection.cik;
          params.tag = $scope.selection.tag;
          fiscalYear: $scope.selection.fiscalYear,
          fiscalPeriod: $scope.selection.fiscalPeriod,
          params.concept = ["fac:PassedValidations", "fac:FailedValidations", "fac:NotApplicableValidations"];
          params.map = $scope.reportname;
          params.rules = $scope.reportname;
        }
        if (format) {
            params.format = format;
        }
        var qs = $scope.wwwFormUrlencoded(params);
        if (qs) {
            str += '?' + qs;
        }
        return str;
    };

    $scope.$on('$stateChangeSuccess', function(event, toState) {
        $scope.subActive = toState.data && toState.data.subActive;
    });
});
<commit_msg>- fixed fiscalYear and fiscalPeriod parameters syntax error<commit_after>'use strict';

/*globals accounting*/

angular.module('main')
.controller('ComparisonValidationsDashboardCtrl', function($scope, $http, $location, $state, $backend, QueriesService) {
    $scope.service = (new QueriesService($backend.API_URL + '/_queries/public/api'));
    $scope.selection = {};
    $scope.showtab = [];
    $scope.reports = [];
    $scope.reportname = 'FundamentalAccountingConcepts';
    $scope.filings = null;
    $scope.error = false;
    $scope.errormany = false;

    $scope.$on('filterChanged', function(event, selection) {
        $scope.selection = angular.copy(selection);
        if (!selection) { return; }

        $location.search($scope.selection);

        $scope.filings = null;
        $scope.error = false;
        $scope.errormany = false;

        $scope.service.listFilings({
            $method: 'POST',
            cik: selection.cik,
            tag: selection.tag,
            fiscalYear: selection.fiscalYear,
            fiscalPeriod: selection.fiscalPeriod,
            token: $scope.token
        }).then(function(data) {
            $scope.filings = [];
            data.Archives.forEach(function(a) { $scope.filings.push(a.AccessionNumber); });
            if ($scope.filings.length > 30 && !$scope.nomany) {
                $scope.reports = [];
                $scope.errormany = true;
            } else {
                $scope.getInfo();
            }
        },
        function(response) {
            $scope.$emit('error', response.status, response.data);
        });
    });

    $scope.getInfo = function() {

        $scope.reports = [];
        $scope.params = {
                _method: 'POST',
                aid: $scope.filings,
                fiscalYear : $scope.selection.fiscalYear,
                fiscalPeriod : $scope.selection.fiscalPeriod,
                report: 'FundamentalAccountingConcepts',
                'token' : $scope.token
            };
        var promiseResponse = $backend.getFactsForReport($scope.params);
        promiseResponse.then(
            $scope.prepareReportForUI,
            function (data, status) {
              if (status === 401) {
                $scope.error = true;
              } else {
                $scope.$emit('error', status, data);
              }
            }
          );
    };

    $scope.prepareReportForUI = function(data) {
      $scope.reports = [];
      $scope.showtab = [];

      for (var i = 0; i < data.length; i++)
      {
        var root =
          data[i].Trees['fac:FundamentalAccountingConceptsLineItems']
          .To['fac:FundamentalAccountingConceptsHierarchy'].To;

        var report = {};
        report.entity =
          root["fac:GeneralInformationHierarchy"]
            .To["fac:EntityRegistrantName"].Facts[0].Value;
        report.period =
          root["fac:GeneralInformationHierarchy"]
            .To["fac:FiscalPeriod"].Facts[0].Value;
        report.year =
          root["fac:GeneralInformationHierarchy"]
            .To["fac:FiscalYear"].Facts[0].Value;
        report.passed =
          root["fac:ValidationStatistics"]
            .To["fac:PassedValidations"].Facts[0].Value;
        report.failed =
          root["fac:ValidationStatistics"]
            .To["fac:FailedValidations"].Facts[0].Value;
        report.notApplicable =
          root["fac:ValidationStatistics"]
            .To["fac:NotApplicableValidations"].Facts[0].Value;

        var k = 0;
        var validations =
          root["fac:Validations"].To;
        var details = [];
        for (var key in validations) {
          var detail = {};
          detail.name = validations[key].Name;
          detail.label = validations[key].Label;
          if(validations[key].Facts.length == 0)
          {
            detail.skipped = true;
          }else{
            var fact = validations[key].Facts[0];
            detail.passed = fact.Value;
            detail.message = fact.AuditTrails[0].Message;
          }
          details.push(detail);
        }//for
        report.details = details;

        $scope.reports.push(report);
        // tab should be closed
        $scope.showtab.push(false);
      }//for

      $scope.error = false;
      $scope.errormany = false;
    };

    $scope.forceShow = function() {
        $scope.nomany=true;
        $scope.getInfo();
    };

    $scope.drill = function(cik, year, period) {
        $state.go('root.entity.information', { cik: cik, year: year, period: period });
    };

    $scope.isBlock = function(string) {
        if (!string) {
            return false;
        }
        return string.length > 60;
    };

    $scope.showText = function(html) {
        $scope.$emit('alert', 'Text Details', html);
    };

    $scope.getUrl = function(format) {
        var str = $backend.API_URL + '/_queries/public/api/facts.jq';
        var params = angular.copy($scope.params);
        if (params) {
          params.cik = $scope.selection.cik;
          params.tag = $scope.selection.tag;
          params.concept = ["fac:PassedValidations", "fac:FailedValidations", "fac:NotApplicableValidations"];
          params.map = $scope.reportname;
          params.rules = $scope.reportname;
        }
        if (format) {
            params.format = format;
        }
        var qs = $scope.wwwFormUrlencoded(params);
        if (qs) {
            str += '?' + qs;
        }
        return str;
    };

    $scope.$on('$stateChangeSuccess', function(event, toState) {
        $scope.subActive = toState.data && toState.data.subActive;
    });
});
<|endoftext|>


<commit_before>// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks

import * as Common from '../common/common.js';
import * as Persistence from '../persistence/persistence.js';
import * as QuickOpen from '../quick_open/quick_open.js';
import * as UI from '../ui/ui.js';
import * as Workspace from '../workspace/workspace.js';

import {FilePathScoreFunction} from './FilePathScoreFunction.js';

/**
 * @unrestricted
 */
export class FilteredUISourceCodeListProvider extends QuickOpen.FilteredListWidget.Provider {
  constructor() {
    super();

    this._queryLineNumberAndColumnNumber = '';
    this._defaultScores = null;
    this._scorer = new FilePathScoreFunction('');
  }

  /**
   * @param {!Common.EventTarget.EventTargetEvent} event
   */
  _projectRemoved(event) {
    const project = /** @type {!Workspace.Workspace.Project} */ (event.data);
    this._populate(project);
    this.refresh();
  }

  /**
   * @param {!Workspace.Workspace.Project=} skipProject
   */
  _populate(skipProject) {
    /** @type {!Array.<!Workspace.UISourceCode.UISourceCode>} */
    this._uiSourceCodes = [];
    const projects = Workspace.Workspace.WorkspaceImpl.instance().projects().filter(this.filterProject.bind(this));
    for (let i = 0; i < projects.length; ++i) {
      if (skipProject && projects[i] === skipProject) {
        continue;
      }
      const uiSourceCodes = projects[i].uiSourceCodes().filter(this._filterUISourceCode.bind(this));
      this._uiSourceCodes = this._uiSourceCodes.concat(uiSourceCodes);
    }
  }

  /**
   * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode
   * @return {boolean}
   */
  _filterUISourceCode(uiSourceCode) {
    const binding = Persistence.Persistence.PersistenceImpl.instance().binding(uiSourceCode);
    return !binding || binding.fileSystem === uiSourceCode;
  }

  /**
   * @param {?Workspace.UISourceCode.UISourceCode} uiSourceCode
   * @param {number=} lineNumber
   * @param {number=} columnNumber
   */
  uiSourceCodeSelected(uiSourceCode, lineNumber, columnNumber) {
    // Overridden by subclasses
  }

  /**
   * @param {!Workspace.Workspace.Project} project
   * @return {boolean}
   */
  filterProject(project) {
    return true;
    // Overridden by subclasses
  }

  /**
   * @override
   * @return {number}
   */
  itemCount() {
    return this._uiSourceCodes.length;
  }

  /**
   * @override
   * @param {number} itemIndex
   * @return {string}
   */
  itemKeyAt(itemIndex) {
    return this._uiSourceCodes[itemIndex].url();
  }

  /**
   * @protected
   * @param {?Map.<!Workspace.UISourceCode.UISourceCode, number>} defaultScores
   */
  setDefaultScores(defaultScores) {
    this._defaultScores = defaultScores;
  }

  /**
   * @override
   * @param {number} itemIndex
   * @param {string} query
   * @return {number}
   */
  itemScoreAt(itemIndex, query) {
    const uiSourceCode = this._uiSourceCodes[itemIndex];
    const score = this._defaultScores ? (this._defaultScores.get(uiSourceCode) || 0) : 0;
    if (!query || query.length < 2) {
      return score;
    }

    if (this._query !== query) {
      this._query = query;
      this._scorer = new FilePathScoreFunction(query);
    }

    let multiplier = 10;
    if (uiSourceCode.project().type() === Workspace.Workspace.projectTypes.FileSystem &&
        !Persistence.Persistence.PersistenceImpl.instance().binding(uiSourceCode)) {
      multiplier = 5;
    }

    const fullDisplayName = uiSourceCode.fullDisplayName();
    return score + multiplier * this._scorer.score(fullDisplayName, null);
  }

  /**
   * @override
   * @param {number} itemIndex
   * @param {string} query
   * @param {!Element} titleElement
   * @param {!Element} subtitleElement
   */
  renderItem(itemIndex, query, titleElement, subtitleElement) {
    query = this.rewriteQuery(query);
    const uiSourceCode = this._uiSourceCodes[itemIndex];
    const fullDisplayName = uiSourceCode.fullDisplayName();
    const indexes = [];
    new FilePathScoreFunction(query).score(fullDisplayName, indexes);
    const fileNameIndex = fullDisplayName.lastIndexOf('/');

    titleElement.classList.add('monospace');
    subtitleElement.classList.add('monospace');
    titleElement.textContent = uiSourceCode.displayName() + (this._queryLineNumberAndColumnNumber || '');
    this._renderSubtitleElement(subtitleElement, fullDisplayName);
    subtitleElement.title = fullDisplayName;
    const ranges = [];
    for (let i = 0; i < indexes.length; ++i) {
      ranges.push({offset: indexes[i], length: 1});
    }

    if (indexes[0] > fileNameIndex) {
      for (let i = 0; i < ranges.length; ++i) {
        ranges[i].offset -= fileNameIndex + 1;
      }
      UI.UIUtils.highlightRangesWithStyleClass(titleElement, ranges, 'highlight');
    } else {
      UI.UIUtils.highlightRangesWithStyleClass(subtitleElement, ranges, 'highlight');
    }
  }

  /**
   * @param {!Element} element
   * @param {string} text
   */
  _renderSubtitleElement(element, text) {
    element.removeChildren();
    let splitPosition = text.lastIndexOf('/');
    if (text.length > 55) {
      splitPosition = text.length - 55;
    }
    const first = element.createChild('div', 'first-part');
    first.textContent = text.substring(0, splitPosition);
    const second = element.createChild('div', 'second-part');
    second.textContent = text.substring(splitPosition);
    element.title = text;
  }

  /**
   * @override
   * @param {?number} itemIndex
   * @param {string} promptValue
   */
  selectItem(itemIndex, promptValue) {
    const parsedExpression = promptValue.trim().match(/^([^:]*)(:\d+)?(:\d+)?$/);
    if (!parsedExpression) {
      return;
    }

    let lineNumber;
    let columnNumber;
    if (parsedExpression[2]) {
      lineNumber = parseInt(parsedExpression[2].substr(1), 10) - 1;
    }
    if (parsedExpression[3]) {
      columnNumber = parseInt(parsedExpression[3].substr(1), 10) - 1;
    }
    const uiSourceCode = itemIndex !== null ? this._uiSourceCodes[itemIndex] : null;
    this.uiSourceCodeSelected(uiSourceCode, lineNumber, columnNumber);
  }

  /**
   * @override
   * @param {string} query
   * @return {string}
   */
  rewriteQuery(query) {
    query = query ? query.trim() : '';
    if (!query || query === ':') {
      return '';
    }
    const lineNumberMatch = query.match(/^([^:]+)((?::[^:]*){0,2})$/);
    this._queryLineNumberAndColumnNumber = lineNumberMatch ? lineNumberMatch[2] : '';
    return lineNumberMatch ? lineNumberMatch[1] : query;
  }

  /**
   * @param {!Common.EventTarget.EventTargetEvent} event
   */
  _uiSourceCodeAdded(event) {
    const uiSourceCode = /** @type {!Workspace.UISourceCode.UISourceCode} */ (event.data);
    if (!this._filterUISourceCode(uiSourceCode) || !this.filterProject(uiSourceCode.project())) {
      return;
    }
    this._uiSourceCodes.push(uiSourceCode);
    this.refresh();
  }

  /**
   * @override
   * @return {string}
   */
  notFoundText() {
    return Common.UIString.UIString('No files found');
  }

  /**
   * @override
   */
  attach() {
    Workspace.Workspace.WorkspaceImpl.instance().addEventListener(
        Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    Workspace.Workspace.WorkspaceImpl.instance().addEventListener(
        Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this);
    this._populate();
  }

  /**
   * @override
   */
  detach() {
    Workspace.Workspace.WorkspaceImpl.instance().removeEventListener(
        Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    Workspace.Workspace.WorkspaceImpl.instance().removeEventListener(
        Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this);
    this._queryLineNumberAndColumnNumber = '';
    this._defaultScores = null;
  }
}
<commit_msg>[ts] Type-check sources/FilteredUISourceCodeListProvider with TypeScript<commit_after>// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../common/common.js';
import * as Persistence from '../persistence/persistence.js';
import * as QuickOpen from '../quick_open/quick_open.js';
import * as UI from '../ui/ui.js';
import * as Workspace from '../workspace/workspace.js';

import {FilePathScoreFunction} from './FilePathScoreFunction.js';

export class FilteredUISourceCodeListProvider extends QuickOpen.FilteredListWidget.Provider {
  constructor() {
    super();

    this._queryLineNumberAndColumnNumber = '';
    this._defaultScores = null;
    this._scorer = new FilePathScoreFunction('');

    /** @type {!Array.<!Workspace.UISourceCode.UISourceCode>} */
    this._uiSourceCodes = [];

    /** @type {string} */
    this._query;
  }

  /**
   * @param {!Common.EventTarget.EventTargetEvent} event
   */
  _projectRemoved(event) {
    const project = /** @type {!Workspace.Workspace.Project} */ (event.data);
    this._populate(project);
    this.refresh();
  }

  /**
   * @param {!Workspace.Workspace.Project=} skipProject
   */
  _populate(skipProject) {
    this._uiSourceCodes = [];
    const projects = Workspace.Workspace.WorkspaceImpl.instance().projects().filter(this.filterProject.bind(this));
    for (let i = 0; i < projects.length; ++i) {
      if (skipProject && projects[i] === skipProject) {
        continue;
      }
      const uiSourceCodes = projects[i].uiSourceCodes().filter(this._filterUISourceCode.bind(this));
      this._uiSourceCodes = this._uiSourceCodes.concat(uiSourceCodes);
    }
  }

  /**
   * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode
   * @return {boolean}
   */
  _filterUISourceCode(uiSourceCode) {
    const binding = Persistence.Persistence.PersistenceImpl.instance().binding(uiSourceCode);
    return !binding || binding.fileSystem === uiSourceCode;
  }

  /**
   * @param {?Workspace.UISourceCode.UISourceCode} uiSourceCode
   * @param {number=} lineNumber
   * @param {number=} columnNumber
   */
  uiSourceCodeSelected(uiSourceCode, lineNumber, columnNumber) {
    // Overridden by subclasses
  }

  /**
   * @param {!Workspace.Workspace.Project} project
   * @return {boolean}
   */
  filterProject(project) {
    return true;
    // Overridden by subclasses
  }

  /**
   * @override
   * @return {number}
   */
  itemCount() {
    return this._uiSourceCodes.length;
  }

  /**
   * @override
   * @param {number} itemIndex
   * @return {string}
   */
  itemKeyAt(itemIndex) {
    return this._uiSourceCodes[itemIndex].url();
  }

  /**
   * @protected
   * @param {?Map.<!Workspace.UISourceCode.UISourceCode, number>} defaultScores
   */
  setDefaultScores(defaultScores) {
    this._defaultScores = defaultScores;
  }

  /**
   * @override
   * @param {number} itemIndex
   * @param {string} query
   * @return {number}
   */
  itemScoreAt(itemIndex, query) {
    const uiSourceCode = this._uiSourceCodes[itemIndex];
    const score = this._defaultScores ? (this._defaultScores.get(uiSourceCode) || 0) : 0;
    if (!query || query.length < 2) {
      return score;
    }

    if (this._query !== query) {
      this._query = query;
      this._scorer = new FilePathScoreFunction(query);
    }

    let multiplier = 10;
    if (uiSourceCode.project().type() === Workspace.Workspace.projectTypes.FileSystem &&
        !Persistence.Persistence.PersistenceImpl.instance().binding(uiSourceCode)) {
      multiplier = 5;
    }

    const fullDisplayName = uiSourceCode.fullDisplayName();
    return score + multiplier * this._scorer.score(fullDisplayName, null);
  }

  /**
   * @override
   * @param {number} itemIndex
   * @param {string} query
   * @param {!Element} titleElement
   * @param {!Element} subtitleElement
   */
  renderItem(itemIndex, query, titleElement, subtitleElement) {
    query = this.rewriteQuery(query);
    const uiSourceCode = this._uiSourceCodes[itemIndex];
    const fullDisplayName = uiSourceCode.fullDisplayName();
    /** @type {!Array<number>} */
    const indexes = [];
    new FilePathScoreFunction(query).score(fullDisplayName, indexes);
    const fileNameIndex = fullDisplayName.lastIndexOf('/');

    titleElement.classList.add('monospace');
    subtitleElement.classList.add('monospace');
    titleElement.textContent = uiSourceCode.displayName() + (this._queryLineNumberAndColumnNumber || '');
    this._renderSubtitleElement(subtitleElement, fullDisplayName);
    /** @type {!HTMLElement} */ (subtitleElement).title = fullDisplayName;
    const ranges = [];
    for (let i = 0; i < indexes.length; ++i) {
      ranges.push({offset: indexes[i], length: 1});
    }

    if (indexes[0] > fileNameIndex) {
      for (let i = 0; i < ranges.length; ++i) {
        ranges[i].offset -= fileNameIndex + 1;
      }
      UI.UIUtils.highlightRangesWithStyleClass(titleElement, ranges, 'highlight');
    } else {
      UI.UIUtils.highlightRangesWithStyleClass(subtitleElement, ranges, 'highlight');
    }
  }

  /**
   * @param {!Element} element
   * @param {string} text
   */
  _renderSubtitleElement(element, text) {
    element.removeChildren();
    let splitPosition = text.lastIndexOf('/');
    if (text.length > 55) {
      splitPosition = text.length - 55;
    }
    const first = element.createChild('div', 'first-part');
    first.textContent = text.substring(0, splitPosition);
    const second = element.createChild('div', 'second-part');
    second.textContent = text.substring(splitPosition);
    /** @type {!HTMLElement} */ (element).title = text;
  }

  /**
   * @override
   * @param {?number} itemIndex
   * @param {string} promptValue
   */
  selectItem(itemIndex, promptValue) {
    const parsedExpression = promptValue.trim().match(/^([^:]*)(:\d+)?(:\d+)?$/);
    if (!parsedExpression) {
      return;
    }

    let lineNumber;
    let columnNumber;
    if (parsedExpression[2]) {
      lineNumber = parseInt(parsedExpression[2].substr(1), 10) - 1;
    }
    if (parsedExpression[3]) {
      columnNumber = parseInt(parsedExpression[3].substr(1), 10) - 1;
    }
    const uiSourceCode = itemIndex !== null ? this._uiSourceCodes[itemIndex] : null;
    this.uiSourceCodeSelected(uiSourceCode, lineNumber, columnNumber);
  }

  /**
   * @override
   * @param {string} query
   * @return {string}
   */
  rewriteQuery(query) {
    query = query ? query.trim() : '';
    if (!query || query === ':') {
      return '';
    }
    const lineNumberMatch = query.match(/^([^:]+)((?::[^:]*){0,2})$/);
    this._queryLineNumberAndColumnNumber = lineNumberMatch ? lineNumberMatch[2] : '';
    return lineNumberMatch ? lineNumberMatch[1] : query;
  }

  /**
   * @param {!Common.EventTarget.EventTargetEvent} event
   */
  _uiSourceCodeAdded(event) {
    const uiSourceCode = /** @type {!Workspace.UISourceCode.UISourceCode} */ (event.data);
    if (!this._filterUISourceCode(uiSourceCode) || !this.filterProject(uiSourceCode.project())) {
      return;
    }
    this._uiSourceCodes.push(uiSourceCode);
    this.refresh();
  }

  /**
   * @override
   * @return {string}
   */
  notFoundText() {
    return Common.UIString.UIString('No files found');
  }

  /**
   * @override
   */
  attach() {
    Workspace.Workspace.WorkspaceImpl.instance().addEventListener(
        Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    Workspace.Workspace.WorkspaceImpl.instance().addEventListener(
        Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this);
    this._populate();
  }

  /**
   * @override
   */
  detach() {
    Workspace.Workspace.WorkspaceImpl.instance().removeEventListener(
        Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    Workspace.Workspace.WorkspaceImpl.instance().removeEventListener(
        Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this);
    this._queryLineNumberAndColumnNumber = '';
    this._defaultScores = null;
  }
}
<|endoftext|>


<commit_before>/* global require */
var http = require('http');
var fs = require('fs');
var express = require('express');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3001);

app.use(express.static(path.join(__dirname, '/public/app')));

app.get('/', function(req, res) {
  res.sendfile('public/app/base.html');
});

app.get('/api/chapters', chapters);
app.get('/api/chapters/:chapter_name', sanitize, chapter);
app.get('/api/chapters/:chapter_name/:directory', sanitize, chapter_directory);
app.use(express.static(__dirname + '/public/app'));

function sanitize(req, res, next) {
  for (var key in req.params) {
    if (req.params[key].indexOf(".") > -1) {
      return res.json(400, "Bad request");
    }
  }
  next();
}

function chapters(req, res) {
  function callback(err, files) {
    res.json(200, files);
  }

  fs.readdir('chapters', callback);
}

function chapter(req, res) {
  function callback(err, files) {
    res.json(200, files);
  }

  fs.readdir('chapters/' + req.params.chapter_name, callback);
}

function chapter_directory(req, res) {

  function callback(err, files) {
    var data = [];

    for (var i=0; i<files.length; i++) {
      try {
        var d = require('./chapters/' + req.params.chapter_name + '/' + req.params.directory + '/' + files[i]);
        data.push(d)
      } catch(exception) {}
    }

    res.json(200, data);
  }

  fs.readdir('chapters/' + req.params.chapter_name + '/' + req.params.directory, callback);
}

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>[refactor] clean up file loading in main route because OCD<commit_after>/* global require */
var http = require('http');
var fs = require('fs');
var path = require('path');
var express = require('express');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3001);

app.use(express.static(path.join(__dirname, '/public/app')));

app.get('/', function(req, res) {
  res.sendfile('public/app/base.html');
});

app.get('/api/chapters', chapters);
app.get('/api/chapters/:chapter_name', sanitize, chapter);
app.get('/api/chapters/:chapter_name/:directory', sanitize, chapter_directory);
app.use(express.static(__dirname + '/public/app'));

function sanitize(req, res, next) {
  for (var key in req.params) {
    if (req.params[key].indexOf(".") > -1) {
      return res.json(400, "Bad request");
    }
  }
  next();
}

function chapters(req, res) {
  function callback(err, files) {
    res.json(200, files);
  }

  fs.readdir('chapters', callback);
}

function chapter(req, res) {
  function callback(err, files) {
    res.json(200, files);
  }

  fs.readdir('chapters/' + req.params.chapter_name, callback);
}

function chapter_directory(req, res) {

  function callback(err, files) {
    //
    // Validate the files are json before we try and load them
    //
    var root = path.join(__dirname, 'chapters', req.params.chapter_name, req.params.directory);
    var data  = files.filter(function (file) {
      return /.json$/.test(file);
    }).map(function (file) {
      var d;
      try { d = require(path.join(root, file)) }
      catch (ex) { d = null }
      return d;
    }).filter(Boolean);

    res.json(200, data);
  }

  fs.readdir('chapters/' + req.params.chapter_name + '/' + req.params.directory, callback);
}

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>// @flow
import { isElement } from './instanceOf';
import type { Window } from '../types';

export default function getDocumentElement(
  element: Element | Window
): HTMLElement {
  // $FlowFixMe: assume body is always available
  return (
    (isElement(element) ? element.ownerDocument : element.document) ||
    window.document
  ).documentElement;
}
<commit_msg>fix: flow errors<commit_after>// @flow
import { isElement } from './instanceOf';
import type { Window } from '../types';

export default function getDocumentElement(
  element: Element | Window
): HTMLElement {
  // $FlowFixMe: assume body is always available
  return ((isElement(element) ? element.ownerDocument : element.document) || window.document)
    .documentElement;
}
<|endoftext|>


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

"use strict";

var DOMProperty = require('DOMProperty');

var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;

var DefaultDOMPropertyConfig = {
  isCustomAttribute: RegExp.prototype.test.bind(
    /^(data|aria)-[a-z_][a-z\d_.\-]*$/
  ),
  Properties: {
    /**
     * Standard Properties
     */
    accessKey: null,
    accept: null,
    action: null,
    ajaxify: MUST_USE_ATTRIBUTE,
    allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    alt: null,
    autoComplete: null,
    autoFocus: HAS_BOOLEAN_VALUE,
    autoPlay: HAS_BOOLEAN_VALUE,
    cellPadding: null,
    cellSpacing: null,
    checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    className: MUST_USE_PROPERTY,
    colSpan: null,
    contentEditable: null,
    contextMenu: MUST_USE_ATTRIBUTE,
    controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    data: null, // For `<object />` acts as `src`.
    dateTime: MUST_USE_ATTRIBUTE,
    dir: null,
    disabled: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    draggable: null,
    encType: null,
    height: MUST_USE_ATTRIBUTE,
    hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    href: null,
    htmlFor: null,
    icon: null,
    id: MUST_USE_PROPERTY,
    label: null,
    lang: null,
    list: null,
    max: null,
    maxLength: MUST_USE_ATTRIBUTE,
    method: null,
    min: null,
    multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    name: null,
    pattern: null,
    poster: null,
    preload: null,
    placeholder: null,
    radioGroup: null,
    rel: null,
    readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    required: HAS_BOOLEAN_VALUE,
    role: MUST_USE_ATTRIBUTE,
    scrollLeft: MUST_USE_PROPERTY,
    scrollTop: MUST_USE_PROPERTY,
    selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    size: null,
    spellCheck: null,
    src: null,
    step: null,
    style: null,
    tabIndex: null,
    target: null,
    title: null,
    type: null,
    value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
    width: MUST_USE_ATTRIBUTE,
    wmode: MUST_USE_ATTRIBUTE,
    /**
     * SVG Properties
     */
    cx: MUST_USE_PROPERTY,
    cy: MUST_USE_PROPERTY,
    d: MUST_USE_PROPERTY,
    fill: MUST_USE_PROPERTY,
    fx: MUST_USE_PROPERTY,
    fy: MUST_USE_PROPERTY,
    points: MUST_USE_PROPERTY,
    r: MUST_USE_PROPERTY,
    stroke: MUST_USE_PROPERTY,
    strokeLinecap: MUST_USE_PROPERTY,
    strokeWidth: MUST_USE_PROPERTY,
    transform: MUST_USE_PROPERTY,
    x: MUST_USE_PROPERTY,
    x1: MUST_USE_PROPERTY,
    x2: MUST_USE_PROPERTY,
    version: MUST_USE_PROPERTY,
    viewBox: MUST_USE_PROPERTY,
    y: MUST_USE_PROPERTY,
    y1: MUST_USE_PROPERTY,
    y2: MUST_USE_PROPERTY,
    spreadMethod: MUST_USE_PROPERTY,
    offset: MUST_USE_PROPERTY,
    stopColor: MUST_USE_PROPERTY,
    stopOpacity: MUST_USE_PROPERTY,
    gradientUnits: MUST_USE_PROPERTY,
    gradientTransform: MUST_USE_PROPERTY
  },
  DOMAttributeNames: {
    className: 'class',
    htmlFor: 'for',
    strokeLinecap: 'stroke-linecap',
    strokeWidth: 'stroke-width',
    stopColor: 'stop-color',
    stopOpacity: 'stop-opacity'
  },
  DOMPropertyNames: {
    autoComplete: 'autocomplete',
    autoFocus: 'autofocus',
    autoPlay: 'autoplay',
    encType: 'enctype',
    radioGroup: 'radiogroup',
    spellCheck: 'spellcheck'
  },
  DOMMutationMethods: {
    /**
     * Setting `className` to null may cause it to be set to the string "null".
     *
     * @param {DOMElement} node
     * @param {*} value
     */
    className: function(node, value) {
      node.className = value || '';
    }
  }
};

module.exports = DefaultDOMPropertyConfig;
<commit_msg>Add iframe attributes to React<commit_after>/**
 * Copyright 2013 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @providesModule DefaultDOMPropertyConfig
 */

"use strict";

var DOMProperty = require('DOMProperty');

var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;

var DefaultDOMPropertyConfig = {
  isCustomAttribute: RegExp.prototype.test.bind(
    /^(data|aria)-[a-z_][a-z\d_.\-]*$/
  ),
  Properties: {
    /**
     * Standard Properties
     */
    accessKey: null,
    accept: null,
    action: null,
    ajaxify: MUST_USE_ATTRIBUTE,
    allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    allowTransparency: MUST_USE_ATTRIBUTE,
    alt: null,
    autoComplete: null,
    autoFocus: HAS_BOOLEAN_VALUE,
    autoPlay: HAS_BOOLEAN_VALUE,
    cellPadding: null,
    cellSpacing: null,
    checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    className: MUST_USE_PROPERTY,
    colSpan: null,
    contentEditable: null,
    contextMenu: MUST_USE_ATTRIBUTE,
    controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    data: null, // For `<object />` acts as `src`.
    dateTime: MUST_USE_ATTRIBUTE,
    dir: null,
    disabled: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    draggable: null,
    encType: null,
    frameBorder: MUST_USE_ATTRIBUTE,
    height: MUST_USE_ATTRIBUTE,
    hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    href: null,
    htmlFor: null,
    icon: null,
    id: MUST_USE_PROPERTY,
    label: null,
    lang: null,
    list: null,
    max: null,
    maxLength: MUST_USE_ATTRIBUTE,
    method: null,
    min: null,
    multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    name: null,
    pattern: null,
    poster: null,
    preload: null,
    placeholder: null,
    radioGroup: null,
    rel: null,
    readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    required: HAS_BOOLEAN_VALUE,
    role: MUST_USE_ATTRIBUTE,
    scrollLeft: MUST_USE_PROPERTY,
    scrollTop: MUST_USE_PROPERTY,
    selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    size: null,
    spellCheck: null,
    src: null,
    step: null,
    style: null,
    tabIndex: null,
    target: null,
    title: null,
    type: null,
    value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
    width: MUST_USE_ATTRIBUTE,
    wmode: MUST_USE_ATTRIBUTE,
    /**
     * SVG Properties
     */
    cx: MUST_USE_PROPERTY,
    cy: MUST_USE_PROPERTY,
    d: MUST_USE_PROPERTY,
    fill: MUST_USE_PROPERTY,
    fx: MUST_USE_PROPERTY,
    fy: MUST_USE_PROPERTY,
    points: MUST_USE_PROPERTY,
    r: MUST_USE_PROPERTY,
    stroke: MUST_USE_PROPERTY,
    strokeLinecap: MUST_USE_PROPERTY,
    strokeWidth: MUST_USE_PROPERTY,
    transform: MUST_USE_PROPERTY,
    x: MUST_USE_PROPERTY,
    x1: MUST_USE_PROPERTY,
    x2: MUST_USE_PROPERTY,
    version: MUST_USE_PROPERTY,
    viewBox: MUST_USE_PROPERTY,
    y: MUST_USE_PROPERTY,
    y1: MUST_USE_PROPERTY,
    y2: MUST_USE_PROPERTY,
    spreadMethod: MUST_USE_PROPERTY,
    offset: MUST_USE_PROPERTY,
    stopColor: MUST_USE_PROPERTY,
    stopOpacity: MUST_USE_PROPERTY,
    gradientUnits: MUST_USE_PROPERTY,
    gradientTransform: MUST_USE_PROPERTY
  },
  DOMAttributeNames: {
    className: 'class',
    htmlFor: 'for',
    strokeLinecap: 'stroke-linecap',
    strokeWidth: 'stroke-width',
    stopColor: 'stop-color',
    stopOpacity: 'stop-opacity'
  },
  DOMPropertyNames: {
    autoComplete: 'autocomplete',
    autoFocus: 'autofocus',
    autoPlay: 'autoplay',
    encType: 'enctype',
    radioGroup: 'radiogroup',
    spellCheck: 'spellcheck'
  },
  DOMMutationMethods: {
    /**
     * Setting `className` to null may cause it to be set to the string "null".
     *
     * @param {DOMElement} node
     * @param {*} value
     */
    className: function(node, value) {
      node.className = value || '';
    }
  }
};

module.exports = DefaultDOMPropertyConfig;
<|endoftext|>


<commit_before>angular.module('fitness.game', [])

// directive for auto-focusing popup input when shown
.directive('focusMe', function($timeout) {
  return {
    link: function(scope, element, attrs) {
      $timeout(function() {
        element[0].focus();
      }, 150);
    }
  };
})
.directive('advanceInputArea', function($timeout, $rootScope) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			$timeout(function() {
				scope.spans = document.getElementById('popup-input-container').getElementsByTagName('span');
				scope.input = document.getElementById('hidden-input');
				scope.input.focus();
				scope.index = 0;
				scope.done = false;
				scope.indexStack = [];
				$rootScope.letters = [];
				findInitialInput();

				element.bind('keydown', function(e) {
					 if(e.key == "Backspace" || e.key == "Delete") {
						e.preventDefault();
						findPrevInput();
					} else if(e.key.match(/^[a-z]$/i)) {
						if(!scope.done) {
							e.preventDefault();
							scope.spans[scope.index].innerHTML = e.key.toUpperCase();
							$rootScope.letters[scope.index] = e.key.toUpperCase();
							findNextInput(scope.index);
						}
					} else {
						console.error("Incorrect key: " + e.key)
						e.preventDefault();
					}
				});
			}, 150);

			$rootScope.clickedPopup = function() {
				scope.input.focus();
			};

			function findInitialInput() {
				for(var i = 0; i < scope.spans.length; i++) {
					if(scope.spans[i].innerHTML == ".") {
						scope.index = i;
						scope.spans[scope.index].className += " char-selected";
						return;
					}
				}
				scope.done = true;
			}

			function findPrevInput() {
				scope.done = false;
				if(scope.indexStack.length > 0) {
					scope.spans[scope.index].classList.remove("char-selected");
					var ind = scope.indexStack.shift();
					scope.spans[ind].innerHTML = ".";
					scope.index = ind;
					scope.spans[scope.index].className += " char-selected";
				} else {
					console.error("beginning reached!")
				}
			}

			function findNextInput(startIndex) {
				scope.indexStack.unshift(startIndex);
				scope.spans[scope.index].classList.remove("char-selected");
				for(var i = startIndex; i < scope.spans.length; i++) {
					if(scope.spans[i].innerHTML == ".") {
						scope.index = i;
						scope.spans[scope.index].className += " char-selected";
						return;
					}
				}
				scope.done = true;
			}
		}
	}
})
.controller('GameCtrl', function($ionicPopup, $ionicModal, $timeout, $interval, $rootScope, gameService, $scope, $state) {

	console.log('Game Controller loaded');

	var self = this;
	var vowels = ['A', 'E', 'I', 'O', 'U'];
	var numVowels;
	var numCons;
	var vowelsRevealed;
	var consRevealed;
	var vowelStack, consStack, thePhrase, noSpace;
	var thePhrase;

	this.init = function(){
		console.log('init game function');
		var obj = {} ;

		self.loadGame();
	};

	this.showPopup = function() {
		$rootScope.copy = _.cloneDeep(self.phrase);
		$scope.data = self.stringifyViewModel(self.phrase);
		console.info(thePhrase)
		var guessPopup = $ionicPopup.show({
			templateUrl: 'pages/game/guess-popup.html',
			title: 'Enter Phrase',
			scope: $scope,
			buttons: [
				{
					text: 'Cancel',
					type: 'button-dark'
				},
				{
					text: 'Solve The Puzzle',
					type: 'button-positive',
					onTap: function(e) {
						var actual = self.translateViewModel($rootScope.copy).toUpperCase().replace(/\s/g, '');
						var expected = thePhrase.toUpperCase().replace(/\s/g, '');
						console.info(actual)
						console.info(expected)
						if(actual && actual === expected) {
							self.goodGuess();
						} else {
							self.badGuess();
						}
					}
				}
			]
		});
	};

	this.stringifyViewModel = function(viewModel) {
		var str = "";
		for(var a = 0; a < viewModel.length; a++) {
			for(var b = 0; b < viewModel[a].length; b++) {
				if(viewModel[a][b].revealed) {
					str += viewModel[a][b].letter;
				} else {
					str += ".";
				}
			}
			str += "  ";
		}
		return str;
	};

	this.translateViewModel = function(viewModel) {
		var str = "";
		for(var a = 0; a < viewModel.length; a++) {
			for(var b = 0; b < viewModel[a].length; b++) {
				if(viewModel[a][b].model == ".") {
					str += $rootScope.letters.shift();
				} else {
					str += viewModel[a][b].letter;
					$rootScope.letters.shift();
				}
			}
			str += "  ";
		}
		return str;
	};

	this.goodGuess = function() {
		console.log("good guess!")
		$ionicPopup.alert({
	     	title: 'You are correct!',
	    	 template: 'Great Job! Play another.'
	   });
		self.revealAll();
		self.closeGame();
		gameService.addScore();

	};

	this.badGuess = function() {
		self.guess = "";
		$ionicPopup.alert({
	     title: 'Wrong Guess!',
	     template: 'Penalty points were added to your goals. Try again!'
	   });

	   gameService.addPenalty();
	};

	this.timeExpired = function(){
		self.guess = "";
			$ionicPopup.alert({
	  		   title: 'Time Expired!',
	  		   template: 'Uh no! You ran out of time. Better luck next time!'
	   });

	   $state.go('app.home');

	}

	this.initModal = function(template) {
		$ionicModal.fromTemplateUrl(template, {
			scope: $scope,
			animation: 'slide-in-up'
		}).then(function(modal) {
			self.modal = modal;
			self.modal.show();
		});
	};

	this.reveal = function(letterType) {
		var curr;
		if(letterType === "V" && vowelStack.length > 1) {
			curr = vowelStack.shift();
			if (curr) {
				curr.model = curr.letter;
				curr.revealed = true;
				vowelsRevealed++;
			}
		} else if(letterType === "C" && consStack.length > 1) {
			curr = consStack.shift();
			if (curr) {
				curr.model = curr.letter;
				curr.revealed = true;
				consRevealed++;
			}
		} else {
			console.error("something went wrong")
			// either we have a bad lettertype or both stacks are empty
		}
	};

	// reveals the entire phrase
	this.revealAll = function() {
		vowelStack.forEach(function(d) {
			d.model = d.letter;
		});

		consStack.forEach(function(d) {
			d.model = d.letter;
		});
	}

	// takes the number of vowels and consonants that should be revealed and reveals them
	this.catchUp = function(vowels, consonants) {
		console.log('catch up to ' + vowels, consonants);
		if(vowels < 0 || consonants < 0) {
			return;
		}

		for(var a = 0; a < vowels; a++) {
			self.reveal("V");
		}

		for(var b = 0; b < consonants; b++) {
			self.reveal("C");
		}

		self.saveGame();
	};

	this.saveGame = function() {
		console.info("game saved!")

		if (!gameService.activeGame)
			return null ;

		var state = {
			numVowels: numVowels,
			numCons: numCons,
			vowelsRevealed: vowelsRevealed,
			consRevealed: consRevealed,
			vowelStack: vowelStack,
			consStack: consStack,
			viewModel: self.phrase,
			thePhrase: thePhrase,
			noSpace: noSpace,
			hint: self.hint
		};

		return localforage.setItem("gameState", JSON.stringify(state));
	};

	this.loadGame = function() {
		console.info("game loaded!")
		localforage.getItem("gameState").then(function(savedState) {

			if (savedState){

				savedState = JSON.parse(savedState);

				numVowels = savedState.numVowels;
				numCons = savedState.numCons;
				vowelsRevealed = savedState.vowelsRevealed;
				consRevealed = savedState.consRevealed;
				vowelStack = savedState.vowelStack;
				consStack = savedState.consStack;
				self.phrase = savedState.viewModel;
				thePhrase = savedState.thePhrase;
				noSpace = savedState.noSpace;
				self.hint = savedState.hint;
			}
			else{
				obj = gameService.startGame();
				self.guess = "" ;

				gameService.activeGame = obj ;
				gameService.activeGameFlag = true ;

				numVowels = obj.numVowels;
				numCons = obj.numCons;
				vowelsRevealed = 0;
				consRevealed = 0;
				vowelStack = obj.vowelStack;
				consStack = obj.consStack;
				self.phrase = obj.viewModel;
				thePhrase = obj.phrase;
				noSpace = obj.noSpace;
				self.hint = obj.hint;

				self.saveGame();

			}
			gameService.activeGame = true;
		});
	};

	this.testReveal = function() {
		if(vowelStack.length > 0) {
			self.reveal("V");
		} else {
			self.reveal("C");
		}
	}

	this.drawFriendly = function() {

		console.log('goal steps ' + self.fitbitData.goals.steps);

		jQuery("#friend-progress").empty();

			self.friendlyProgress = jQuery("#friend-progress").radialMultiProgress("init", {
				'fill': 25,
				'font-size': 14,
				'size': 100,
				'data': [
					{'color': "#2DB1E4", 'range': [0, gameService.data.goalSteps]}, // steps
					{'color': "#9CCA13", 'range': [0, gameService.data.goalFloors]}, // floors
					{'color': "#cf2583", 'range': [0, 24]} // time
				]
			});

		var dh, dm, ds;
	//	setInterval(function() {
			console.log('in the draw circle func.');

			var date = new Date(),
	        h = date.getHours(),
	        m = date.getMinutes(),
	        s = date.getSeconds();

			self.fitbitData.time = gameService.updateTime(h);

			console.log('hours is ' + h);

	    	self.friendlyProgress.radialMultiProgress("to", {
	      		"index": 0, 'perc': self.fitbitData.steps, 'time': 10
	      	});
	    	self.friendlyProgress.radialMultiProgress("to", {
	    		"index": 1, 'perc': self.fitbitData.floors, 'time': 10
	    	});
	    	self.friendlyProgress.radialMultiProgress("to", {
	    		"index": 2, 'perc': h, 'time': 10
	    	});
	  //  }
//	  }, 1000);
	};

	$scope.$on('$ionicView.leave', function(e) {
		self.saveGame();
	});

	$scope.$on('$ionicView.enter', function(e) {

		self.fitbitData = {} ;
		self.fitbitData.goals = {} ;

		self.fitbitData = gameService.data ;

		console.log('steps in game.js: ' + self.fitbitData.steps);

		console.log('getting access token from storage');
		localforage.getItem('fitbitToken').then(function(token){
			if (!token)
				gameService.reload();

			gameService.fitbitToken = token;
			console.log('saving token to game service: ' + token);
			gameService.getFitbitData();
			$timeout( self.computeGameLogic, 4000);

		});

		self.init();

		$interval.cancel(self.queryInterval);

		self.queryInterval = $interval( function(){ self.refreshData(); } , 260000);

		$timeout( self.drawFriendly, 1000);

	});

	this.refreshData = function(){

		gameService.getFitbitData();
		$timeout( self.computeGameLogic, 2000);
		$timeout( self.drawFriendly, 750);
		$scope.$broadcast('scroll.refreshComplete');
	}

	this.computeGameLogic = function(){
		var vowelWorth = parseInt( self.fitbitData.goalFloors /  numVowels);
		var consWorth = parseInt(self.fitbitData.goalSteps /  numCons) ;

		if (consWorth < 200) // min steps required
			consWorth = 200 ;

		if (vowelWorth < 1) // min floors required
			vowelWorth = 1 ;

		var vowelCount = parseInt(self.fitbitData.floors / vowelWorth ) - vowelsRevealed;
		var consCount = parseInt(self.fitbitData.steps / consWorth ) - consRevealed;

		if (vowelCount < 0)
			vowelCount = 0;
		if (consCount < 0)
			consCount = 0 ;

		self.catchUp( vowelCount, consCount );
	}

	this.openGiveUpAlert = function() {
		$ionicPopup.confirm({
	     title: 'Aww You\'re Ready To Give Up Already?',
	     template: 'Are you sure you want to give up on this puzzle? All progress will be lost.',
		 okText: 'Give Up'
	   }).then(function(res) {
	   	if(res) {
	   		self.closeGame();
	   	} else {
	   		// do nothing
	   	}
	   });
	};

	this.closeGame = function(){
		// needs a prompt

		localforage.removeItem("gameState");

		gameService.activeGame = false;
		gameService.clearGame();
		$state.transitionTo('app.home');
	}
});
<commit_msg>working great<commit_after>angular.module('fitness.game', [])

// directive for auto-focusing popup input when shown
.directive('focusMe', function($timeout) {
  return {
    link: function(scope, element, attrs) {
      $timeout(function() {
        element[0].focus();
      }, 150);
    }
  };
})
.directive('advanceInputArea', function($timeout, $rootScope) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			$timeout(function() {
				scope.spans = document.getElementById('popup-input-container').getElementsByTagName('span');
				scope.input = document.getElementById('hidden-input');
				scope.input.focus();
				scope.index = 0;
				scope.done = false;
				scope.indexStack = [];
				$rootScope.letters = [];
				findInitialInput();

				element.bind('keyup', function(e) {
					 if(e.key == "Backspace" || e.key == "Delete") {
						e.preventDefault();
						findPrevInput();
					} else if(e.key.match(/^[a-z]$/i)) {
						if(!scope.done) {
							e.preventDefault();
							scope.spans[scope.index].innerHTML = e.key.toUpperCase();
							$rootScope.letters[scope.index] = e.key.toUpperCase();
							findNextInput(scope.index);
						}
					} else {
						console.error("Incorrect key: " + e.key)
						e.preventDefault();
					}
				});
			}, 150);

			$rootScope.clickedPopup = function() {
				scope.input.focus();
			};

			function findInitialInput() {
				for(var i = 0; i < scope.spans.length; i++) {
					if(scope.spans[i].innerHTML == ".") {
						scope.index = i;
						scope.spans[scope.index].className += " char-selected";
						return;
					}
				}
				scope.done = true;
			}

			function findPrevInput() {
				scope.done = false;
				if(scope.indexStack.length > 0) {
					scope.spans[scope.index].classList.remove("char-selected");
					var ind = scope.indexStack.shift();
					scope.spans[ind].innerHTML = ".";
					scope.index = ind;
					scope.spans[scope.index].className += " char-selected";
				} else {
					console.error("beginning reached!")
				}
			}

			function findNextInput(startIndex) {
				scope.indexStack.unshift(startIndex);
				scope.spans[scope.index].classList.remove("char-selected");
				for(var i = startIndex; i < scope.spans.length; i++) {
					if(scope.spans[i].innerHTML == ".") {
						scope.index = i;
						scope.spans[scope.index].className += " char-selected";
						return;
					}
				}
				scope.done = true;
			}
		}
	}
})
.controller('GameCtrl', function($ionicPopup, $ionicModal, $timeout, $interval, $rootScope, gameService, $scope, $state) {

	console.log('Game Controller loaded');

	var self = this;
	var vowels = ['A', 'E', 'I', 'O', 'U'];
	var numVowels;
	var numCons;
	var vowelsRevealed;
	var consRevealed;
	var vowelStack, consStack, thePhrase, noSpace;
	var thePhrase;

	this.init = function(){
		console.log('init game function');
		var obj = {} ;

		self.loadGame();
	};

	this.showPopup = function() {
		$rootScope.copy = _.cloneDeep(self.phrase);
		$scope.data = self.stringifyViewModel(self.phrase);
		console.info(thePhrase)
		var guessPopup = $ionicPopup.show({
			templateUrl: 'pages/game/guess-popup.html',
			title: 'Enter Phrase',
			scope: $scope,
			buttons: [
				{
					text: 'Cancel',
					type: 'button-dark'
				},
				{
					text: 'Solve The Puzzle',
					type: 'button-positive',
					onTap: function(e) {
						var actual = self.translateViewModel($rootScope.copy).toUpperCase().replace(/\s/g, '');
						var expected = thePhrase.toUpperCase().replace(/\s/g, '');
						console.info(actual)
						console.info(expected)
						if(actual && actual === expected) {
							self.goodGuess();
						} else {
							self.badGuess();
						}
					}
				}
			]
		});
	};

	this.stringifyViewModel = function(viewModel) {
		var str = "";
		for(var a = 0; a < viewModel.length; a++) {
			for(var b = 0; b < viewModel[a].length; b++) {
				if(viewModel[a][b].revealed) {
					str += viewModel[a][b].letter;
				} else {
					str += ".";
				}
			}
			str += "  ";
		}
		return str;
	};

	this.translateViewModel = function(viewModel) {
		var str = "";
		for(var a = 0; a < viewModel.length; a++) {
			for(var b = 0; b < viewModel[a].length; b++) {
				if(viewModel[a][b].model == ".") {
					str += $rootScope.letters.shift();
				} else {
					str += viewModel[a][b].letter;
					$rootScope.letters.shift();
				}
			}
			str += "  ";
		}
		return str;
	};

	this.goodGuess = function() {
		console.log("good guess!")
		$ionicPopup.alert({
	     	title: 'You are correct!',
	    	 template: 'Great Job! Play another.'
	   });
		self.revealAll();
		self.closeGame();
		gameService.addScore();

	};

	this.badGuess = function() {
		self.guess = "";
		$ionicPopup.alert({
	     title: 'Wrong Guess!',
	     template: 'Penalty points were added to your goals. Try again!'
	   });

	   gameService.addPenalty();
	};

	this.timeExpired = function(){
		self.guess = "";
			$ionicPopup.alert({
	  		   title: 'Time Expired!',
	  		   template: 'Uh no! You ran out of time. Better luck next time!'
	   });

	   $state.go('app.home');

	}

	this.initModal = function(template) {
		$ionicModal.fromTemplateUrl(template, {
			scope: $scope,
			animation: 'slide-in-up'
		}).then(function(modal) {
			self.modal = modal;
			self.modal.show();
		});
	};

	this.reveal = function(letterType) {
		var curr;
		if(letterType === "V" && vowelStack.length > 1) {
			curr = vowelStack.shift();
			if (curr) {
				curr.model = curr.letter;
				curr.revealed = true;
				vowelsRevealed++;
			}
		} else if(letterType === "C" && consStack.length > 1) {
			curr = consStack.shift();
			if (curr) {
				curr.model = curr.letter;
				curr.revealed = true;
				consRevealed++;
			}
		} else {
			console.error("something went wrong")
			// either we have a bad lettertype or both stacks are empty
		}
	};

	// reveals the entire phrase
	this.revealAll = function() {
		vowelStack.forEach(function(d) {
			d.model = d.letter;
		});

		consStack.forEach(function(d) {
			d.model = d.letter;
		});
	}

	// takes the number of vowels and consonants that should be revealed and reveals them
	this.catchUp = function(vowels, consonants) {
		console.log('catch up to ' + vowels, consonants);
		if(vowels < 0 || consonants < 0) {
			return;
		}

		for(var a = 0; a < vowels; a++) {
			self.reveal("V");
		}

		for(var b = 0; b < consonants; b++) {
			self.reveal("C");
		}

		self.saveGame();
	};

	this.saveGame = function() {
		console.info("game saved!")

		if (!gameService.activeGame)
			return null ;

		var state = {
			numVowels: numVowels,
			numCons: numCons,
			vowelsRevealed: vowelsRevealed,
			consRevealed: consRevealed,
			vowelStack: vowelStack,
			consStack: consStack,
			viewModel: self.phrase,
			thePhrase: thePhrase,
			noSpace: noSpace,
			hint: self.hint
		};

		return localforage.setItem("gameState", JSON.stringify(state));
	};

	this.loadGame = function() {
		console.info("game loaded!")
		localforage.getItem("gameState").then(function(savedState) {

			if (savedState){

				savedState = JSON.parse(savedState);

				numVowels = savedState.numVowels;
				numCons = savedState.numCons;
				vowelsRevealed = savedState.vowelsRevealed;
				consRevealed = savedState.consRevealed;
				vowelStack = savedState.vowelStack;
				consStack = savedState.consStack;
				self.phrase = savedState.viewModel;
				thePhrase = savedState.thePhrase;
				noSpace = savedState.noSpace;
				self.hint = savedState.hint;
			}
			else{
				obj = gameService.startGame();
				self.guess = "" ;

				gameService.activeGame = obj ;
				gameService.activeGameFlag = true ;

				numVowels = obj.numVowels;
				numCons = obj.numCons;
				vowelsRevealed = 0;
				consRevealed = 0;
				vowelStack = obj.vowelStack;
				consStack = obj.consStack;
				self.phrase = obj.viewModel;
				thePhrase = obj.phrase;
				noSpace = obj.noSpace;
				self.hint = obj.hint;

				self.saveGame();

			}
			gameService.activeGame = true;
		});
	};

	this.testReveal = function() {
		if(vowelStack.length > 0) {
			self.reveal("V");
		} else {
			self.reveal("C");
		}
	}

	this.drawFriendly = function() {

		console.log('goal steps ' + self.fitbitData.goals.steps);

		jQuery("#friend-progress").empty();

			self.friendlyProgress = jQuery("#friend-progress").radialMultiProgress("init", {
				'fill': 25,
				'font-size': 14,
				'size': 100,
				'data': [
					{'color': "#2DB1E4", 'range': [0, gameService.data.goalSteps]}, // steps
					{'color': "#9CCA13", 'range': [0, gameService.data.goalFloors]}, // floors
					{'color': "#cf2583", 'range': [0, 24]} // time
				]
			});

		var dh, dm, ds;
	//	setInterval(function() {
			console.log('in the draw circle func.');

			var date = new Date(),
	        h = date.getHours(),
	        m = date.getMinutes(),
	        s = date.getSeconds();

			self.fitbitData.time = gameService.updateTime(h);

			console.log('hours is ' + h);

	    	self.friendlyProgress.radialMultiProgress("to", {
	      		"index": 0, 'perc': self.fitbitData.steps, 'time': 10
	      	});
	    	self.friendlyProgress.radialMultiProgress("to", {
	    		"index": 1, 'perc': self.fitbitData.floors, 'time': 10
	    	});
	    	self.friendlyProgress.radialMultiProgress("to", {
	    		"index": 2, 'perc': h, 'time': 10
	    	});
	  //  }
//	  }, 1000);
	};

	$scope.$on('$ionicView.leave', function(e) {
		self.saveGame();
	});

	$scope.$on('$ionicView.enter', function(e) {

		self.fitbitData = {} ;
		self.fitbitData.goals = {} ;

		self.fitbitData = gameService.data ;

		console.log('steps in game.js: ' + self.fitbitData.steps);

		console.log('getting access token from storage');
		localforage.getItem('fitbitToken').then(function(token){
			if (!token)
				gameService.reload();

			gameService.fitbitToken = token;
			console.log('saving token to game service: ' + token);
			gameService.getFitbitData();
			$timeout( self.computeGameLogic, 4000);

		});

		self.init();

		$interval.cancel(self.queryInterval);

		self.queryInterval = $interval( function(){ self.refreshData(); } , 260000);

		$timeout( self.drawFriendly, 1000);

	});

	this.refreshData = function(){

		gameService.getFitbitData();
		$timeout( self.computeGameLogic, 2000);
		$timeout( self.drawFriendly, 750);
		$scope.$broadcast('scroll.refreshComplete');
	}

	this.computeGameLogic = function(){
		var vowelWorth = parseInt( self.fitbitData.goalFloors /  numVowels);
		var consWorth = parseInt(self.fitbitData.goalSteps /  numCons) ;

		if (consWorth < 200) // min steps required
			consWorth = 200 ;

		if (vowelWorth < 1) // min floors required
			vowelWorth = 1 ;

		var vowelCount = parseInt(self.fitbitData.floors / vowelWorth ) - vowelsRevealed;
		var consCount = parseInt(self.fitbitData.steps / consWorth ) - consRevealed;

		if (vowelCount < 0)
			vowelCount = 0;
		if (consCount < 0)
			consCount = 0 ;

		self.catchUp( vowelCount, consCount );
	}

	this.openGiveUpAlert = function() {
		$ionicPopup.confirm({
	     title: 'Aww You\'re Ready To Give Up Already?',
	     template: 'Are you sure you want to give up on this puzzle? All progress will be lost.',
		 okText: 'Give Up'
	   }).then(function(res) {
	   	if(res) {
	   		self.closeGame();
	   	} else {
	   		// do nothing
	   	}
	   });
	};

	this.closeGame = function(){
		// needs a prompt

		localforage.removeItem("gameState");

		gameService.activeGame = false;
		gameService.clearGame();
		$state.transitionTo('app.home');
	}
});
<|endoftext|>


<commit_before>import './top-nav.scss';

var Template = require('./top-nav.html');
var Interface = require('interface.json');
var Core = require('_core.js');

var Profile = require('./profile/profile.js');
var Shortcut = require('./shortcut/shortcut.js');
var Help = require('./help/help.js');
var ProjectAccountSwitcher = require('./project-account-switcher/project-account-switcher.js');
var Search = require('./search/search.js');

/**
 * Creates an TopNav
 *
 * @class
 */

class TopNav extends Core {

    constructor(options){
        super(options);
        this._render(Template, options);
    }

    onHamburgerClick(fn){
        return this._attachListener("click", '.hig__global-nav__top-nav__hamburger', this.el, fn);
    }

    setLogo(logo){
        this._setLogoAttributeForTag("img","src",logo);
    }

    setLogoLink(link){
        this._setLogoAttributeForTag("a","href",link);
    }

    addProfile(profileInstance){
        if (profileInstance instanceof Profile){
            this.mountPartialToComment('PROFILE', profileInstance);
        }
    }

    addProjectAccountSwitcher(instance){
        if (instance instanceof ProjectAccountSwitcher){
            this.mountPartialToComment('PROJECT_ACCOUNT_SWITCHER', instance);
        }
    }

    addSearch(searchInstance, referenceInstance){
        if(searchInstance instanceof Search){
            this.mountPartialToComment('SEARCH', searchInstance, referenceInstance);
        }
    }

    addShortcut(instance, referenceInstance){
        if(instance instanceof Shortcut){
            this.mountPartialToComment('SEARCH', instance, referenceInstance);
        }
    }

    addHelp(instance, referenceInstance){
        if(instance instanceof Search){
            this.mountPartialToComment('SEARCH', instance, referenceInstance);
        }
    }

    sidenavOpen() {
        this._findDOMEl(".hig__global-nav__top-nav__hamburger", this.el).classList.add("hig__global-nav__top-nav__hamburger--menuopen");
    }

    sidenavClosed() {
        this._findDOMEl(".hig__global-nav__top-nav__hamburger", this.el).classList.remove("hig__global-nav__top-nav__hamburger--menuopen");
    }

    _setLogoAttributeForTag(tag,attr,val) {
        const scope = this._findDOMEl('.hig__global-nav__top-nav__logo', this.el);
        this._findDOMEl(tag, scope).setAttribute(attr, val);
    }
}

TopNav._interface = Interface['components']['GlobalNav']['partials']['TopNav'];
TopNav._defaults = {
    logo: "link",
    logoLink: "#"
};

TopNav._partials = {
    Profile: Profile,
    ProjectAccountSwitcher: ProjectAccountSwitcher,
    Shortcut: Shortcut,
    Help: Help,
    Search: Search
};

module.exports = TopNav;<commit_msg>fix copy paste error<commit_after>import './top-nav.scss';

var Template = require('./top-nav.html');
var Interface = require('interface.json');
var Core = require('_core.js');

var Profile = require('./profile/profile.js');
var Shortcut = require('./shortcut/shortcut.js');
var Help = require('./help/help.js');
var ProjectAccountSwitcher = require('./project-account-switcher/project-account-switcher.js');
var Search = require('./search/search.js');

/**
 * Creates an TopNav
 *
 * @class
 */

class TopNav extends Core {

    constructor(options){
        super(options);
        this._render(Template, options);
    }

    onHamburgerClick(fn){
        return this._attachListener("click", '.hig__global-nav__top-nav__hamburger', this.el, fn);
    }

    setLogo(logo){
        this._setLogoAttributeForTag("img","src",logo);
    }

    setLogoLink(link){
        this._setLogoAttributeForTag("a","href",link);
    }

    addProfile(profileInstance){
        if (profileInstance instanceof Profile){
            this.mountPartialToComment('PROFILE', profileInstance);
        }
    }

    addProjectAccountSwitcher(instance){
        if (instance instanceof ProjectAccountSwitcher){
            this.mountPartialToComment('PROJECT_ACCOUNT_SWITCHER', instance);
        }
    }

    addSearch(searchInstance, referenceInstance){
        if(searchInstance instanceof Search){
            this.mountPartialToComment('SEARCH', searchInstance, referenceInstance);
        }
    }

    addShortcut(instance, referenceInstance){
        if(instance instanceof Shortcut){
            this.mountPartialToComment('SHORTCUT', instance, referenceInstance);
        }
    }

    addHelp(instance, referenceInstance){
        if(instance instanceof Search){
            this.mountPartialToComment('SHORTCUT', instance, referenceInstance);
        }
    }

    sidenavOpen() {
        this._findDOMEl(".hig__global-nav__top-nav__hamburger", this.el).classList.add("hig__global-nav__top-nav__hamburger--menuopen");
    }

    sidenavClosed() {
        this._findDOMEl(".hig__global-nav__top-nav__hamburger", this.el).classList.remove("hig__global-nav__top-nav__hamburger--menuopen");
    }

    _setLogoAttributeForTag(tag,attr,val) {
        const scope = this._findDOMEl('.hig__global-nav__top-nav__logo', this.el);
        this._findDOMEl(tag, scope).setAttribute(attr, val);
    }
}

TopNav._interface = Interface['components']['GlobalNav']['partials']['TopNav'];
TopNav._defaults = {
    logo: "link",
    logoLink: "#"
};

TopNav._partials = {
    Profile: Profile,
    ProjectAccountSwitcher: ProjectAccountSwitcher,
    Shortcut: Shortcut,
    Help: Help,
    Search: Search
};

module.exports = TopNav;<|endoftext|>


<commit_before>// ==UserScript==
// @name         KANJAX on all Websites v2
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    var scriptElementBpop = document.createElement( "script" );
    scriptElementBpop.type = "text/javascript";
    scriptElementBpop.src = "http://127.0.0.1:8887/_jquery.bpopup.min.js";
    document.body.appendChild( scriptElementBpop );

    var scriptElement = document.createElement( "script" );
    scriptElement.type = "text/javascript";
    scriptElement.src = "http://127.0.0.1:8887/_kanjax_with_koohii.js";
    document.body.appendChild( scriptElement );
})();<commit_msg>Update ALL_KANJAX.js<commit_after>// ==UserScript==
// @name         KANJAX on all Websites v2
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Adds scripts to find Kanji on website page and makes them interactive with Kanji Koohi data + kanji strokes.
// @author       You
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    var scriptElementBpop = document.createElement( "script" );
    scriptElementBpop.type = "text/javascript";
    scriptElementBpop.src = "http://127.0.0.1:8887/_jquery.bpopup.min.js";
    document.body.appendChild( scriptElementBpop );

    var scriptElement = document.createElement( "script" );
    scriptElement.type = "text/javascript";
    scriptElement.src = "http://127.0.0.1:8887/_kanjax_with_koohii.js";
    document.body.appendChild( scriptElement );
})();
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace random
*/
var random = {};

/**
* @name beta
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/beta}
*/
setReadOnly( random, 'beta', require( '@stdlib/math/base/random/beta' ) );

/**
* @name binomial
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/binomial}
*/
setReadOnly( random, 'binomial', require( '@stdlib/math/base/random/binomial' ) );

/**
* @name boxMuller
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/box-muller}
*/
setReadOnly( random, 'boxMuller', require( '@stdlib/math/base/random/box-muller' ) );

/**
* @name cauchy
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/cauchy}
*/
setReadOnly( random, 'cauchy', require( '@stdlib/math/base/random/cauchy' ) );

/**
* @name chisquare
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/chisquare}
*/
setReadOnly( random, 'chisquare', require( '@stdlib/math/base/random/chisquare' ) );

/**
* @name erlang
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/erlang}
*/
setReadOnly( random, 'erlang', require( '@stdlib/math/base/random/erlang' ) );

/**
* @name exponential
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/exponential}
*/
setReadOnly( random, 'exponential', require( '@stdlib/math/base/random/exponential' ) );

/**
* @name f
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/f}
*/
setReadOnly( random, 'f', require( '@stdlib/math/base/random/f' ) );

/**
* @name gamma
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/gamma}
*/
setReadOnly( random, 'gamma', require( '@stdlib/math/base/random/gamma' ) );

/**
* @name geometric
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/geometric}
*/
setReadOnly( random, 'geometric', require( '@stdlib/math/base/random/geometric' ) );

/**
* @name gumbel
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/gumbel}
*/
setReadOnly( random, 'gumbel', require( '@stdlib/math/base/random/gumbel' ) );

/**
* @name hypergeometric
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/hypergeometric}
*/

setReadOnly( random, 'hypergeometric', require( '@stdlib/math/base/random/hypergeometric' ) );

/**
* @name improvedZiggurat
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/improved-ziggurat}
*/
setReadOnly( random, 'improvedZiggurat', require( '@stdlib/math/base/random/improved-ziggurat' ) );

/**
* @name invgamma
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/invgamma}
*/
setReadOnly( random, 'invgamma', require( '@stdlib/math/base/random/invgamma' ) );

/**
* @name laplace
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/laplace}
*/
setReadOnly( random, 'laplace', require( '@stdlib/math/base/random/laplace' ) );

/**
* @name logistic
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/logistic}
*/
setReadOnly( random, 'logistic', require( '@stdlib/math/base/random/logistic' ) );

/**
* @name lognormal
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/lognormal}
*/
setReadOnly( random, 'lognormal', require( '@stdlib/math/base/random/lognormal' ) );

/**
* @name minstd
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/minstd}
*/
setReadOnly( random, 'minstd', require( '@stdlib/math/base/random/minstd' ) );

/**
* @name minstdShuffle
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/minstd-shuffle}
*/
setReadOnly( random, 'minstdShuffle', require( '@stdlib/math/base/random/minstd-shuffle' ) );

/**
* @name negativeBinomial
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/negative-binomial}
*/
setReadOnly( random, 'negativeBinomial', require( '@stdlib/math/base/random/negative-binomial' ) );

/**
* @name normal
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/normal}
*/
setReadOnly( random, 'normal', require( '@stdlib/math/base/random/normal' ) );

/**
* @name pareto1
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/pareto-type1}
*/
setReadOnly( random, 'pareto1', require( '@stdlib/math/base/random/pareto-type1' ) );

/**
* @name poisson
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/poisson}
*/
setReadOnly( random, 'poisson', require( '@stdlib/math/base/random/poisson' ) );

/**
* @name randn
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/randn}
*/
setReadOnly( random, 'randn', require( '@stdlib/math/base/random/randn' ) );

/**
* @name randu
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/randu}
*/
setReadOnly( random, 'randu', require( '@stdlib/math/base/random/randu' ) );

/**
* @name rayleigh
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/rayleigh}
*/
setReadOnly( random, 'rayleigh', require( '@stdlib/math/base/random/rayleigh' ) );

/**
* @name t
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/t}
*/
setReadOnly( random, 't', require( '@stdlib/math/base/random/t' ) );

/**
* @name triangular
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/triangular}
*/
setReadOnly( random, 'triangular', require( '@stdlib/math/base/random/triangular' ) );

/**
* @name uniform
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/uniform}
*/
setReadOnly( random, 'uniform', require( '@stdlib/math/base/random/uniform' ) );

/**
* @name weibull
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/weibull}
*/
setReadOnly( random, 'weibull', require( '@stdlib/math/base/random/weibull' ) );

// EXPORTS //

module.exports = random;
<commit_msg>Add arcsine to random namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace random
*/
var random = {};

/**
* @name arcsine
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/arcsine}
*/
setReadOnly( random, 'arcsine', require( '@stdlib/math/base/random/arcsine' ) );

/**
* @name beta
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/beta}
*/
setReadOnly( random, 'beta', require( '@stdlib/math/base/random/beta' ) );

/**
* @name binomial
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/binomial}
*/
setReadOnly( random, 'binomial', require( '@stdlib/math/base/random/binomial' ) );

/**
* @name boxMuller
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/box-muller}
*/
setReadOnly( random, 'boxMuller', require( '@stdlib/math/base/random/box-muller' ) );

/**
* @name cauchy
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/cauchy}
*/
setReadOnly( random, 'cauchy', require( '@stdlib/math/base/random/cauchy' ) );

/**
* @name chisquare
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/chisquare}
*/
setReadOnly( random, 'chisquare', require( '@stdlib/math/base/random/chisquare' ) );

/**
* @name erlang
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/erlang}
*/
setReadOnly( random, 'erlang', require( '@stdlib/math/base/random/erlang' ) );

/**
* @name exponential
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/exponential}
*/
setReadOnly( random, 'exponential', require( '@stdlib/math/base/random/exponential' ) );

/**
* @name f
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/f}
*/
setReadOnly( random, 'f', require( '@stdlib/math/base/random/f' ) );

/**
* @name gamma
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/gamma}
*/
setReadOnly( random, 'gamma', require( '@stdlib/math/base/random/gamma' ) );

/**
* @name geometric
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/geometric}
*/
setReadOnly( random, 'geometric', require( '@stdlib/math/base/random/geometric' ) );

/**
* @name gumbel
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/gumbel}
*/
setReadOnly( random, 'gumbel', require( '@stdlib/math/base/random/gumbel' ) );

/**
* @name hypergeometric
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/hypergeometric}
*/

setReadOnly( random, 'hypergeometric', require( '@stdlib/math/base/random/hypergeometric' ) );

/**
* @name improvedZiggurat
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/improved-ziggurat}
*/
setReadOnly( random, 'improvedZiggurat', require( '@stdlib/math/base/random/improved-ziggurat' ) );

/**
* @name invgamma
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/invgamma}
*/
setReadOnly( random, 'invgamma', require( '@stdlib/math/base/random/invgamma' ) );

/**
* @name laplace
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/laplace}
*/
setReadOnly( random, 'laplace', require( '@stdlib/math/base/random/laplace' ) );

/**
* @name logistic
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/logistic}
*/
setReadOnly( random, 'logistic', require( '@stdlib/math/base/random/logistic' ) );

/**
* @name lognormal
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/lognormal}
*/
setReadOnly( random, 'lognormal', require( '@stdlib/math/base/random/lognormal' ) );

/**
* @name minstd
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/minstd}
*/
setReadOnly( random, 'minstd', require( '@stdlib/math/base/random/minstd' ) );

/**
* @name minstdShuffle
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/minstd-shuffle}
*/
setReadOnly( random, 'minstdShuffle', require( '@stdlib/math/base/random/minstd-shuffle' ) );

/**
* @name negativeBinomial
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/negative-binomial}
*/
setReadOnly( random, 'negativeBinomial', require( '@stdlib/math/base/random/negative-binomial' ) );

/**
* @name normal
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/normal}
*/
setReadOnly( random, 'normal', require( '@stdlib/math/base/random/normal' ) );

/**
* @name pareto1
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/pareto-type1}
*/
setReadOnly( random, 'pareto1', require( '@stdlib/math/base/random/pareto-type1' ) );

/**
* @name poisson
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/poisson}
*/
setReadOnly( random, 'poisson', require( '@stdlib/math/base/random/poisson' ) );

/**
* @name randn
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/randn}
*/
setReadOnly( random, 'randn', require( '@stdlib/math/base/random/randn' ) );

/**
* @name randu
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/randu}
*/
setReadOnly( random, 'randu', require( '@stdlib/math/base/random/randu' ) );

/**
* @name rayleigh
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/rayleigh}
*/
setReadOnly( random, 'rayleigh', require( '@stdlib/math/base/random/rayleigh' ) );

/**
* @name t
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/t}
*/
setReadOnly( random, 't', require( '@stdlib/math/base/random/t' ) );

/**
* @name triangular
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/triangular}
*/
setReadOnly( random, 'triangular', require( '@stdlib/math/base/random/triangular' ) );

/**
* @name uniform
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/uniform}
*/
setReadOnly( random, 'uniform', require( '@stdlib/math/base/random/uniform' ) );

/**
* @name weibull
* @memberof random
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/random/weibull}
*/
setReadOnly( random, 'weibull', require( '@stdlib/math/base/random/weibull' ) );

// EXPORTS //

module.exports = random;
<|endoftext|>