<commit_before>'use strict';
var bitcore = require('bitcore');

angular.module('copayApp.controllers').controller('TransactionsController',
  function($scope, $rootScope, $timeout, controllerUtils) {

    $scope.title = 'Transactions';
    $scope.loading = false;
    $scope.onlyPending = true;
    $scope.lastShowed = false;

    $scope.txpCurrentPage = 1;
    $scope.txpItemsPerPage = 4;
    $scope.blockchain_txs = [];

    var satToUnit = 1 / config.unitToSatoshi;

    $scope.update = function() {
      $scope.loading = false;
      var from = ($scope.txpCurrentPage - 1) * $scope.txpItemsPerPage;
      var opts = {
        onlyPending: $scope.onlyPending,
        skip: !$scope.onlyPending ? [from, from + $scope.txpItemsPerPage] : null
      };
      controllerUtils.updateTxs(opts);
      $rootScope.$digest();
    };

    $scope.show = function(onlyPending) {
      $scope.loading = true;
      $scope.onlyPending = onlyPending;
      setTimeout(function() {
        $scope.update();
      }, 10);
    };

    var _aggregateItems = function(items) {
      if (!items) return [];

      var l = items.length;

      var ret = [];
      var tmp = {};
      var u = 0;

      for (var i = 0; i < l; i++) {

        var notAddr = false;
        // non standard input
        if (items[i].scriptSig && !items[i].addr) {
          items[i].addr = 'Unparsed address [' + u+++']';
          items[i].notAddr = true;
          notAddr = true;
        }

        // non standard output
        if (items[i].scriptPubKey && !items[i].scriptPubKey.addresses) {
          items[i].scriptPubKey.addresses = ['Unparsed address [' + u+++']'];
          items[i].notAddr = true;
          notAddr = true;
        }

        // multiple addr at output
        if (items[i].scriptPubKey && items[i].scriptPubKey.addresses.length > 1) {
          items[i].addr = items[i].scriptPubKey.addresses.join(',');
          ret.push(items[i]);
          continue;
        }

        var addr = items[i].addr || (items[i].scriptPubKey && items[i].scriptPubKey.addresses[0]);

        if (!tmp[addr]) {
          tmp[addr] = {};
          tmp[addr].valueSat = 0;
          tmp[addr].count = 0;
          tmp[addr].addr = addr;
          tmp[addr].items = [];
        }
        tmp[addr].isSpent = items[i].spentTxId;

        tmp[addr].doubleSpentTxID = tmp[addr].doubleSpentTxID || items[i].doubleSpentTxID;
        tmp[addr].doubleSpentIndex = tmp[addr].doubleSpentIndex || items[i].doubleSpentIndex;
        tmp[addr].unconfirmedInput += items[i].unconfirmedInput;
        tmp[addr].dbError = tmp[addr].dbError || items[i].dbError;
        tmp[addr].valueSat += parseInt((items[i].value * bitcore.util.COIN).toFixed(0));
        tmp[addr].items.push(items[i]);
        tmp[addr].notAddr = notAddr;
        tmp[addr].count++;
      }

      angular.forEach(tmp, function(v) {
        v.value = (parseInt(v.valueSat || 0).toFixed(0)) * satToUnit;
        ret.push(v);
      });
      return ret;
    };

    $scope.toogleLast = function() {
      $scope.lastShowed = !$scope.lastShowed;
      if ($scope.lastShowed) {
        $scope.getTransactions();
      }
    };

    $scope.send = function(ntxid, cb) {
      $scope.loading = true;
      $rootScope.txAlertCount = 0;
      var w = $rootScope.wallet;
      w.sendTx(ntxid, function(txid) {
        $rootScope.$flashMessage = txid ? {
          type: 'success',
          message: 'Transaction broadcasted. txid: ' + txid
        } : {
          type: 'error',
          message: 'There was an error sending the Transaction'
        };
        if (cb) return cb();
        else $scope.update();
      });
    };

    $scope.sign = function(ntxid) {
      $scope.loading = true;
      var w = $rootScope.wallet;
      w.sign(ntxid, function(ret) {
        if (!ret) {
          $rootScope.$flashMessage = {
            type: 'error',
            message: 'There was an error signing the Transaction',
          };
          $scope.update();
        } else {
          var p = w.txProposals.getTxProposal(ntxid);
          if (p.builder.isFullySigned()) {
            $scope.send(ntxid, function() {
              $scope.update();
            });
          } else
            $scope.update();
        }
      });
    };

    $scope.getTransactions = function() {
      var w = $rootScope.wallet;
      $scope.loading = true;
      if (w) {
        var addresses = w.getAddressesStr();
        if (addresses.length > 0) {
          $scope.blockchain_txs = $scope.wallet.txCache || [];
          w.blockchain.getTransactions(addresses, function(txs) {
            $timeout(function() {
              $scope.blockchain_txs = [];
              for (var i = 0; i < txs.length; i++) {
                txs[i].vinSimple = _aggregateItems(txs[i].vin);
                txs[i].voutSimple = _aggregateItems(txs[i].vout);
                txs[i].valueOut = ((txs[i].valueOut * bitcore.util.COIN).toFixed(0)) * satToUnit;
                txs[i].fees = ((txs[i].fees * bitcore.util.COIN).toFixed(0)) * satToUnit;
                $scope.blockchain_txs.push(txs[i]);
              }
              $scope.wallet.txCache = $scope.blockchain_txs;
              $scope.loading = false;
            }, 10);
          });
        } else {
          $timeout(function() {
            $scope.loading = false;
            $scope.lastShowed = false;
          }, 1);
        }
      }
    };

    $scope.getShortNetworkName = function() {
      return config.networkName.substring(0, 4);
    };

    $scope.reject = function(ntxid) {
      $scope.loading = true;
      $rootScope.txAlertCount = 0;
      var w = $rootScope.wallet;
      w.reject(ntxid);
      $rootScope.$flashMessage = {
        type: 'warning',
        message: 'Transaction rejected by you'
      };
      $scope.loading = false;
    };

    // Autoload transactions on 1-of-1
    if ($rootScope.wallet && $rootScope.wallet.totalCopayers == 1) {
      $scope.lastShowed = true;
      $scope.getTransactions();
    }

  });
<commit_msg>remove flashmessages from transactions<commit_after>'use strict';
var bitcore = require('bitcore');

angular.module('copayApp.controllers').controller('TransactionsController',
  function($scope, $rootScope, $timeout, controllerUtils) {

    $scope.title = 'Transactions';
    $scope.loading = false;
    $scope.onlyPending = true;
    $scope.lastShowed = false;

    $scope.txpCurrentPage = 1;
    $scope.txpItemsPerPage = 4;
    $scope.blockchain_txs = [];

    var satToUnit = 1 / config.unitToSatoshi;

    $scope.update = function() {
      $scope.loading = false;
      var from = ($scope.txpCurrentPage - 1) * $scope.txpItemsPerPage;
      var opts = {
        onlyPending: $scope.onlyPending,
        skip: !$scope.onlyPending ? [from, from + $scope.txpItemsPerPage] : null
      };
      controllerUtils.updateTxs(opts);
      $rootScope.$digest();
    };

    $scope.show = function(onlyPending) {
      $scope.loading = true;
      $scope.onlyPending = onlyPending;
      setTimeout(function() {
        $scope.update();
      }, 10);
    };

    var _aggregateItems = function(items) {
      if (!items) return [];

      var l = items.length;

      var ret = [];
      var tmp = {};
      var u = 0;

      for (var i = 0; i < l; i++) {

        var notAddr = false;
        // non standard input
        if (items[i].scriptSig && !items[i].addr) {
          items[i].addr = 'Unparsed address [' + u+++']';
          items[i].notAddr = true;
          notAddr = true;
        }

        // non standard output
        if (items[i].scriptPubKey && !items[i].scriptPubKey.addresses) {
          items[i].scriptPubKey.addresses = ['Unparsed address [' + u+++']'];
          items[i].notAddr = true;
          notAddr = true;
        }

        // multiple addr at output
        if (items[i].scriptPubKey && items[i].scriptPubKey.addresses.length > 1) {
          items[i].addr = items[i].scriptPubKey.addresses.join(',');
          ret.push(items[i]);
          continue;
        }

        var addr = items[i].addr || (items[i].scriptPubKey && items[i].scriptPubKey.addresses[0]);

        if (!tmp[addr]) {
          tmp[addr] = {};
          tmp[addr].valueSat = 0;
          tmp[addr].count = 0;
          tmp[addr].addr = addr;
          tmp[addr].items = [];
        }
        tmp[addr].isSpent = items[i].spentTxId;

        tmp[addr].doubleSpentTxID = tmp[addr].doubleSpentTxID || items[i].doubleSpentTxID;
        tmp[addr].doubleSpentIndex = tmp[addr].doubleSpentIndex || items[i].doubleSpentIndex;
        tmp[addr].unconfirmedInput += items[i].unconfirmedInput;
        tmp[addr].dbError = tmp[addr].dbError || items[i].dbError;
        tmp[addr].valueSat += parseInt((items[i].value * bitcore.util.COIN).toFixed(0));
        tmp[addr].items.push(items[i]);
        tmp[addr].notAddr = notAddr;
        tmp[addr].count++;
      }

      angular.forEach(tmp, function(v) {
        v.value = (parseInt(v.valueSat || 0).toFixed(0)) * satToUnit;
        ret.push(v);
      });
      return ret;
    };

    $scope.toogleLast = function() {
      $scope.lastShowed = !$scope.lastShowed;
      if ($scope.lastShowed) {
        $scope.getTransactions();
      }
    };

    $scope.send = function(ntxid, cb) {
      $scope.loading = true;
      $rootScope.txAlertCount = 0;
      var w = $rootScope.wallet;
      w.sendTx(ntxid, function(txid) {
        if (!txid) {
          notification.error('Error', 'There was an error sending the transaction');
        } else {
          notification.success('Transaction broadcast', 'Transaction id: '+txid);
        }
        if (cb) return cb();
        else $scope.update();
      });
    };

    $scope.sign = function(ntxid) {
      $scope.loading = true;
      var w = $rootScope.wallet;
      w.sign(ntxid, function(ret) {
        if (!ret) {
          notification.error('Error', 'There was an error signing the transaction');
          $scope.update();
        } else {
          var p = w.txProposals.getTxProposal(ntxid);
          if (p.builder.isFullySigned()) {
            $scope.send(ntxid, function() {
              $scope.update();
            });
          } else
            $scope.update();
        }
      });
    };

    $scope.getTransactions = function() {
      var w = $rootScope.wallet;
      $scope.loading = true;
      if (w) {
        var addresses = w.getAddressesStr();
        if (addresses.length > 0) {
          $scope.blockchain_txs = $scope.wallet.txCache || [];
          w.blockchain.getTransactions(addresses, function(txs) {
            $timeout(function() {
              $scope.blockchain_txs = [];
              for (var i = 0; i < txs.length; i++) {
                txs[i].vinSimple = _aggregateItems(txs[i].vin);
                txs[i].voutSimple = _aggregateItems(txs[i].vout);
                txs[i].valueOut = ((txs[i].valueOut * bitcore.util.COIN).toFixed(0)) * satToUnit;
                txs[i].fees = ((txs[i].fees * bitcore.util.COIN).toFixed(0)) * satToUnit;
                $scope.blockchain_txs.push(txs[i]);
              }
              $scope.wallet.txCache = $scope.blockchain_txs;
              $scope.loading = false;
            }, 10);
          });
        } else {
          $timeout(function() {
            $scope.loading = false;
            $scope.lastShowed = false;
          }, 1);
        }
      }
    };

    $scope.getShortNetworkName = function() {
      return config.networkName.substring(0, 4);
    };

    $scope.reject = function(ntxid) {
      $scope.loading = true;
      $rootScope.txAlertCount = 0;
      var w = $rootScope.wallet;
      w.reject(ntxid);
      notification.warning('Transaction rejected', 'You rejected the transaction successfully');
      $scope.loading = false;
    };

    // Autoload transactions on 1-of-1
    if ($rootScope.wallet && $rootScope.wallet.totalCopayers == 1) {
      $scope.lastShowed = true;
      $scope.getTransactions();
    }

  });
<|endoftext|>


<commit_before>// ******************************************************************
// Format keyword
// ******************************************************************

var Errors = require('../../../../errors.js')
  , core = require('../../core.js')
  ;

module.exports = function(config) {
  var errors = [];
  var valid = false;

  var match = config.inst.match(core.FORMAT_REGEXPS['date-time']);

  if (match) {
    var year = parseInt(match[1], 10);
    var month = parseInt(match[2], 10);
    var mday = parseInt(match[3], 10);
    var hour = parseInt(match[4], 10);
    var min = parseInt(match[5], 10);
    var sec = parseInt(match[6], 10);

    if (
        month >= 1 && month <= 12 &&
        mday >= 1 && mday <= 31 &&
        hour >= 0 && hour <= 23 &&
        min >= 0 && min <= 59 &&
        sec >= 0 && sec <= 60       // it’s 60 during a leap second
       )
    {
      var d = new Date(year, (month - 1) + 1);  // the next month
      var lastDay = new Date(d - 86400000);
      if (mday <= lastDay.getDate()) {

        // [day-of-month is valid]

        if (match[10]) {
          var offsetHour = parseInt(match[10], 10);
          var offsetMin = parseInt(match[11], 10);
          if (
              offsetHour >=0 && offsetHour <= 23 &&
              offsetMin >= 0 && offsetMin <= 59
             )
          {
            valid = true;
          }
        } else {
          valid = true;
        }
      }
    }
  }

  if (!valid) {
    var desc = 'not a valid date-time per RFC 3339 secton 5.6 ' +
      '(use "date" for date-only or "time" for time-only)';
    errors.push(new Errors.FormatValidationError(config.resolutionScope,
      config.instanceContext, 'format', 'date-time', config.inst, desc));
  }

  return errors;
};

<commit_msg>fix typo<commit_after>// ******************************************************************
// Format keyword
// ******************************************************************

var Errors = require('../../../../errors.js')
  , core = require('../../core.js')
  ;

module.exports = function(config) {
  var errors = [];
  var valid = false;

  var match = config.inst.match(core.FORMAT_REGEXPS['date-time']);

  if (match) {
    var year = parseInt(match[1], 10);
    var month = parseInt(match[2], 10);
    var mday = parseInt(match[3], 10);
    var hour = parseInt(match[4], 10);
    var min = parseInt(match[5], 10);
    var sec = parseInt(match[6], 10);

    if (
        month >= 1 && month <= 12 &&
        mday >= 1 && mday <= 31 &&
        hour >= 0 && hour <= 23 &&
        min >= 0 && min <= 59 &&
        sec >= 0 && sec <= 60       // it’s 60 during a leap second
       )
    {
      var d = new Date(year, (month - 1) + 1);  // the next month
      var lastDay = new Date(d - 86400000);
      if (mday <= lastDay.getDate()) {

        // [day-of-month is valid]

        if (match[10]) {
          var offsetHour = parseInt(match[10], 10);
          var offsetMin = parseInt(match[11], 10);
          if (
              offsetHour >=0 && offsetHour <= 23 &&
              offsetMin >= 0 && offsetMin <= 59
             )
          {
            valid = true;
          }
        } else {
          valid = true;
        }
      }
    }
  }

  if (!valid) {
    var desc = 'not a valid date-time per RFC 3339 section 5.6 ' +
      '(use "date" for date-only or "time" for time-only)';
    errors.push(new Errors.FormatValidationError(config.resolutionScope,
      config.instanceContext, 'format', 'date-time', config.inst, desc));
  }

  return errors;
};

<|endoftext|>


<commit_before>var OsmFeatureSelector = Backbone.Form.editors.Base.extend({
    /*
     * TODO:
     * o ajouter la possibiliter de filtrer sur tag/key
     * x sélectionner this.value lors de l'init le cas échéant
     * o ajouter un  marqueur "vous êtes ici"
     * o étendre OL.Protocol.HTTP pour définir filterToParams
     * o essayer de positionner la carte en CSS (déporter le createmap ? sur quel évènement ?)
     */

    tagName: 'div',
    className: 'osm-map',
    attributes: {tabindex: 0}, // make element "focusable"

    mapObject: null,
    dataLayer: null,
    selectedFeature: null,
    selector: null,

    events: {
        'focus': function() {this.trigger('focus', this);},
        'blur': function() {this.trigger('blur', this);}
        //'change' ?
    },

    createMap: function() {
        // Create map once
        if (this.mapObject !== null)
            return this.mapObject;

        // Ensure the map div has a size. FIXME: crappy code, should not be necessary (sizing/positionning is normally controlled by CSS...)
        var mapSize;
        if ('mapSize' in this.schema.mapConfig)
            mapSize = this.schema.mapConfig.mapSize;
        else
            mapSize = {width: '800px', height: '300px'};
        this.$el.css(mapSize);

        // Initialize map with baselayer, projection, center, etc...
        var mapOptions = {
            projection: new OpenLayers.Projection('EPSG:3857'),
            displayProjection: new OpenLayers.Projection('EPSG:4326'),
            theme: null,
            controls: [
                new OpenLayers.Control.Attribution(),
                new OpenLayers.Control.TouchNavigation({dragPanOptions: {enableKinetic: true}}),
                new OpenLayers.Control.Zoom()
            ],
            layers: []
        };
        if ('basemapUrl' in this.schema.mapConfig) {
            mapOptions.layers.push(new OpenLayers.Layer.OSM('Fond de plan', this.schema.mapConfig.basemapUrl, {tileOptions: {crossOriginKeyword: null}, transitionEffect: 'resize'}));
        } else {
            mapOptions.layers.push(new OpenLayers.Layer.OSM('Fond de plan', null, {transitionEffect: 'resize'}));
        }
        this.mapObject = new OpenLayers.Map(this.el, mapOptions);
        if ('currentPosition' in this.schema.mapConfig) {
            // Zoom to a focus point if any
            this.mapObject.setCenter(
                (new OpenLayers.LonLat([this.schema.mapConfig.currentPosition.lon, this.schema.mapConfig.currentPosition.lat])).transform(mapOptions.displayProjection, mapOptions.projection),
                18
            );
        } else {
            // Zoom to a wide extent otherwise
            var ext = this.schema.mapConfig.mapExtent,
                bounds = new OpenLayers.Bounds([ext.minx, ext.miny, ext.maxx, ext.maxy]);
            this.mapObject.zoomToExtent(bounds.transform(mapOptions.displayProjection, mapOptions.projection));
        }

        // Add vector data layer
        this.dataLayer = new OpenLayers.Layer.Vector('Données', {
            strategies: [new OpenLayers.Strategy.Fixed()],
            projection: 'EPSG:4326',
            protocol: new OpenLayers.Protocol.HTTP({
                format: new OpenLayers.Format.OSM()
            })
        });
        this.mapObject.addLayer(this.dataLayer);

        this.dataLayer.events.on({
            featureselected: function (e) {
                this.trigger('change', this);
            },
            featureunselected: function (e) {
                this.trigger('change', this);
            },
            scope: this
        });

        this.selector = new OpenLayers.Control.SelectFeature(this.dataLayer, {'toggle': true});
        this.mapObject.addControl(this.selector);
        this.selector.activate();

        if (this.value !== null) this.setValue(this.value);

        // Add a button on the map for data loading
        var loadButton = $('<div>')
            .css({position: 'absolute', top: '1em', right: '1em', 'z-index': 1000})
            .append(
                $('<button type="button">')
                    .addClass('btn').append($('<i>').addClass('icon-download'))
                    .on('click', $.proxy(this.loadData, this))
            );
        this.$el.append(loadButton);
    },

    loadData: function() {
        var extent = this.mapObject.getExtent();
        if (extent === null) return; // Map is not initialized yet
        if (this.mapObject.getZoom() < 17) return; // Extent is too wide
        extent = extent.transform(this.mapObject.getProjectionObject(), this.mapObject.displayProjection);
        // /!\ Possible cross-domain request issues here
        this.dataLayer.strategies[0].load({url: 'http://api.openstreetmap.fr/api/0.6/map?bbox='+extent.left+','+extent.bottom+','+extent.right+','+extent.top});
    },

    render: function() {
        this.createMap();
        this.loadData();
        return this;
    },

    getValue: function() {
        if (this.dataLayer.selectedFeatures.length == 1)
            return this.dataLayer.selectedFeatures[0].fid;
        return null;
    },
    setValue: function(value) {
        var i, j, f;
        for (i=0; i<this.dataLayer.features.length; i++) {
            f = this.dataLayer.features[i];
            if (f.fid == value) {
                for (j=0; j<this.dataLayer.selectedFeatures.length; j++) {
                    this.selector.unselect(this.dataLayer.selectedFeatures[j]);
                }
                this.selector.select(f);
                return;
            }
        }
        console.log('OsmFeatureSelector: feature is not available in the current scope');
    },

    focus: function() {
        if (this.hasFocus) return;
        this.$el.focus();
    },
    blur: function() {
        if (!this.hasFocus) return;
        this.$el.blur();
    }
});<commit_msg>bugfix: trigger change event when map feature is deselected by a data reload<commit_after>var OsmFeatureSelector = Backbone.Form.editors.Base.extend({
    /*
     * TODO:
     * o ajouter la possibiliter de filtrer sur tag/key
     * x sélectionner this.value lors de l'init le cas échéant
     * o ajouter un  marqueur "vous êtes ici"
     * o étendre OL.Protocol.HTTP pour définir filterToParams
     * o essayer de positionner la carte en CSS (déporter le createmap ? sur quel évènement ?)
     */

    tagName: 'div',
    className: 'osm-map',
    attributes: {tabindex: 0}, // make element "focusable"

    mapObject: null,
    dataLayer: null,
    selectedFeature: null,
    selector: null,

    events: {
        'focus': function() {this.trigger('focus', this);},
        'blur': function() {this.trigger('blur', this);}
        //'change' ?
    },

    createMap: function() {
        // Create map once
        if (this.mapObject !== null)
            return this.mapObject;

        // Ensure the map div has a size. FIXME: crappy code, should not be necessary (sizing/positionning is normally controlled by CSS...)
        var mapSize;
        if ('mapSize' in this.schema.mapConfig)
            mapSize = this.schema.mapConfig.mapSize;
        else
            mapSize = {width: '800px', height: '300px'};
        this.$el.css(mapSize);

        // Initialize map with baselayer, projection, center, etc...
        var mapOptions = {
            projection: new OpenLayers.Projection('EPSG:3857'),
            displayProjection: new OpenLayers.Projection('EPSG:4326'),
            theme: null,
            controls: [
                new OpenLayers.Control.Attribution(),
                new OpenLayers.Control.TouchNavigation({dragPanOptions: {enableKinetic: true}}),
                new OpenLayers.Control.Zoom()
            ],
            layers: []
        };
        if ('basemapUrl' in this.schema.mapConfig) {
            mapOptions.layers.push(new OpenLayers.Layer.OSM('Fond de plan', this.schema.mapConfig.basemapUrl, {tileOptions: {crossOriginKeyword: null}, transitionEffect: 'resize'}));
        } else {
            mapOptions.layers.push(new OpenLayers.Layer.OSM('Fond de plan', null, {transitionEffect: 'resize'}));
        }
        this.mapObject = new OpenLayers.Map(this.el, mapOptions);
        if ('currentPosition' in this.schema.mapConfig) {
            // Zoom to a focus point if any
            this.mapObject.setCenter(
                (new OpenLayers.LonLat([this.schema.mapConfig.currentPosition.lon, this.schema.mapConfig.currentPosition.lat])).transform(mapOptions.displayProjection, mapOptions.projection),
                18
            );
        } else {
            // Zoom to a wide extent otherwise
            var ext = this.schema.mapConfig.mapExtent,
                bounds = new OpenLayers.Bounds([ext.minx, ext.miny, ext.maxx, ext.maxy]);
            this.mapObject.zoomToExtent(bounds.transform(mapOptions.displayProjection, mapOptions.projection));
        }

        // Add vector data layer
        this.dataLayer = new OpenLayers.Layer.Vector('Données', {
            strategies: [new OpenLayers.Strategy.Fixed()],
            projection: 'EPSG:4326',
            protocol: new OpenLayers.Protocol.HTTP({
                format: new OpenLayers.Format.OSM()
            })
        });
        this.mapObject.addLayer(this.dataLayer);

        this.dataLayer.events.on({
            loadend: this.triggerChange,
            featureselected: this.triggerChange,
            featureunselected: this.triggerChange,
            scope: this
        });

        this.selector = new OpenLayers.Control.SelectFeature(this.dataLayer, {'toggle': true});
        this.mapObject.addControl(this.selector);
        this.selector.activate();

        if (this.value !== null) this.setValue(this.value);

        // Add a button on the map for data loading
        var loadButton = $('<div>')
            .css({position: 'absolute', top: '1em', right: '1em', 'z-index': 1000})
            .append(
                $('<button type="button">')
                    .addClass('btn').append($('<i>').addClass('icon-download'))
                    .on('click', $.proxy(this.loadData, this))
            );
        this.$el.append(loadButton);
    },

    loadData: function() {
        var extent = this.mapObject.getExtent();
        if (extent === null) return; // Map is not initialized yet
        if (this.mapObject.getZoom() < 17) return; // Extent is too wide
        extent = extent.transform(this.mapObject.getProjectionObject(), this.mapObject.displayProjection);
        // /!\ Possible cross-domain request issues here
        this.dataLayer.strategies[0].load({url: 'http://api.openstreetmap.fr/api/0.6/map?bbox='+extent.left+','+extent.bottom+','+extent.right+','+extent.top});
    },

    triggerChange: function() {this.trigger('change', this);},

    render: function() {
        this.createMap();
        this.loadData();
        return this;
    },

    getValue: function() {
        if (this.dataLayer.selectedFeatures.length == 1)
            return this.dataLayer.selectedFeatures[0].fid;
        return null;
    },
    setValue: function(value) {
        var i, j, f;
        for (i=0; i<this.dataLayer.features.length; i++) {
            f = this.dataLayer.features[i];
            if (f.fid == value) {
                for (j=0; j<this.dataLayer.selectedFeatures.length; j++) {
                    this.selector.unselect(this.dataLayer.selectedFeatures[j]);
                }
                this.selector.select(f);
                return;
            }
        }
        console.log('OsmFeatureSelector: feature is not available in the current scope');
    },

    focus: function() {
        if (this.hasFocus) return;
        this.$el.focus();
    },
    blur: function() {
        if (!this.hasFocus) return;
        this.$el.blur();
    }
});<|endoftext|>


<commit_before>"use strict";

/*global nodeca, _*/

var NLib = require('nlib');
var Async = NLib.Vendor.Async;

var Section = nodeca.models.forum.Section;
var Thread = nodeca.models.forum.Thread;

var forum_breadcrumbs = require('../../lib/forum_breadcrumbs.js');
var to_tree = require('../../lib/to_tree.js');

var threads_in_fields = {
  '_id': 1,
  'id': 1,
  'title': 1,
  'prefix': 1,
  'forum_id': 1,
  'cache': 1
};

var subforums_in_fields = {
  '_id' : 1,
  'id' : 1,
  'title' : 1,
  'description' : 1,
  'parent' : 1,
  'parent_list' : 1,
  'moderator_list' : 1,
  'display_order' : 1,
  'cache' : 1
};

var forum_info_out_fields = [
  'id',
  'title',
  'description',
  'is_category'
];

// Prefetch forum to simplify permisson check.
// Check that forum exists.
//
nodeca.filters.before('@', function (params, next) {
  var env = this;

  env.extras.puncher.start('Forum info prefetch');

  Section.findOne({id: params.id}).setOptions({ lean: true })
      .exec(function(err, forum) {

    if (err) {
      next(err);
      return;
    }

    // No forum -> "Not Found" status
    if (!forum) {
      next({ statusCode: 404 });
      return;
    }

    env.data.section = forum;

    env.extras.puncher.stop();

    next(err);
  });
});

//
// fetch and prepare threads
//
// ##### params
//
// - `id`   forum id
//
module.exports = function (params, next) {
  var env = this;
  var paginate_by;
  var sort = {};
  var ts_from = null;
  var ts_to = null;

  // fetch and prepare threads
  env.extras.puncher.start('Get threads');

  var max_threads = nodeca.settings.global.get('max_threads_per_page');

  var start = (params.page - 1) * max_threads;
  var end   = params.page * max_threads;

  if (env.session.hb) {
    paginate_by = 'cache.hb.last_ts';
  }
  else {
    paginate_by = 'cache.real.last_ts';
  }
  sort[paginate_by] = -1;

  // FIXME add state condition only visible thread
  var query = { forum_id: params.id };

  Async.series([
    // get start bourder
    function(callback){
      Thread.find(query).select('cache').sort(sort).skip(start)
          .limit(1).setOptions({ lean: true }).exec(function(err, docs) {

        // No page -> "Not Found" status
        if (!docs.length) {
          next({ statusCode: 404 });
          return;
        }

        if (env.session.hb) {
          ts_from = docs[0].cache.hb.last_ts;
        }
        else {
          ts_from = docs[0].cache.real.last_ts;
        }
        callback();
      });
    },
    // get end bourder
    function(callback){
      Thread.find(query).select('cache').sort(sort).skip(end)
          .limit(1).setOptions({ lean: true }).exec(function(err, docs) {
        if (docs.length) {
          if (env.session.hb) {
            ts_to = docs[0].cache.hb.last_ts;
          }
          else {
            ts_to = docs[0].cache.real.last_ts;
          }
        }
        callback();
      });
    },
    // fetch threads
    function(callback) {
      // FIXME modify state condition (deleted and etc) if user has permission
      if (!!ts_to) {
        query[paginate_by] = { $lt: ts_from, $gte: ts_to };
      }
      else {
        query[paginate_by] = { $lt: ts_from };
      }

      Thread.find(query).select(threads_in_fields).sort(sort)
          .setOptions({ lean: true }).exec(function(err, threads){
        if (err) {
          callback(err);
          return;
        }

        env.data.threads = threads;

        env.extras.puncher.stop(_.isArray(threads) ? { count: threads.length } : null);

        callback();
      });
    },
    // fetch sub-forums
  ], next);

};

// fetch sub-forums (only on first page)
nodeca.filters.after('@', function (params, next) {
  var env = this;
  env.data.sections = [];
  // subforums fetched only on first page
  if (params.page > 1) {
    next();
    return;
  }
  env.extras.puncher.start('Get subforums');

  var max_level = env.data.section.level + 2; // need two next levels
  var query = {
    level: { $lte: max_level },
    parent_list: env.data.section._id
  };

  // FIXME add permissions check
  Section.find(query).select(subforums_in_fields).sort('display_order')
      .setOptions({ lean: true }).exec(function(err, sections){
    if (err) {
      next(err);
      return;
    }
    env.data.sections = sections;

    env.extras.puncher.stop({ count: sections.length });
    next();
  });
});

// Build response:
//  - forums list -> filtered tree
//  - collect users ids (last posters / moderators / threads authors + last)
//  - threads
//
nodeca.filters.after('@', function (params, next) {
  var env = this;

  env.extras.puncher.start('Post-process forums/threads/users');

  //
  // Process sections
  //

  if (env.session.hb) {
    this.data.sections = this.data.sections.map(function(doc) {
      doc.cache.real = doc.cache.hb;
      return doc;
    });
  }

  var root = this.data.section._id;
  this.response.data.sections = to_tree(this.data.sections, root);

  env.data.users = env.data.users || [];

  // collect users from subforums
  this.data.sections.forEach(function(doc){
    if (!!doc.moderator_list) {
      doc.moderator_list.forEach(function(user) {
        env.data.users.push(user);
      });
    }
    if (doc.cache.real.last_user) {
      env.data.users.push(doc.cache.real.last_user);
    }
  });

  //
  // Process threads
  //

  if (env.session.hb) {
    this.data.threads = this.data.threads.map(function(doc) {
      doc.cache.real = doc.cache.hb;
      return doc;
    });
  }

  this.response.data.threads = this.data.threads;

  // collect users from threads
  this.data.threads.forEach(function(doc) {
    if (doc.cache.real.first_user) {
      env.data.users.push(doc.cache.real.first_user);
    }
    if (doc.cache.real.last_user) {
      env.data.users.push(doc.cache.real.last_user);
    }
  });

  env.extras.puncher.stop();

  next();
});

// Fill head meta & fetch/fill breadcrumbs
//
nodeca.filters.after('@', function (params, next) {
  var env = this;
  var data = this.response.data;
  var forum = this.data.section;

  if (this.session.hb) {
    forum.cache.real = forum.cache.hb;
  }
  // prepare page title
  data.head.title = forum.title;
  if (params.page > 1) {
    data.head.title += ' - ' + env.helpers.t('forum.head.page') + ' ' + params.page;
  }

  // prepare forum info
  data.forum = _.pick(forum, forum_info_out_fields);

  // prepare pagination data
  var max_threads = nodeca.settings.global.get('max_threads_per_page');
  data.max_page = Math.ceil(forum.cache.real.thread_count / max_threads);

  // fetch breadcrumbs data
  var query = { _id: { $in: forum.parent_list } };
  var fields = { '_id': 1, 'id': 1, 'title': 1 };

  env.extras.puncher.start('Build breadcrumbs');

  Section.find(query).select(fields).sort({ 'level': 1 })
      .setOptions({lean:true}).exec(function(err, parents){
    if (err) {
      next(err);
      return;
    }

    parents.push(forum);
    data.widgets.breadcrumbs = forum_breadcrumbs(env, parents);

    env.extras.puncher.stop();

    next();
  });
});
<commit_msg>Fixed pagination algorithm in section controller<commit_after>"use strict";

/*global nodeca, _*/

var NLib = require('nlib');
var Async = NLib.Vendor.Async;

var Section = nodeca.models.forum.Section;
var Thread = nodeca.models.forum.Thread;

var forum_breadcrumbs = require('../../lib/forum_breadcrumbs.js');
var to_tree = require('../../lib/to_tree.js');

var threads_in_fields = {
  '_id': 1,
  'id': 1,
  'title': 1,
  'prefix': 1,
  'forum_id': 1,
  'cache': 1
};

var subforums_in_fields = {
  '_id' : 1,
  'id' : 1,
  'title' : 1,
  'description' : 1,
  'parent' : 1,
  'parent_list' : 1,
  'moderator_list' : 1,
  'display_order' : 1,
  'cache' : 1
};

var forum_info_out_fields = [
  'id',
  'title',
  'description',
  'is_category'
];

// Prefetch forum to simplify permisson check.
// Check that forum exists.
//
nodeca.filters.before('@', function (params, next) {
  var env = this;

  env.extras.puncher.start('Forum info prefetch');

  Section.findOne({id: params.id}).setOptions({ lean: true })
      .exec(function(err, forum) {

    if (err) {
      next(err);
      return;
    }

    // No forum -> "Not Found" status
    if (!forum) {
      next({ statusCode: 404 });
      return;
    }

    env.data.section = forum;

    env.extras.puncher.stop();

    next(err);
  });
});

//
// fetch and prepare threads
//
// ##### params
//
// - `id`   forum id
//
module.exports = function (params, next) {
  var env = this;
  var sort = {};
  var start;
  var max_threads = nodeca.settings.global.get('max_threads_per_page');

  // fetch and prepare threads
  env.extras.puncher.start('Get threads');

  if (env.session.hb) {
    sort['cache.hb.last_ts'] = -1;
  }
  else {
    sort['cache.real.last_ts'] = -1;
  }

  // FIXME add state condition only visible thread
  var conditions = {forum_id: params.id};
  start = (params.page - 1) * max_threads;
  Thread.find(conditions).select('_id').sort(sort).skip(start)
      .limit(max_threads + 1).setOptions({ lean: true }).exec(function(err, docs) {

    // No page -> "Not Found" status
    if (!docs.length) {
      next({ statusCode: 404 });
      return;
    }

    var query = Thread.find(conditions).where('_id').lte(_.first(docs)._id);
    if (docs.length <= max_threads) {
      query.gte(_.last(docs)._id);
    }
    else {
      query.gt(_.last(docs)._id);
    }

    // FIXME modify state condition (deleted and etc) if user has permission
    query.select(threads_in_fields).sort(sort)
        .setOptions({ lean: true }).exec(function(err, threads){
      if (err) {
        next(err);
        return;
      }

      env.data.threads = threads;

      env.extras.puncher.stop({ count: threads.length });

      next();
    });
  });
};

// fetch sub-forums (only on first page)
nodeca.filters.after('@', function (params, next) {
  var env = this;
  env.data.sections = [];
  // subforums fetched only on first page
  if (params.page > 1) {
    next();
    return;
  }
  env.extras.puncher.start('Get subforums');

  var max_level = env.data.section.level + 2; // need two next levels
  var query = {
    level: { $lte: max_level },
    parent_list: env.data.section._id
  };

  // FIXME add permissions check
  Section.find(query).select(subforums_in_fields).sort('display_order')
      .setOptions({ lean: true }).exec(function(err, sections){
    if (err) {
      next(err);
      return;
    }
    env.data.sections = sections;

    env.extras.puncher.stop({ count: sections.length });
    next();
  });
});

// Build response:
//  - forums list -> filtered tree
//  - collect users ids (last posters / moderators / threads authors + last)
//  - threads
//
nodeca.filters.after('@', function (params, next) {
  var env = this;

  env.extras.puncher.start('Post-process forums/threads/users');

  //
  // Process sections
  //

  if (env.session.hb) {
    this.data.sections = this.data.sections.map(function(doc) {
      doc.cache.real = doc.cache.hb;
      return doc;
    });
  }

  var root = this.data.section._id;
  this.response.data.sections = to_tree(this.data.sections, root);

  env.data.users = env.data.users || [];

  // collect users from subforums
  this.data.sections.forEach(function(doc){
    if (!!doc.moderator_list) {
      doc.moderator_list.forEach(function(user) {
        env.data.users.push(user);
      });
    }
    if (doc.cache.real.last_user) {
      env.data.users.push(doc.cache.real.last_user);
    }
  });

  //
  // Process threads
  //

  if (env.session.hb) {
    this.data.threads = this.data.threads.map(function(doc) {
      doc.cache.real = doc.cache.hb;
      return doc;
    });
  }

  this.response.data.threads = this.data.threads;

  // collect users from threads
  this.data.threads.forEach(function(doc) {
    if (doc.cache.real.first_user) {
      env.data.users.push(doc.cache.real.first_user);
    }
    if (doc.cache.real.last_user) {
      env.data.users.push(doc.cache.real.last_user);
    }
  });

  env.extras.puncher.stop();

  next();
});

// Fill head meta & fetch/fill breadcrumbs
//
nodeca.filters.after('@', function (params, next) {
  var env = this;
  var data = this.response.data;
  var forum = this.data.section;

  if (this.session.hb) {
    forum.cache.real = forum.cache.hb;
  }
  // prepare page title
  data.head.title = forum.title;
  if (params.page > 1) {
    data.head.title += ' - ' + env.helpers.t('forum.head.page') + ' ' + params.page;
  }

  // prepare forum info
  data.forum = _.pick(forum, forum_info_out_fields);

  // prepare pagination data
  var max_threads = nodeca.settings.global.get('max_threads_per_page');
  data.max_page = Math.ceil(forum.cache.real.thread_count / max_threads);

  // fetch breadcrumbs data
  var query = { _id: { $in: forum.parent_list } };
  var fields = { '_id': 1, 'id': 1, 'title': 1 };

  env.extras.puncher.start('Build breadcrumbs');

  Section.find(query).select(fields).sort({ 'level': 1 })
      .setOptions({lean:true}).exec(function(err, parents){
    if (err) {
      next(err);
      return;
    }

    parents.push(forum);
    data.widgets.breadcrumbs = forum_breadcrumbs(env, parents);

    env.extras.puncher.stop();

    next();
  });
});
<|endoftext|>


<commit_before>var debug = require('debug')('mpdisco:command_emitters');
var CoverArt = require('./cover_art.js');

function log(command, args, response) {
    debug('Emitting: %s %s: %s', command, JSON.stringify(args), JSON.stringify(response));
}

var specialEmitters = {
    list: function emitSpecializedEvent(command, args, response, client) {
        if (args.length) {
            log(command, args, response)

            client.emit(command, response);

            command = command + ':' + args[0].toLowerCase();

            log(command, args.slice(1), response)

            client.emit(command, {
                args: args.slice(1),
                data: response
            });
        }
    },
    find: function emitCommandWithEverySecondArg(command, args, response, client) {
        if (args.length) {
            log(command, args, response)

            client.emit(command, {
                args: _.filter(args, function(v, i) { return (i % 2 == 1); }),
                data: response
            });
        }
    },
    currentsong: function(command, args, response, client) {

        client.emit(command, response);

        log(command, args, response)

        if (response && response.artist && response.album) {

            CoverArt
                .getCover({ artist: response.artist, release: response.album })
                .then(function(url) {
                    debug('Sending cover: %s', url);

                    client.emit('coverart', {
                        url: url
                    });
                })
                .fail(function(error) {
                    debug('Cover retrieval failed. %s', error);

                    client.emit('coverart', {
                        url: null
                    });
                });
        }
    }
};

function simpleEmitter(command, args, response, client) {
    log(command, args, response)

    client.emit(command, response);
}

module.exports = {
    emitters: specialEmitters,
    emitterForCommand: function(command) {
        return specialEmitters[command] || simpleEmitter;
    }
};<commit_msg>Fixed a bug in the server.<commit_after>var debug = require('debug')('mpdisco:command_emitters');
var CoverArt = require('./cover_art.js');

function log(command, args, response) {
    debug('Emitting: %s %s: %s', command, JSON.stringify(args), JSON.stringify(response));
}

var specialEmitters = {
    list: function emitSpecializedEvent(command, args, response, client) {
        if (args.length) {
            log(command, args, response)

            client.emit(command, response);

            command = command + ':' + args[0].toLowerCase();

            log(command, args.slice(1), response)

            client.emit(command, {
                args: args.slice(1),
                data: response
            });
        }
    },
    find: function emitCommandWithEverySecondArg(command, args, response, client) {
        if (args.length) {
            log(command, args, response)

            client.emit(command, {
                args: args.filter(function(v, i) { return (i % 2 == 1); }),
                data: response
            });
        }
    },
    currentsong: function(command, args, response, client) {

        client.emit(command, response);

        log(command, args, response)

        if (response && response.artist && response.album) {

            CoverArt
                .getCover({ artist: response.artist, release: response.album })
                .then(function(url) {
                    debug('Sending cover: %s', url);

                    client.emit('coverart', {
                        url: url
                    });
                })
                .fail(function(error) {
                    debug('Cover retrieval failed. %s', error);

                    client.emit('coverart', {
                        url: null
                    });
                });
        }
    }
};

function simpleEmitter(command, args, response, client) {
    log(command, args, response)

    client.emit(command, response);
}

module.exports = {
    emitters: specialEmitters,
    emitterForCommand: function(command) {
        return specialEmitters[command] || simpleEmitter;
    }
};<|endoftext|>


<commit_before>define("ace/mode/sparql_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) {
/*var _ = {require: require, exports: exports, module: module};
exports = undefined; module = undefined;
function define(name, deps, m) {
    if (typeof name == "function") {
        m = name; deps = ["require", "exports", "module"]; name = _.module.id
    }
    if (typeof name == "object") {
        m = deps; deps = name; name = _.module.id
    }
    if (typeof deps == "function") {
        m = deps; deps = [];
    }
   var ret = m.apply(_.module, deps.map(function(n){return _[n] || require(n)}))
   if (ret) _.module.exports = ret;
}
define.amd = true;define("ace/mode/sparql_highlight_rules", function(require, exports, module) {*/

var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var SparqlHighlightRules = function() {

  var builtinFunctions_str = "str|lang|langmatches|datatype|bound|sameterm|isiri|isuri|isblank|isliteral|union|a|count|number";
  var builtinFunctions = lang.arrayToMap(builtinFunctions_str.split("|"));
  var keyword_str = "BASE|PREFIX|SELECT|ASK|CONSTRUCT|DESCRIBE|WHERE|FROM|REDUCED|NAMED|ORDER|GROUP|LIMIT|OFFSET|FILTER|OPTIONAL|GRAPH|BY|ASC|DESC|UNION|MINUS|SERVICE|DISTINCT";

  var keywords = lang.arrayToMap(keyword_str.split("|"));

  var buildinConstants = "true|false".split("|");

  this.$keywords = keyword_str.split("|");
  Array.prototype.push.apply(this.$keywords, builtinFunctions_str.split("|"));

  var builtinVariables = lang.arrayToMap(
    ("").split("|")
  );

  this.$rules = {
    "start" : [
      {
        token : "comment",
        regex : "#.*$"
      }, {
        token : "sparql.constant.uri",
        regex : "\\<\\S+\\>"
      }, {
        token : "sparql.variable",
        regex : "[\\?\\$][a-zA-Z_][a-zA-Z_0-9]*"
      }, {
        token : "sparql.prefix.constant.language",
        regex : "[a-zA-Z]+:"
      }, {
        token : "string.regexp",
        regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
      }, {
        token : "string", // single line
        regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
      }, {
        token : "string", // single line
        regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
      }, {
        token : "constant.numeric", // hex
        regex : "0[xX][0-9a-fA-F]+\\b"
      }, {
        token : "constant.numeric", // float
        regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
      }, {
        token : "constant.language.boolean",
        regex : "(?:true|false)\\b"
      }, {
        token : function(value) {
          if (value == "self")
            return "variable.language";
          else if (keywords.hasOwnProperty(value.toUpperCase()))
            return "keyword";
          else if (buildinConstants.hasOwnProperty(value.toUpperCase()))
            return "constant.language";
          else if (builtinVariables.hasOwnProperty(value))
            return "variable.language";
          else if (builtinFunctions.hasOwnProperty(value.toLowerCase()))
            return "support.function";
          else if (value == "debugger")
            return "invalid.deprecated";
          else
            return "identifier";
        },
        regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
      }, {
        token : "keyword.operator",
        regex : "\\*|\\+|\\|\\-|\\<|\\>|=|&|\\|"
      }, {
        token : "lparen",
        regex : "[\\<({]"
      }, {
        token : "rparen",
        regex : "[\\>)}]"
      }, {
        token : "text",
        regex : "\\s+"
      }, {
		caseInsensitive: true
	  }
    ],
    "comment" : [
      {
        token : "comment", // comment spanning whole line
        regex : ".+"
      }
    ]
  };
};

oop.inherits(SparqlHighlightRules, TextHighlightRules);
exports.SparqlHighlightRules = SparqlHighlightRules;
});//});

define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";

var Range = require("../range").Range;

var MatchingBraceOutdent = function() {

(function() {

    this.checkOutdent = function(line, input) {
        if (! /^\s+$/.test(line))
            return false;

        return /^\s*\}/.test(input);
    };

    this.autoOutdent = function(doc, row) {
        var line = doc.getLine(row);
        var match = line.match(/^(\s*\})/);

        if (!match) return 0;

        var column = match[1].length;
        var openBracePos = doc.findMatchingBracket({row: row, column: column});

        if (!openBracePos || openBracePos.row == row) return 0;

        var indent = this.$getIndent(doc.getLine(openBracePos.row));
        doc.replace(new Range(row, 0, row, column-1), indent);
    };

    this.$getIndent = function(line) {
        return line.match(/^\s*/)[0];
    };

}).call(MatchingBraceOutdent.prototype);

exports.MatchingBraceOutdent = MatchingBraceOutdent;
};
});

define("ace/mode/sparql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/sparql_highlight_rules","ace/mode/matching_brace_outdent","ace/range"], function(require, exports, module) {
/*var _ = {require: require, exports: exports, module: module};
exports = undefined; module = undefined;
function define(name, deps, m) {
    if (typeof name == "function") {
        m = name; deps = ["require", "exports", "module"]; name = _.module.id
    }
    if (typeof name == "object") {
        m = deps; deps = name; name = _.module.id
    }
    if (typeof deps == "function") {
        m = deps; deps = [];
    }
   var ret = m.apply(_.module, deps.map(function(n){return _[n] || require(n)}))
   if (ret) _.module.exports = ret;
}

define.amd = true;define("ace/mode/sparql", function(require, exports, module) {*/
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var SparqlHighlightRules = require("./sparql_highlight_rules").SparqlHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;

var Mode = function() {
  this.$tokenizer = new Tokenizer(new SparqlHighlightRules().getRules());
  this.$highlightRules = new SparqlHighlightRules();
  this.$highlightRules.$meta = "SPARQL Core";
  this.$highlightRules.$keywordList = this.$highlightRules.$keywords;
};
oop.inherits(Mode, TextMode);

exports.Mode = Mode;

});
//});
<commit_msg>Updated sparql keywords & functions<commit_after>define("ace/mode/sparql_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) {
/*var _ = {require: require, exports: exports, module: module};
exports = undefined; module = undefined;
function define(name, deps, m) {
    if (typeof name == "function") {
        m = name; deps = ["require", "exports", "module"]; name = _.module.id
    }
    if (typeof name == "object") {
        m = deps; deps = name; name = _.module.id
    }
    if (typeof deps == "function") {
        m = deps; deps = [];
    }
   var ret = m.apply(_.module, deps.map(function(n){return _[n] || require(n)}))
   if (ret) _.module.exports = ret;
}
define.amd = true;define("ace/mode/sparql_highlight_rules", function(require, exports, module) {*/

var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var SparqlHighlightRules = function() {

  var builtinFunctions_str = "str|lang|langmatches|datatype|bound|sameterm|isiri|isuri|isblank|isliteral|union|a|count|number|sum|min|max|avg";
  var builtinFunctions = lang.arrayToMap(builtinFunctions_str.split("|"));
  var keyword_str = "BASE|PREFIX|SELECT|ASK|CONSTRUCT|DESCRIBE|WHERE|FROM|REDUCED|NAMED|ORDER|GROUP|LIMIT|OFFSET|FILTER|OPTIONAL|GRAPH|BY|ASC|DESC|UNION|MINUS|SERVICE|DISTINCT|AS";

  var keywords = lang.arrayToMap(keyword_str.split("|"));

  var buildinConstants = "true|false".split("|");

  this.$keywords = keyword_str.split("|");
  Array.prototype.push.apply(this.$keywords, builtinFunctions_str.split("|"));

  var builtinVariables = lang.arrayToMap(
    ("").split("|")
  );

  this.$rules = {
    "start" : [
      {
        token : "comment",
        regex : "#.*$"
      }, {
        token : "sparql.constant.uri",
        regex : "\\<\\S+\\>"
      }, {
        token : "sparql.variable",
        regex : "[\\?\\$][a-zA-Z_][a-zA-Z_0-9]*"
      }, {
        token : "sparql.prefix.constant.language",
        regex : "[a-zA-Z]+:"
      }, {
        token : "string.regexp",
        regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
      }, {
        token : "string", // single line
        regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
      }, {
        token : "string", // single line
        regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
      }, {
        token : "constant.numeric", // hex
        regex : "0[xX][0-9a-fA-F]+\\b"
      }, {
        token : "constant.numeric", // float
        regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
      }, {
        token : "constant.language.boolean",
        regex : "(?:true|false)\\b"
      }, {
        token : function(value) {
          if (value == "self")
            return "variable.language";
          else if (keywords.hasOwnProperty(value.toUpperCase()))
            return "keyword";
          else if (buildinConstants.hasOwnProperty(value.toUpperCase()))
            return "constant.language";
          else if (builtinVariables.hasOwnProperty(value))
            return "variable.language";
          else if (builtinFunctions.hasOwnProperty(value.toLowerCase()))
            return "support.function";
          else if (value == "debugger")
            return "invalid.deprecated";
          else
            return "identifier";
        },
        regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
      }, {
        token : "keyword.operator",
        regex : "\\*|\\+|\\|\\-|\\<|\\>|=|&|\\|"
      }, {
        token : "lparen",
        regex : "[\\<({]"
      }, {
        token : "rparen",
        regex : "[\\>)}]"
      }, {
        token : "text",
        regex : "\\s+"
      }, {
		caseInsensitive: true
	  }
    ],
    "comment" : [
      {
        token : "comment", // comment spanning whole line
        regex : ".+"
      }
    ]
  };
};

oop.inherits(SparqlHighlightRules, TextHighlightRules);
exports.SparqlHighlightRules = SparqlHighlightRules;
});//});

define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";

var Range = require("../range").Range;

var MatchingBraceOutdent = function() {

(function() {

    this.checkOutdent = function(line, input) {
        if (! /^\s+$/.test(line))
            return false;

        return /^\s*\}/.test(input);
    };

    this.autoOutdent = function(doc, row) {
        var line = doc.getLine(row);
        var match = line.match(/^(\s*\})/);

        if (!match) return 0;

        var column = match[1].length;
        var openBracePos = doc.findMatchingBracket({row: row, column: column});

        if (!openBracePos || openBracePos.row == row) return 0;

        var indent = this.$getIndent(doc.getLine(openBracePos.row));
        doc.replace(new Range(row, 0, row, column-1), indent);
    };

    this.$getIndent = function(line) {
        return line.match(/^\s*/)[0];
    };

}).call(MatchingBraceOutdent.prototype);

exports.MatchingBraceOutdent = MatchingBraceOutdent;
};
});

define("ace/mode/sparql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/sparql_highlight_rules","ace/mode/matching_brace_outdent","ace/range"], function(require, exports, module) {
/*var _ = {require: require, exports: exports, module: module};
exports = undefined; module = undefined;
function define(name, deps, m) {
    if (typeof name == "function") {
        m = name; deps = ["require", "exports", "module"]; name = _.module.id
    }
    if (typeof name == "object") {
        m = deps; deps = name; name = _.module.id
    }
    if (typeof deps == "function") {
        m = deps; deps = [];
    }
   var ret = m.apply(_.module, deps.map(function(n){return _[n] || require(n)}))
   if (ret) _.module.exports = ret;
}

define.amd = true;define("ace/mode/sparql", function(require, exports, module) {*/
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var SparqlHighlightRules = require("./sparql_highlight_rules").SparqlHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;

var Mode = function() {
  this.$tokenizer = new Tokenizer(new SparqlHighlightRules().getRules());
  this.$highlightRules = new SparqlHighlightRules();
  this.$highlightRules.$meta = "SPARQL Core";
  this.$highlightRules.$keywordList = this.$highlightRules.$keywords;
};
oop.inherits(Mode, TextMode);

exports.Mode = Mode;

});
//});
<|endoftext|>


<commit_before>'use strict';
var async = require('async');
var _ = require('underscore');
var Team = require('../models/Team');
var teams = _.map([
    { name: 'DK'},
    { name: 'IG'},
    { name: 'VG'},
    { name: 'LGD',
      alias: ['LGD.taobao']},
    { name: 'NewBee'},
    { name: 'DT'},
    { name: 'TongFu',
      alias: ['TF.Wz', 'TongFu.Wz', 'TF'] },
    { name: 'CIS'}
], function (team) {
    if (team.alias === undefined)
        team.alias = [];
    team.alias.push(team.name);
    return team;
});

require('./opendbonce')(function (cb) {
    async.eachSeries(teams, function(team, cb) {
        var mteam = new Team();
        _.extend(mteam, team).save(cb);
    }, function (err) {
        if (err) {
            console.log(err);
        }
        cb();
    });
});<commit_msg>add alias for newbee<commit_after>'use strict';
var async = require('async');
var _ = require('underscore');
var Team = require('../models/Team');
var teams = _.map([
    { name: 'DK'},
    { name: 'IG'},
    { name: 'VG'},
    { name: 'LGD',
      alias: ['LGD.taobao']},
    { name: 'NewBee',
      alias: ['NB']},
    { name: 'DT'},
    { name: 'TongFu',
      alias: ['TF.Wz', 'TongFu.Wz', 'TF'] },
    { name: 'CIS'}
], function (team) {
    if (team.alias === undefined)
        team.alias = [];
    team.alias.push(team.name);
    return team;
});

require('./opendbonce')(function (cb) {
    async.eachSeries(teams, function(team, cb) {
        var mteam = new Team();
        _.extend(mteam, team).save(cb);
    }, function (err) {
        if (err) {
            console.log(err);
        }
        cb();
    });
});<|endoftext|>


<commit_before>// Load in our dependencies
var assert = require('assert');
var ecmaScopes = require('ecma-scopes');
var estraverse = require('estraverse');

// Define constants
var SCOPE_INFO_INSIDE_WITH = {
  YES: true,
  NO: false
};
var SCOPE_INFO_USED_IN_A_WITH = {
  YES: true,
  NO: false
};
var SCOPE_INFO_TOP_LEVEL = {
  YES: true,
  NO: false
};
var SCOPE_INFO_TYPES = {
  LEXICAL: 'lexical',
  BLOCK: 'block',
  UNDECLARED: 'undeclared'
};
var SCOPE_TYPES = {
  LEXICAL: 'lexical',
  WITH: 'with',
  BLOCK: 'block'
};

// Define helper to check a new scope
function getScopeType(node) {
  if (node.type === 'Program') {
    // DEV: We mark `program` as `lexical` because it is easier to set/compare against
    return SCOPE_TYPES.LEXICAL;
  } else if (ecmaScopes.lexical.indexOf(node.type) !== -1) {
    return SCOPE_TYPES.LEXICAL;
  } else if (node.type === 'WithStatement') {
    return SCOPE_TYPES.WITH;
  } else if (ecmaScopes.block.indexOf(node.type) !== -1) {
    return SCOPE_TYPES.BLOCK;
  } else {
    return null;
  }
}

// TODO: Move to an object or reduce the parameters. The count is too damn high
// DEV: We specify `baseNode` because it should be where we resolve the nearest scope from which may not be an identifier
function resolveScope(baseNode, identifiers, scopeType) {
  // If we resolved identifiers
  // DEV: This assert is to make it faster for developers to debug
  assert(Array.isArray(identifiers), 'Identifier resolution for baseNode "' + baseNode.type + '" did not result in an array');

  if (identifiers.length) {
    // Walk up the nearest scopes until we find one that matches our type
    // DEV: Use `scopeTypes` since a block scope can hit `Program` which is lexical
    var scope = baseNode._nearestScope;
    var scopeTypes = scopeType === SCOPE_INFO_TYPES.LEXICAL ? [SCOPE_INFO_TYPES.LEXICAL] : [SCOPE_INFO_TYPES.LEXICAL, SCOPE_INFO_TYPES.BLOCK];
    while (scope) {
      // If the scope type matches, stop
      if (scopeTypes.indexOf(scope.type) !== -1) {
        break;
      }

      // Look at the scope's parent
      scope = scope.parent;
    }

    // Expand all identifiers (e.g. object patterns to variables, `var {world}` -> `world`)
    var expandedIdentifiers = [];
    identifiers.forEach(function expandIdentifier (identifier) {
      // If it is an object pattern, expand it and save each key/identifier
      if (identifier.type === 'ObjectPattern') {
        identifier.properties.forEach(function extractObjectIdentifier (property) {
          expandedIdentifiers.push(property.key);
        });
      // Otherwise if it is an array pattern, expand it and save each identifier
      } else if (identifier.type === 'ArrayPattern') {
        identifier.elements.forEach(function extractArrayIdentifier (element) {
          expandedIdentifiers.push(element);
        });
      // Otherwise, save the original identifier
      } else {
        expandedIdentifiers.push(identifier);
      }
    });

    // Save declaration info on the scope and scope type to the identifier
    expandedIdentifiers.forEach(function saveIdentifier (identifier) {
      scope.identifiers[identifier.name] = identifier;
      identifier._scopeType = scopeType;
    });
  }
}

function walkVariables(ast, params) {
  // Walk entire tree
  estraverse.traverse(ast, {
    // Skip over undesired identifiers (e.g. `log` in `console.log`)
    // https://github.com/Constellation/estraverse/blob/1.7.0/estraverse.js#L222-L288
    keys: {
      BreakStatement: [/*'label'*/], // `loop1` in `break loop1;`
      ContinueStatement: [/*'label'*/], // `loop1` in `continue loop1;`
      LabeledStatement: [/*'label',*/ 'body'], // `loop1` in `loop1: while (true) {}`
      MemberExpression: ['object'/*, 'property'*/], // `log` in `console.log`
      Property: [/*'key',*/ 'value'] // `key` in `{key: 'value'}`
    },

    enter: function (node) {
      // If the node is an identifier, run our `enter` on it
      if (node.type === 'Identifier' && params.enter) {
        params.enter(node);
      }
    // DEV: Commented for code coverage
    // },
    // exit: function (node) {
    //   // If the node is an identifier, run our `exit` on it
    //   if (node.type === 'Identifier' && params.exit) {
    //     params.exit(node);
    //   }
    }
  });
  return ast;
}

// TODO: Consider breaking down ecmaVariableScope into 3 functions

// Define our variable scope function
// DEV: This function goes in 3 parts
//   1. Generate a scope chain (e.g. `FunctionDeclaration` -> `FunctionDeclaration` -> `Program`)
//   2. Resolve variable declarations to their closest scope
//        (e.g. `function hello(world) {}` maps `world` to the scope of `hello`)
//   3. Match all identifiers to their corresponding scope and save `with` related info
//   4. Add scope info to each identifier
//        (e.g. `function a() { var x; function b() { x(); } }` gives `x` the properties recorded against `a`)
function ecmaVariableScope(ast) {
  // Walk entire tree
  var scopeStack = [];
  var scope;
  estraverse.traverse(ast, {
    // Upon entry of a node
    enter: function (node, parent) {
      // Save the scope to our node
      // e.g. {`FunctionDeclaration._nearestScope === Program`}
      // e.g. {`Program._nearestScope === undefined`}
      node._nearestScope = scope;

      // If it is a a program, lexical scope, with statement, or block scope
      var scopeType = getScopeType(node);
      if (scopeType) {
        // Generate a new scope and push it onto our stack
        var oldScope = scope;
        scope = {
          type: scopeType,
          node: node, // reference to node of AST
          parent: oldScope, // reference to parent in scope tree
          identifiers: { // reference to Identifier nodes in AST under our scope
            // name: Identifier
          },
          children: [] // references to children in scope tree
        };
        scopeStack.push(scope);

        // If there was a parent scope, save a child reference
        if (scope.parent) {
          scope.parent.children.push(scope);
        }
      }
    },
    // Upon exiting a node
    leave: function (node, parent) {
      // If it is a program, lexical scope, with statement, or a block scope
      if (getScopeType(node)) {
        // Pop it from the stack
        scopeStack.pop();

        // Update the scope reference
        scope = scopeStack[scopeStack.length - 1];
      }
    }
  });

  // Walk entire tree
  estraverse.traverse(ast, {
    enter: function (node, parent) {
      // If the item is a variable declaration
      var identifiers;
      var scopeType;
      switch(node.type) {
        // Lexical/block scope
        // If it is a variable declaration (e.g. `var name;`, `let name;`)
        // DEV: This also covers `for/for in/for of` loops since they require a `let`
        case 'VariableDeclaration':
          // Find all of the identifiers via the declarators
          var declarators = node.declarations;
          // TODO: Consider using _.pluck
          identifiers = declarators.map(function getIdentifier (declarator) {
            return declarator.id;
          });
          // DEV: For reference, `const` is lexical
          //   if (true) { const hai = true; } console.log(hai);
          scopeType = node.kind === 'let' ? SCOPE_INFO_TYPES.BLOCK : SCOPE_INFO_TYPES.LEXICAL;
          resolveScope(node, identifiers, scopeType);
          break;

        // Lexical scopes
        // `function name(params) {}`
        case 'FunctionDeclaration':
        // `[].map(function name (params) {})`
        case 'FunctionExpression':
        // `[].map(name => 1);
        case 'ArrowFunctionExpression':
          // DEV: This covers both the function name and its parameters
          // Resolve the scope of the fn name separately from its params (different scopes)
          // DEV: Allow no name (e.g. `[].map(function () {})`
          if (node.id) {
            resolveScope(node, [node.id], SCOPE_INFO_TYPES.LEXICAL);
          }

          // Resolve scope for the fn parameters (will resolve to fn)
          if (node.params[0]) {
            resolveScope(node.params[0], node.params, SCOPE_INFO_TYPES.LEXICAL);
          }
          break;

        // Block scopes
        // `try { /* ... */ } catch (name) { /* ... */ }
        case 'CatchClause':
          resolveScope(node.param, [node.param], SCOPE_INFO_TYPES.BLOCK);
          break;
        // `var a = [1 for (value of ['hello'])];`
        case 'ComprehensionBlock':
          resolveScope(node.left, [node.left], SCOPE_INFO_TYPES.BLOCK);
          break;
      }
    }
  });

  // For each variable node
  walkVariables(ast, {
    enter: function (node, parent) {
      // Walk up the scope chain until we find our containing scope
      var scope = node._nearestScope;
      var insideWith = SCOPE_INFO_INSIDE_WITH.NO;
      var usedInAWith = SCOPE_INFO_USED_IN_A_WITH.NO;
      var declaringIdentifier;
      while (scope) {
        // If we are passing through a `with` and it isn't the `with's` context, save the info
        if (scope.type === SCOPE_TYPES.WITH && scope.node.object !== node) {
          insideWith = SCOPE_INFO_INSIDE_WITH.YES;
          usedInAWith = SCOPE_INFO_USED_IN_A_WITH.YES;
        }

        // If it contains our variable, stop looping
        declaringIdentifier = scope.identifiers[node.name];
        if (declaringIdentifier !== undefined) {
          break;
        }

        // Otherwise, move to the parent scope
        scope = scope.parent;
      }

      // Mark the declaringIdentifier with `usedInAWith` info
      if (declaringIdentifier) {
        declaringIdentifier._usedInAWith = usedInAWith;
      }

      // Save the scope and `insideWith` info to our variable
      node._insideWith = insideWith;
      node.scope = scope;
    }
  });

  // For each variable node
  walkVariables(ast, {
    enter: function (node, parent) {
      // Pick the scope for the node
      var scope = node.scope;

      // Define the default info
      var info = {
        insideWith: node._insideWith,
        topLevel: SCOPE_INFO_TOP_LEVEL.NO,
        type: SCOPE_INFO_TYPES.UNDECLARED,
        usedInAWith: SCOPE_INFO_USED_IN_A_WITH.NO
      };

      // If there is a scope, find its declaring identifier
      var declaringIdentifier;
      if (scope) {
        declaringIdentifier = scope.identifiers[node.name];
      }

      if (scope === undefined || scope.node.type === 'Program') {
        info.topLevel = SCOPE_INFO_TOP_LEVEL.YES;
      }

      // If we hit an identifier, save the type and used in a with info
      if (declaringIdentifier) {
        info.usedInAWith = declaringIdentifier._usedInAWith;
        info.type = declaringIdentifier._scopeType;
      }

      // Save our info to the identifier
      node.scopeInfo = info;
    }
  });

  // Return our marked up AST
  return ast;
}

// Save constants to our export
ecmaVariableScope.SCOPE_INFO_INSIDE_WITH = SCOPE_INFO_INSIDE_WITH;
ecmaVariableScope.SCOPE_INFO_USED_IN_A_WITH = SCOPE_INFO_USED_IN_A_WITH;
ecmaVariableScope.SCOPE_INFO_TOP_LEVEL = SCOPE_INFO_TOP_LEVEL;
ecmaVariableScope.SCOPE_INFO_TYPES = SCOPE_INFO_TYPES;
ecmaVariableScope.SCOPE_TYPES = SCOPE_TYPES;

// Export our funtion
module.exports = ecmaVariableScope;
<commit_msg>Started on maintaining our own parent stack<commit_after>// Load in our dependencies
var assert = require('assert');
var ecmaScopes = require('ecma-scopes');
var estraverse = require('estraverse');

// Define constants
var SCOPE_INFO_INSIDE_WITH = {
  YES: true,
  NO: false
};
var SCOPE_INFO_USED_IN_A_WITH = {
  YES: true,
  NO: false
};
var SCOPE_INFO_TOP_LEVEL = {
  YES: true,
  NO: false
};
var SCOPE_INFO_TYPES = {
  LEXICAL: 'lexical',
  BLOCK: 'block',
  UNDECLARED: 'undeclared'
};
var SCOPE_TYPES = {
  LEXICAL: 'lexical',
  WITH: 'with',
  BLOCK: 'block'
};

// Define helper to check a new scope
function getScopeType(node) {
  if (node.type === 'Program') {
    // DEV: We mark `program` as `lexical` because it is easier to set/compare against
    return SCOPE_TYPES.LEXICAL;
  } else if (ecmaScopes.lexical.indexOf(node.type) !== -1) {
    return SCOPE_TYPES.LEXICAL;
  } else if (node.type === 'WithStatement') {
    return SCOPE_TYPES.WITH;
  } else if (ecmaScopes.block.indexOf(node.type) !== -1) {
    return SCOPE_TYPES.BLOCK;
  } else {
    return null;
  }
}

// TODO: Move to an object or reduce the parameters. The count is too damn high
// DEV: We specify `baseNode` because it should be where we resolve the nearest scope from which may not be an identifier
function resolveScope(baseNode, identifiers, scopeType) {
  // If we resolved identifiers
  // DEV: This assert is to make it faster for developers to debug
  assert(Array.isArray(identifiers), 'Identifier resolution for baseNode "' + baseNode.type + '" did not result in an array');

  if (identifiers.length) {
    // Walk up the nearest scopes until we find one that matches our type
    // DEV: Use `scopeTypes` since a block scope can hit `Program` which is lexical
    var scope = baseNode._nearestScope;
    var scopeTypes = scopeType === SCOPE_INFO_TYPES.LEXICAL ? [SCOPE_INFO_TYPES.LEXICAL] : [SCOPE_INFO_TYPES.LEXICAL, SCOPE_INFO_TYPES.BLOCK];
    while (scope) {
      // If the scope type matches, stop
      if (scopeTypes.indexOf(scope.type) !== -1) {
        break;
      }

      // Look at the scope's parent
      scope = scope.parent;
    }

    // Expand all identifiers (e.g. object patterns to variables, `var {world}` -> `world`)
    var expandedIdentifiers = [];
    identifiers.forEach(function expandIdentifier (identifier) {
      // If it is an object pattern, expand it and save each key/identifier
      if (identifier.type === 'ObjectPattern') {
        identifier.properties.forEach(function extractObjectIdentifier (property) {
          expandedIdentifiers.push(property.key);
        });
      // Otherwise if it is an array pattern, expand it and save each identifier
      } else if (identifier.type === 'ArrayPattern') {
        identifier.elements.forEach(function extractArrayIdentifier (element) {
          expandedIdentifiers.push(element);
        });
      // Otherwise, save the original identifier
      } else {
        expandedIdentifiers.push(identifier);
      }
    });

    // Save declaration info on the scope and scope type to the identifier
    expandedIdentifiers.forEach(function saveIdentifier (identifier) {
      scope.identifiers[identifier.name] = identifier;
      identifier._scopeType = scopeType;
    });
  }
}

function verifyIdentifier(node, parent) {
  if (node.type === 'Identifier'
}

function walkVariables(ast, params) {
  // Walk entire tree
  var parents = [];
  estraverse.traverse(ast, {
    // Skip over undesired identifiers (e.g. `log` in `console.log`)
    // https://github.com/Constellation/estraverse/blob/1.7.0/estraverse.js#L222-L288
    keys: {
      BreakStatement: [/*'label'*/], // `loop1` in `break loop1;`
      ContinueStatement: [/*'label'*/], // `loop1` in `continue loop1;`
      LabeledStatement: [/*'label',*/ 'body'], // `loop1` in `loop1: while (true) {}`
      MemberExpression: ['object', 'property'], // `log` in `console.log`
      Property: [/*'key',*/ 'value'] // `key` in `{key: 'value'}`
    },

    enter: function (node) {
      // If the node is an identifier, run our `enter` on it
      if (node.type === 'Identifier' && params.enter) {
        // If the node's parent is a `MemberExpression`
        var parent = parents[parents.length - 1];
        if (parent && parent.type === 'MemberExpression') {
          // If the node expression is computed (e.g. `key` in `obj[key]` vs `log` in `console.log`)
          if (parent.computed === true) {
            params.enter(node);
          }
        // Otherwise, run `enter` on the node
        } else {
          params.enter(node);
        }
      }

      // Save the node as the next one's parent
      parents.push(node);
    },
    exit: function (node) {
      // Pop the node as a parent
      parents.pop();

      // DEV: Commented for code coverage
      // // If the node is an identifier, run our `exit` on it
      // if (node.type === 'Identifier' && params.exit) {
      //   params.exit(node);
      // }
    }
  });
  return ast;
}

// TODO: Consider breaking down ecmaVariableScope into 3 functions

// Define our variable scope function
// DEV: This function goes in 3 parts
//   1. Generate a scope chain (e.g. `FunctionDeclaration` -> `FunctionDeclaration` -> `Program`)
//   2. Resolve variable declarations to their closest scope
//        (e.g. `function hello(world) {}` maps `world` to the scope of `hello`)
//   3. Match all identifiers to their corresponding scope and save `with` related info
//   4. Add scope info to each identifier
//        (e.g. `function a() { var x; function b() { x(); } }` gives `x` the properties recorded against `a`)
function ecmaVariableScope(ast) {
  // Walk entire tree
  var scopeStack = [];
  var scope;
  estraverse.traverse(ast, {
    // Upon entry of a node
    enter: function (node, parent) {
      // Save the scope to our node
      // e.g. {`FunctionDeclaration._nearestScope === Program`}
      // e.g. {`Program._nearestScope === undefined`}
      node._nearestScope = scope;

      // If it is a a program, lexical scope, with statement, or block scope
      var scopeType = getScopeType(node);
      if (scopeType) {
        // Generate a new scope and push it onto our stack
        var oldScope = scope;
        scope = {
          type: scopeType,
          node: node, // reference to node of AST
          parent: oldScope, // reference to parent in scope tree
          identifiers: { // reference to Identifier nodes in AST under our scope
            // name: Identifier
          },
          children: [] // references to children in scope tree
        };
        scopeStack.push(scope);

        // If there was a parent scope, save a child reference
        if (scope.parent) {
          scope.parent.children.push(scope);
        }
      }
    },
    // Upon exiting a node
    leave: function (node, parent) {
      // If it is a program, lexical scope, with statement, or a block scope
      if (getScopeType(node)) {
        // Pop it from the stack
        scopeStack.pop();

        // Update the scope reference
        scope = scopeStack[scopeStack.length - 1];
      }
    }
  });

  // Walk entire tree
  estraverse.traverse(ast, {
    enter: function (node, parent) {
      // If the item is a variable declaration
      var identifiers;
      var scopeType;
      switch(node.type) {
        // Lexical/block scope
        // If it is a variable declaration (e.g. `var name;`, `let name;`)
        // DEV: This also covers `for/for in/for of` loops since they require a `let`
        case 'VariableDeclaration':
          // Find all of the identifiers via the declarators
          var declarators = node.declarations;
          // TODO: Consider using _.pluck
          identifiers = declarators.map(function getIdentifier (declarator) {
            return declarator.id;
          });
          // DEV: For reference, `const` is lexical
          //   if (true) { const hai = true; } console.log(hai);
          scopeType = node.kind === 'let' ? SCOPE_INFO_TYPES.BLOCK : SCOPE_INFO_TYPES.LEXICAL;
          resolveScope(node, identifiers, scopeType);
          break;

        // Lexical scopes
        // `function name(params) {}`
        case 'FunctionDeclaration':
        // `[].map(function name (params) {})`
        case 'FunctionExpression':
        // `[].map(name => 1);
        case 'ArrowFunctionExpression':
          // DEV: This covers both the function name and its parameters
          // Resolve the scope of the fn name separately from its params (different scopes)
          // DEV: Allow no name (e.g. `[].map(function () {})`
          if (node.id) {
            resolveScope(node, [node.id], SCOPE_INFO_TYPES.LEXICAL);
          }

          // Resolve scope for the fn parameters (will resolve to fn)
          if (node.params[0]) {
            resolveScope(node.params[0], node.params, SCOPE_INFO_TYPES.LEXICAL);
          }
          break;

        // Block scopes
        // `try { /* ... */ } catch (name) { /* ... */ }
        case 'CatchClause':
          resolveScope(node.param, [node.param], SCOPE_INFO_TYPES.BLOCK);
          break;
        // `var a = [1 for (value of ['hello'])];`
        case 'ComprehensionBlock':
          resolveScope(node.left, [node.left], SCOPE_INFO_TYPES.BLOCK);
          break;
      }
    }
  });

  // For each variable node
  walkVariables(ast, {
    enter: function (node, parent) {
      // Walk up the scope chain until we find our containing scope
      var scope = node._nearestScope;
      var insideWith = SCOPE_INFO_INSIDE_WITH.NO;
      var usedInAWith = SCOPE_INFO_USED_IN_A_WITH.NO;
      var declaringIdentifier;
      while (scope) {
        // If we are passing through a `with` and it isn't the `with's` context, save the info
        if (scope.type === SCOPE_TYPES.WITH && scope.node.object !== node) {
          insideWith = SCOPE_INFO_INSIDE_WITH.YES;
          usedInAWith = SCOPE_INFO_USED_IN_A_WITH.YES;
        }

        // If it contains our variable, stop looping
        declaringIdentifier = scope.identifiers[node.name];
        if (declaringIdentifier !== undefined) {
          break;
        }

        // Otherwise, move to the parent scope
        scope = scope.parent;
      }

      // Mark the declaringIdentifier with `usedInAWith` info
      if (declaringIdentifier) {
        declaringIdentifier._usedInAWith = usedInAWith;
      }

      // Save the scope and `insideWith` info to our variable
      node._insideWith = insideWith;
      node.scope = scope;
    }
  });

  // For each variable node
  walkVariables(ast, {
    enter: function (node, parent) {
      // Pick the scope for the node
      var scope = node.scope;

      // Define the default info
      var info = {
        insideWith: node._insideWith,
        topLevel: SCOPE_INFO_TOP_LEVEL.NO,
        type: SCOPE_INFO_TYPES.UNDECLARED,
        usedInAWith: SCOPE_INFO_USED_IN_A_WITH.NO
      };

      // If there is a scope, find its declaring identifier
      var declaringIdentifier;
      if (scope) {
        declaringIdentifier = scope.identifiers[node.name];
      }

      if (scope === undefined || scope.node.type === 'Program') {
        info.topLevel = SCOPE_INFO_TOP_LEVEL.YES;
      }

      // If we hit an identifier, save the type and used in a with info
      if (declaringIdentifier) {
        info.usedInAWith = declaringIdentifier._usedInAWith;
        info.type = declaringIdentifier._scopeType;
      }

      // Save our info to the identifier
      node.scopeInfo = info;
    }
  });

  // Return our marked up AST
  return ast;
}

// Save constants to our export
ecmaVariableScope.SCOPE_INFO_INSIDE_WITH = SCOPE_INFO_INSIDE_WITH;
ecmaVariableScope.SCOPE_INFO_USED_IN_A_WITH = SCOPE_INFO_USED_IN_A_WITH;
ecmaVariableScope.SCOPE_INFO_TOP_LEVEL = SCOPE_INFO_TOP_LEVEL;
ecmaVariableScope.SCOPE_INFO_TYPES = SCOPE_INFO_TYPES;
ecmaVariableScope.SCOPE_TYPES = SCOPE_TYPES;

// Export our funtion
module.exports = ecmaVariableScope;
<|endoftext|>


<commit_before>function Character(descr){
    this.setup(descr);
};

Character.prototype = new Model();

Character.prototype.isDead = false;
Character.prototype.availableMoves = [[1,0],[0,1],[-1,0],[0,-1]];

Character.prototype.move = function(move,noAnimation){
    var currLoc = this.loc;
    var trans = [move[0],0,move[1],0];
    var currH = this.loc[1];
    var newH =
	    - Math.abs(move[0]+this.loc[0])
	    - Math.abs(move[1]+this.loc[2]);
    var diff = newH - currH + this.origHeight;

    trans[1] = diff;
    trans[3] = 0;
    if(!noAnimation){
	this.setRot(this.getRot(move));
	this.startAnim(trans);
    } else {
	this.translate(trans);
    }
};

Character.prototype.setRot = function(newRot){
    var diff = newRot - this.rot;
    this.rotate(diff,[0,1,0]);
    this.rot = newRot;
};

Character.prototype.getRot = function(move){
    if(move[0] === 1 )
	return -Math.PI/2;
    if(move[0] === -1 )
	return Math.PI/2;
    if(move[1] === 1 )
	return Math.PI;
    return 0;
}

Character.prototype.isLegal = function(move){
  var dNext = manhattanDist(this.loc[0]+move[0] ,this.loc[2]+move[1]);
  return dNext < pyramid.height -1;
};

Character.prototype.getLegalMoves = function(){
   var legalMoves = [];
   for(var m in this.availableMoves)
       if(this.isLegal(this.availableMoves[m]))
	   legalMoves.push(this.availableMoves[m].slice(0));
   return legalMoves;
};

Character.prototype.onAnimEnd = function(currloc,nextloc){
    //Callback on anim end
};
Character.prototype.onAnimStart = function(currloc,prevloc){
    //Callback on anim start
};

Character.prototype.update = function(du){
    if(this.animating) this.animate();
    else {
	if(this.moveQueue.length !== 0){
	    this.move(this.moveQueue.shift());
	}
    }
};

Character.prototype.addMove = function(trans){
    this.moveQueue.push(trans);
};

Character.prototype.startAnim = function(trans){
    this.currTransParts = 0;
    this.animParts = this.animSpeed || 10;
    this.currentTrans = trans;

    this.transPart = vec4.scale(trans, 2/this.animParts, vec4.create());
    if(this.transPart[1] > 0){
	this.transPart[0] = 0;
	this.transPart[2] = 0;
    } else {
	this.transPart[1] = 0;
    }

    this.animating = true;
    this.onAnimStart(vec4.round(this.loc),vec4.round(
	vec4.add(this.loc,trans,vec4.create())));
};

Character.prototype.halfAnim = function(){
    this.transPart = vec4.scale(this.currentTrans, 2/this.animParts, vec4.create());
    if(this.transPart[1] < 0){
	this.transPart[0] = 0;
	this.transPart[2] = 0;
    } else {
	this.transPart[1] = 0;
    }
};

Character.prototype.endAnim = function(){
    this.animating = false;
    this.onAnimEnd(vec4.round(this.loc),vec4.round(
	vec4.subtract(this.loc,this.currentTrans,vec4.create())));
    this.loc = this.loc.map(Math.round);
    this.currentTrans = [0,0,0,0];
    this.transPart = [0,0,0,0];
};

Character.prototype.animate = function(){
    if(this.currTransParts < this.animParts){
	this.translate(this.transPart);
	this.currTransParts +=1;
    } else {
	this.endAnim();
    }

    if(this.currTransParts === this.animParts/2){
	this.halfAnim();
    }
};
<commit_msg>reverted some errors<commit_after>function Character(descr){
    this.setup(descr);
};

Character.prototype = new Model();

Character.prototype.isDead = false;
Character.prototype.availableMoves = [[1,0],[0,1],[-1,0],[0,-1]];

Character.prototype.move = function(move,noAnimation){
    var currLoc = this.loc;
    var trans = [move[0],0,move[1],0];
    var currH = this.loc[1];
    var newH =
	    - Math.abs(move[0]+this.loc[0])
	    - Math.abs(move[1]+this.loc[2]);
    var diff = newH - currH + this.origHeight;

    trans[1] = diff;
    trans[3] = 0;
    if(!noAnimation){
	this.setRot(this.getRot(move));
	this.startAnim(trans);
    } else {
	this.translate(trans);
    }
};

Character.prototype.setRot = function(newRot){
    var diff = newRot - this.rot;
    this.rotate(diff,[0,1,0]);
    this.rot = newRot;
};

Character.prototype.getRot = function(move){
    if(move[0] === 1 )
	return -Math.PI/2;
    if(move[0] === -1 )
	return Math.PI/2;
    if(move[1] === 1 )
	return Math.PI;
    return 0;
}

Character.prototype.isLegal = function(move){
  var dNext = manhattanDist(this.loc[0]+move[0] ,this.loc[2]+move[1]);
  return dNext < pyramid.height -1;
};

Character.prototype.getLegalMoves = function(){
   var legalMoves = [];
   for(var m in this.availableMoves)
       if(this.isLegal(this.availableMoves[m]))
	   legalMoves.push(this.availableMoves[m].slice(0));
   return legalMoves;
};

Character.prototype.onAnimEnd = function(currloc,nextloc){
    //Callback on anim end
};
Character.prototype.onAnimStart = function(currloc,prevloc){
    //Callback on anim start
};

Character.prototype.update = function(du){
    if(this.animating) this.animate();
    else {
	if(this.moveQueue.length !== 0){
	    this.move(this.moveQueue.shift());
	}
    }
};

Character.prototype.addMove = function(trans){
    this.moveQueue.push(trans);
};

Character.prototype.startAnim = function(trans){
    this.currTransParts = 0;
    this.animParts = this.animSpeed || 10;
    this.currentTrans = trans;

    this.transPart = vec4.scale(trans, 2/this.animParts, vec4.create());
    if(this.transPart[1] > 0){
	this.transPart[0] = 0;
	this.transPart[2] = 0;
    } else {
	this.transPart[1] = 0;
    }

    this.animating = true;
    this.onAnimStart(vec4.round(this.loc),vec4.round(
	vec4.add(this.loc,trans,vec4.create())));
};

Character.prototype.halfAnim = function(){
    this.transPart = vec4.scale(this.currentTrans, 2/this.animParts, vec4.create());
    if(this.transPart[1] < 0){
	this.transPart[0] = 0;
	this.transPart[2] = 0;
    } else {
	this.transPart[1] = 0;
    }
};

Character.prototype.endAnim = function(){
    this.animating = false;
    this.onAnimEnd(vec4.round(this.loc),vec4.round(
	vec4.subtract(this.loc,this.currentTrans,vec4.create())));
    //Models get placed in wrong spots!
    //this.loc = this.loc.map(Math.round);
    this.currentTrans = [0,0,0,0];
    this.transPart = [0,0,0,0];
};

Character.prototype.animate = function(){
    if(this.currTransParts < this.animParts){
	this.translate(this.transPart);
	this.currTransParts +=1;
    } else {
	this.endAnim();
    }

    if(this.currTransParts === this.animParts/2){
	this.halfAnim();
    }
};
<|endoftext|>


<commit_before>
/**
 * whether we are in a circle or not
 * args :
 * px,py = point position
 * cx,cy,cr = circle position and radius
 */
$.jController.registerHelper({
	name : "inCircle",
	fn : function(args) {
		var a = Math.pow(args.px - args.cx, 2);
		var b = Math.pow(args.py - args.cy, 2);
		var c = Math.pow(args.cr, 2);
		return (a + b < c);
	},
})

/**
 * whether we are in a rect or not
 * args :
 * px,py = point position
 * rx,ry,rw, rh = rect position and size
 */
$.jController.registerHelper({
	name : "inRect",
	fn : function(args) {
		var x = args.rx <= args.px && args.px <= args.rx + args.rw;
		var y = args.ry <= args.py && args.py <= args.ry + args.rh;
		return (x && y)
	},
})

/**
 * whether we are in a path
 * args :
 * px,py = point position
 * draw = instructions to draw path [function(ctx){}]
 */
$.jController.registerHelper({
	name : "inPath",
	fn : function(args) {
		// Get context
		var ctx = $.jController.getContext();

		// Save
		ctx.save();
		ctx.beginPath();

		// Draw path
		args.draw(ctx);

		// Check in
		var result = ctx.isPointInPath(args.px, args.py);

		// Restore
		ctx.closePath();
		ctx.restore();

		return result;
	},
})
<commit_msg>removed useless helper<commit_after><|endoftext|>


<commit_before>Response(function (get, deferred) {
    get("HTTPCache.comment.get", function (ev, matched, dispatch) {
        var url = ev.message;
        HTTPCache.comment.get(url).next(function(r) {
            dispatch(r);
        });
    });

    get("HTTPCache.usertags.get", function (ev, matched, dispatch) {
        var username = ev.message;
        HTTPCache.usertags.get(username).next(function(r) {
            dispatch(r);
        });
    });

    get("HTTPCache.entry.get", function (ev, matched, dispatch) {
        var url = ev.message;
        HTTPCache.entry.get(url).next(function(r) {
            dispatch(r);
        });
    });

    get("Model.Bookmark.findByUrl", function (ev, matched, dispatch) {
        var url = ev.message;
        Model.Bookmark.findByUrl(url).next(function(r) {
            dispatch(r);
        });
    });

    get("UserManager.user", function (ev, matched, dispatch) {
        console.log(UserManager.user);
        return UserManager.user;
    });

});
<commit_msg>model.bookmarkをhashにして返す<commit_after>Response(function (get, deferred) {
    get("HTTPCache.comment.get", function (ev, matched, dispatch) {
        var url = ev.message;
        HTTPCache.comment.get(url).next(function(r) {
            dispatch(r);
        });
    });

    get("HTTPCache.usertags.get", function (ev, matched, dispatch) {
        var username = ev.message;
        HTTPCache.usertags.get(username).next(function(r) {
            dispatch(r);
        });
    });

    get("HTTPCache.entry.get", function (ev, matched, dispatch) {
        var url = ev.message;
        HTTPCache.entry.get(url).next(function(r) {
            dispatch(r);
        });
    });

    get("Model.Bookmark.findByUrl", function (ev, matched, dispatch) {
        var url = ev.message;
        Model.Bookmark.findByUrl(url).next(function(r) {
            var newData = {};
            (['comment', 'dateYMD', 'dateYMDHM']).forEach(function(key) {
                newData[key] = r[key];
            });
            dispatch(newData);
        });
    });

    get("UserManager.user", function (ev, matched, dispatch) {
        console.log(UserManager.user);
        return UserManager.user;
    });

});
<|endoftext|>