<commit_before>
/**
 * common header for map/table views
 */

var OptionsMenu = cdb.admin.DropdownMenu.extend({
  events: {
    'click .export':        '_export',
    'click .duplicate':     '_duplicate',
    'click .append':        '_append',
    'click .delete_table':  '_delete'
  },

  show: function() {
    this.render();
    this.constructor.__super__.show.apply(this);
  },

  _export: function(e){
    e.preventDefault();

    // Should check if query is applied and it is correct, if not, user can't
    // export anything...
    if (this.options.table.isInSQLView() && !this.options.dataLayer.get("query")) {
      return;
    }

    var export_dialog = new cdb.admin.ExportTableDialog({
      model: this.options.table,
      config: config,
      user_data: user_data
    });

    $("body").append(export_dialog.render().el);
    export_dialog.open();
  },

  _duplicate: function(e){
    e.preventDefault();

    // Should check if query is applied and it is correct, if not, user can't
    // duplicate a table or a query...
    if (this.options.table.isInSQLView() && !this.options.dataLayer.get("query")) {
      return;
    }

    var duplicate_dialog = new cdb.admin.DuplicateTable({
      model: this.options.table
    });

    $("body").append(duplicate_dialog.render().el);
    duplicate_dialog.open();
  },

  _append: function(e){
    e.preventDefault();
  },

  _delete: function(e){
    e.preventDefault();
    var delete_dialog = new cdb.admin.DeleteDialog({
      model: this.options.table,
      config: config,
      user_data: user_data,
      ok: function() {
        location = "/dashboard";
      }
    });

    $("body").append(delete_dialog.render().el);
    delete_dialog.open();
  }
});

cdb.admin.Header = cdb.core.View.extend({
  _TEXTS: {
    _DEFAULT_DESCRIPTION:         'add a description for this table...',
    _DEFAULT_QUERY_DESCRIPTION:   'There is no description...',
    _DEFAULT_ADD_TAG_BUTTON:      'add tags',
    _DEFAULT_EDIT_TAG_BUTTON:     'edit tags'
  },
  _PRIVACY_VALUES: [
    'public',
    'private'
  ],
  _MAX_DESCRIPTION_LENGTH: 200,
  events: {
    'click .clearview':           'clearView',
    'click .status':              '_addPrivacySelector',
    'click .change_title':        '_changeTitle',
    'click .table_description p': '_changeDescription',
    'click .georeference':        'georeference',
    'click span.tags > *':        '_changeTags'
  },

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

    this.$body = this.options.body || $('body');
    this.table = this.model;
    this.globalError = this.options.globalError;
    this.createBindings();

    this.add_related_model(this.table);
    this.$('.clearview').hide();

    // Print all the information and don't
    // wait for table changes, it renders faster
    this.setTableInfo();
    this.createUserMenu();
    this.createOptionsMenu();

    // if(this.table.isInSQLView()) {
    //   this.onSQLView();
    // }
  },

  createBindings: function() {
    _.bindAll(this, '_changeTitle', '_setDescription', '_setTags', '_setNameAndStatus');
    this.table.bind('change:dataSource', this.onSQLView, this);
    this.table.bind('privacyUpdated', this._setNameAndStatus);
    this.bind('descriptionChanged', this._setDescription);
    this.bind('tagsChanged', this._setTags);
    this.table.bind('change:name', this._setNameAndStatus);
  },

  createUserMenu: function() {
    // User menu
    var user_menu = this.user_menu = new cdb.admin.DropdownMenu({
      target: $('a.account'),
      username: this.options.user.get('username'),
      host: this.options.config.account_host,
      template_base: 'common/views/settings_item'
    }).bind("onDropdownShown",function(ev) {
      cdb.god.unbind("closeDialogs", user_menu.hide, user_menu);
      cdb.god.trigger("closeDialogs");
      cdb.god.bind("closeDialogs", user_menu.hide, user_menu);
    });

    cdb.god.bind("closeDialogs", user_menu.hide, user_menu);
    this.$body.append(user_menu.render().el);
    this.addView(user_menu);
  },

  createOptionsMenu: function() {
    // Options menu
    var options_menu = this.options_menu = new OptionsMenu({
      target: $('a.options'),
      model: { username: this.options.user.get('username') },
      username: this.options.user.get('username'),
      table: this.table,
      template_base: 'table/views/header_table_options'
    }).bind("onDropdownShown",function(ev) {
      cdb.god.unbind("closeDialogs", options_menu.hide, options_menu);
      cdb.god.trigger("closeDialogs");
      cdb.god.bind("closeDialogs", options_menu.hide, options_menu);
    });
    cdb.god.bind("closeDialogs", options_menu.hide, options_menu);
    this.addView(options_menu);
  },

  setOptionsMenu: function(dl) {
    this.options_menu.options.dataLayer = dl;
    $('body').append(this.options_menu.render().el);
  },

  setDataLayer: function(dl) {
    this.dataLayer = dl;
    // Set the new datalayer to the options menu
    // due to the fact that we need for duplicating
    // dialog, export dialog, and so on...
    this.setOptionsMenu(dl);
  },

  georeference: function(e) {
    e.preventDefault();
    var dlg = new cdb.admin.GeoreferenceDialog({
      model: this.table,
      geocoder: this.options.geocoder
    });
    dlg.appendToBody().open();
  },

  setTableInfo: function() {
    this._setNameAndStatus();
    this._setDescription();
    this._setTags();
  },

  /**
   *  Set Name and status of the table
   */
  _setNameAndStatus: function() {

    this.$('h2.special a').html(this.table.get('name'));

    var $status = this.$('.status');

    for(var n in this._PRIVACY_VALUES) {
      var privacyName = this._PRIVACY_VALUES[n]
      $status.removeClass(privacyName);
    }

    $status
      .addClass(this.table.get('privacy').toLowerCase())
      .html(this.table.get('privacy'));
  },

  /**
   *  Set table description in the header
   */
  _setDescription: function() {
    var default_description = this._TEXTS._DEFAULT_DESCRIPTION;

    if(this.table.sqlView) {
      default_description = "" + this._TEXTS._DEFAULT_QUERY_DESCRIPTION + "";
    }

    this.$('.table_description p').html(this.table.get('description') || default_description);
  },

  /**
   *  Set table tags in the header
   */
  _setTags: function() {
    var tag_button_text = this._TEXTS._DEFAULT_ADD_TAG_BUTTON;
    if (this.table.get('tags')) {
      tag_button_text = this._TEXTS._DEFAULT_EDIT_TAG_BUTTON;
    }
    if (this.table.sqlView) {
      tag_button_text = '';
    }
    if (this.table.get('tags')) {
      var tags = this.table.get('tags').split(",")
        , html = '
';

      _.each(tags, function(tag,i) {
        html += "" + tag + "";
      });

      this.$('span.tags').html(html + "
");
      this.$('span.tags').append(""+tag_button_text+"");
    } else {
      this.$('span.tags').html(""+tag_button_text+"");
    }
  },

  onSQLView: function() {
    this.setTableInfo();
    if(this.table.isInSQLView()) {
      this.$('.clearview').show();
      this.$el.addClass('query');
      this.$('.status').hide();
      this.$('.georeference').parent().hide();
    } else {
      this.$('.clearview').hide();
      this.$el.removeClass('query');
      this.$('.status').show();
      this.$('.georeference').parent().show();
    }
  },

  clearView: function(e) {
    e.preventDefault();
    this.dataLayer && this.dataLayer.save({ query: undefined });
    $.faviconNotify('/favicons/cartofante_blue.png');
    return false;
  },

  _addPrivacySelector: function(ev) {
    ev.preventDefault();

    this.privacy && this.privacy.clean();
    cdb.god.trigger("closeDialogs");
        // Add privacy selector
    var privacy = this.privacy = new cdb.admin.PrivacySelector({
      model: this.table,
      limitation: !this.options.user.get("private_tables"),
      direction: 'down',
      upgrade_url: 'https://' + config.account_host + "/account/" + user_data.username + "/upgrade"
    });

    cdb.god.bind("closeDialogs", this.privacy.hide, this.privacy);

    this.$el.parent().append(this.privacy.render().el);

    this.privacy.show($(ev.target),"offset");

    return false;
  },

  _changeDescription: function(e) {
    var self = this;
    this.killEvent(e);
    if(!this.table.sqlView) {
      this.description_dialog && this.description_dialog.clean();
      cdb.god.trigger("closeDialogs");

      var description_dialog = this.description_dialog = new cdb.admin.EditTextDialog({
        initial_value: this.table.get('description') || '',
        template_name: 'table/views/edit_name',
        clean_on_hide: true,
        maxLength: self._MAX_DESCRIPTION_LENGTH,
        modal_class: 'edit_name_dialog',
        res: function(val) {
          // safety check
          val = val.substr(0, self._MAX_DESCRIPTION_LENGTH);
          if (val !== self.model.get('description')) {
            // Show a loader, and when saves the new description
            // Take into account we don't trigger save event to
            // avoid change the whole application
            self.globalError.showError('Saving ... ', 'load');
            $.when(self.model.save({ description:val }, { silent:true })).done(function() {
              self.trigger('descriptionChanged');
              self.globalError.showError('Saved', 'info', 3000);
            }).fail(function() {
              self.globalError.showError('Something has failed', 'error', 5000);
            });
          }
        }
      });

      cdb.god.bind("closeDialogs", description_dialog.hide, description_dialog);

      var pos = $(e.target).offset();
      pos.left -= $(window).scrollLeft();
      pos.top -= $(window).scrollTop();
      var w = Math.max($(e.target).width() + 100, 280);

      description_dialog.showAt(pos.left - 20, pos.top - 13, w);
    }
  },

  _changeTitle: function(e) {
    var self = this;
    this.killEvent(e);
    if(!this.table.sqlView) {
      this.title_dialog && this.title_dialog.clean();
      cdb.god.trigger("closeDialogs");
      var previousName = this.table.get('name');
      var title_dialog = this.title_dialog = new cdb.admin.EditTextDialog({
        initial_value: previousName,
        template_name: 'table/views/edit_name',
        clean_on_hide: true,
        modal_class: 'edit_name_dialog',
        res: function(val) {
          if(val !== self.model.get('name') && val != '') {
            var confirmation = new cdb.admin.RenameConfirmationDialog({
              model: self.table,
              globalError: self.globalError,
              newName: val
            });

            confirmation.appendToBody().open();
            var promise = confirmation.confirm();
            $.when(promise).done(self._renameTable.bind(self));
          }
        }
      });

      cdb.god.bind("closeDialogs", title_dialog.hide, title_dialog);

      // when the table has horizontal scroll for some reason
      // object offset returned has the scroll added
      var pos = $(e.target).offset();
      pos.left -= $(window).scrollLeft()
      pos.top -= $(window).scrollTop()
      var w = Math.max($(e.target).width() + 100, 280);
      title_dialog.showAt(pos.left - 20, pos.top - 6, w);
    }
  },

  _renameTable: function(newName) {
    var self = this;
    self.globalError.showError('Renaming your table ... ', 'load');
    $.when(self.model.save({ name: newName }, {wait: true})).done(function() {
      self.globalError.showError('Saved', 'info', 3000);
    });
  },

  _changeTags: function(e) {
    var self = this;
    e.preventDefault();
    e.stopPropagation();
    if(!this.table.sqlView) {
      this.tags_dialog && this.tags_dialog.clean();
      cdb.god.trigger("closeDialogs");

      var tags_dialog = this.tags_dialog = new cdb.admin.TagsDialog({
        initial_value: this.table.get('tags'),
        template_name: 'table/views/edit_name',
        clean_on_hide: false,
        modal_class: 'edit_name_dialog',
        res: function(val) {
          if (val !== self.model.get('tags')) {
            // Show a loader, and when saves new tags
            // Take into account we don't trigger save event to
            // avoid change the whole application (same as description)
            self.model.notice('Saving ... ', 'load');
            $.when(self.model.save({ tags:val }, { silent:true })).done(function() {
              self.trigger('tagsChanged');
              self.model.notice('Saved', 'info', 3000);
            }).fail(function() {
              self.model.notice('Something has failed', 'error', 5000);
            });
          }
        }
      });

      cdb.god.bind("closeDialogs", tags_dialog.hide, tags_dialog);

      // when the table has horizontal scroll for some reason
      // object offset returned has the scroll added
      var $tags = $(e.target).closest("span.tags")
      var pos = $tags.offset();
      pos.left -= $(window).scrollLeft();
      pos.top -= $(window).scrollTop() + 6;

      var w = Math.max($tags.find("p").width() + 100, 280);
      tags_dialog.showAt(pos.left - 20, pos.top - 8);
    }
  }
});
<commit_msg>no max time of renaming your table warning<commit_after>
/**
 * common header for map/table views
 */

var OptionsMenu = cdb.admin.DropdownMenu.extend({
  events: {
    'click .export':        '_export',
    'click .duplicate':     '_duplicate',
    'click .append':        '_append',
    'click .delete_table':  '_delete'
  },

  show: function() {
    this.render();
    this.constructor.__super__.show.apply(this);
  },

  _export: function(e){
    e.preventDefault();

    // Should check if query is applied and it is correct, if not, user can't
    // export anything...
    if (this.options.table.isInSQLView() && !this.options.dataLayer.get("query")) {
      return;
    }

    var export_dialog = new cdb.admin.ExportTableDialog({
      model: this.options.table,
      config: config,
      user_data: user_data
    });

    $("body").append(export_dialog.render().el);
    export_dialog.open();
  },

  _duplicate: function(e){
    e.preventDefault();

    // Should check if query is applied and it is correct, if not, user can't
    // duplicate a table or a query...
    if (this.options.table.isInSQLView() && !this.options.dataLayer.get("query")) {
      return;
    }

    var duplicate_dialog = new cdb.admin.DuplicateTable({
      model: this.options.table
    });

    $("body").append(duplicate_dialog.render().el);
    duplicate_dialog.open();
  },

  _append: function(e){
    e.preventDefault();
  },

  _delete: function(e){
    e.preventDefault();
    var delete_dialog = new cdb.admin.DeleteDialog({
      model: this.options.table,
      config: config,
      user_data: user_data,
      ok: function() {
        location = "/dashboard";
      }
    });

    $("body").append(delete_dialog.render().el);
    delete_dialog.open();
  }
});

cdb.admin.Header = cdb.core.View.extend({
  _TEXTS: {
    _DEFAULT_DESCRIPTION:         'add a description for this table...',
    _DEFAULT_QUERY_DESCRIPTION:   'There is no description...',
    _DEFAULT_ADD_TAG_BUTTON:      'add tags',
    _DEFAULT_EDIT_TAG_BUTTON:     'edit tags'
  },
  _PRIVACY_VALUES: [
    'public',
    'private'
  ],
  _MAX_DESCRIPTION_LENGTH: 200,
  events: {
    'click .clearview':           'clearView',
    'click .status':              '_addPrivacySelector',
    'click .change_title':        '_changeTitle',
    'click .table_description p': '_changeDescription',
    'click .georeference':        'georeference',
    'click span.tags > *':        '_changeTags'
  },

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

    this.$body = this.options.body || $('body');
    this.table = this.model;
    this.globalError = this.options.globalError;
    this.createBindings();

    this.add_related_model(this.table);
    this.$('.clearview').hide();

    // Print all the information and don't
    // wait for table changes, it renders faster
    this.setTableInfo();
    this.createUserMenu();
    this.createOptionsMenu();

    // if(this.table.isInSQLView()) {
    //   this.onSQLView();
    // }
  },

  createBindings: function() {
    _.bindAll(this, '_changeTitle', '_setDescription', '_setTags', '_setNameAndStatus');
    this.table.bind('change:dataSource', this.onSQLView, this);
    this.table.bind('privacyUpdated', this._setNameAndStatus);
    this.bind('descriptionChanged', this._setDescription);
    this.bind('tagsChanged', this._setTags);
    this.table.bind('change:name', this._setNameAndStatus);
  },

  createUserMenu: function() {
    // User menu
    var user_menu = this.user_menu = new cdb.admin.DropdownMenu({
      target: $('a.account'),
      username: this.options.user.get('username'),
      host: this.options.config.account_host,
      template_base: 'common/views/settings_item'
    }).bind("onDropdownShown",function(ev) {
      cdb.god.unbind("closeDialogs", user_menu.hide, user_menu);
      cdb.god.trigger("closeDialogs");
      cdb.god.bind("closeDialogs", user_menu.hide, user_menu);
    });

    cdb.god.bind("closeDialogs", user_menu.hide, user_menu);
    this.$body.append(user_menu.render().el);
    this.addView(user_menu);
  },

  createOptionsMenu: function() {
    // Options menu
    var options_menu = this.options_menu = new OptionsMenu({
      target: $('a.options'),
      model: { username: this.options.user.get('username') },
      username: this.options.user.get('username'),
      table: this.table,
      template_base: 'table/views/header_table_options'
    }).bind("onDropdownShown",function(ev) {
      cdb.god.unbind("closeDialogs", options_menu.hide, options_menu);
      cdb.god.trigger("closeDialogs");
      cdb.god.bind("closeDialogs", options_menu.hide, options_menu);
    });
    cdb.god.bind("closeDialogs", options_menu.hide, options_menu);
    this.addView(options_menu);
  },

  setOptionsMenu: function(dl) {
    this.options_menu.options.dataLayer = dl;
    $('body').append(this.options_menu.render().el);
  },

  setDataLayer: function(dl) {
    this.dataLayer = dl;
    // Set the new datalayer to the options menu
    // due to the fact that we need for duplicating
    // dialog, export dialog, and so on...
    this.setOptionsMenu(dl);
  },

  georeference: function(e) {
    e.preventDefault();
    var dlg = new cdb.admin.GeoreferenceDialog({
      model: this.table,
      geocoder: this.options.geocoder
    });
    dlg.appendToBody().open();
  },

  setTableInfo: function() {
    this._setNameAndStatus();
    this._setDescription();
    this._setTags();
  },

  /**
   *  Set Name and status of the table
   */
  _setNameAndStatus: function() {

    this.$('h2.special a').html(this.table.get('name'));

    var $status = this.$('.status');

    for(var n in this._PRIVACY_VALUES) {
      var privacyName = this._PRIVACY_VALUES[n]
      $status.removeClass(privacyName);
    }

    $status
      .addClass(this.table.get('privacy').toLowerCase())
      .html(this.table.get('privacy'));
  },

  /**
   *  Set table description in the header
   */
  _setDescription: function() {
    var default_description = this._TEXTS._DEFAULT_DESCRIPTION;

    if(this.table.sqlView) {
      default_description = "" + this._TEXTS._DEFAULT_QUERY_DESCRIPTION + "";
    }

    this.$('.table_description p').html(this.table.get('description') || default_description);
  },

  /**
   *  Set table tags in the header
   */
  _setTags: function() {
    var tag_button_text = this._TEXTS._DEFAULT_ADD_TAG_BUTTON;
    if (this.table.get('tags')) {
      tag_button_text = this._TEXTS._DEFAULT_EDIT_TAG_BUTTON;
    }
    if (this.table.sqlView) {
      tag_button_text = '';
    }
    if (this.table.get('tags')) {
      var tags = this.table.get('tags').split(",")
        , html = '
';

      _.each(tags, function(tag,i) {
        html += "" + tag + "";
      });

      this.$('span.tags').html(html + "
");
      this.$('span.tags').append(""+tag_button_text+"");
    } else {
      this.$('span.tags').html(""+tag_button_text+"");
    }
  },

  onSQLView: function() {
    this.setTableInfo();
    if(this.table.isInSQLView()) {
      this.$('.clearview').show();
      this.$el.addClass('query');
      this.$('.status').hide();
      this.$('.georeference').parent().hide();
    } else {
      this.$('.clearview').hide();
      this.$el.removeClass('query');
      this.$('.status').show();
      this.$('.georeference').parent().show();
    }
  },

  clearView: function(e) {
    e.preventDefault();
    this.dataLayer && this.dataLayer.save({ query: undefined });
    $.faviconNotify('/favicons/cartofante_blue.png');
    return false;
  },

  _addPrivacySelector: function(ev) {
    ev.preventDefault();

    this.privacy && this.privacy.clean();
    cdb.god.trigger("closeDialogs");
        // Add privacy selector
    var privacy = this.privacy = new cdb.admin.PrivacySelector({
      model: this.table,
      limitation: !this.options.user.get("private_tables"),
      direction: 'down',
      upgrade_url: 'https://' + config.account_host + "/account/" + user_data.username + "/upgrade"
    });

    cdb.god.bind("closeDialogs", this.privacy.hide, this.privacy);

    this.$el.parent().append(this.privacy.render().el);

    this.privacy.show($(ev.target),"offset");

    return false;
  },

  _changeDescription: function(e) {
    var self = this;
    this.killEvent(e);
    if(!this.table.sqlView) {
      this.description_dialog && this.description_dialog.clean();
      cdb.god.trigger("closeDialogs");

      var description_dialog = this.description_dialog = new cdb.admin.EditTextDialog({
        initial_value: this.table.get('description') || '',
        template_name: 'table/views/edit_name',
        clean_on_hide: true,
        maxLength: self._MAX_DESCRIPTION_LENGTH,
        modal_class: 'edit_name_dialog',
        res: function(val) {
          // safety check
          val = val.substr(0, self._MAX_DESCRIPTION_LENGTH);
          if (val !== self.model.get('description')) {
            // Show a loader, and when saves the new description
            // Take into account we don't trigger save event to
            // avoid change the whole application
            self.globalError.showError('Saving ... ', 'load');
            $.when(self.model.save({ description:val }, { silent:true })).done(function() {
              self.trigger('descriptionChanged');
              self.globalError.showError('Saved', 'info', 3000);
            }).fail(function() {
              self.globalError.showError('Something has failed', 'error', 5000);
            });
          }
        }
      });

      cdb.god.bind("closeDialogs", description_dialog.hide, description_dialog);

      var pos = $(e.target).offset();
      pos.left -= $(window).scrollLeft();
      pos.top -= $(window).scrollTop();
      var w = Math.max($(e.target).width() + 100, 280);

      description_dialog.showAt(pos.left - 20, pos.top - 13, w);
    }
  },

  _changeTitle: function(e) {
    var self = this;
    this.killEvent(e);
    if(!this.table.sqlView) {
      this.title_dialog && this.title_dialog.clean();
      cdb.god.trigger("closeDialogs");
      var previousName = this.table.get('name');
      var title_dialog = this.title_dialog = new cdb.admin.EditTextDialog({
        initial_value: previousName,
        template_name: 'table/views/edit_name',
        clean_on_hide: true,
        modal_class: 'edit_name_dialog',
        res: function(val) {
          if(val !== self.model.get('name') && val != '') {
            var confirmation = new cdb.admin.RenameConfirmationDialog({
              model: self.table,
              globalError: self.globalError,
              newName: val
            });

            confirmation.appendToBody().open();
            var promise = confirmation.confirm();
            $.when(promise).done(self._renameTable.bind(self));
          }
        }
      });

      cdb.god.bind("closeDialogs", title_dialog.hide, title_dialog);

      // when the table has horizontal scroll for some reason
      // object offset returned has the scroll added
      var pos = $(e.target).offset();
      pos.left -= $(window).scrollLeft()
      pos.top -= $(window).scrollTop()
      var w = Math.max($(e.target).width() + 100, 280);
      title_dialog.showAt(pos.left - 20, pos.top - 6, w);
    }
  },

  _renameTable: function(newName) {
    var self = this;
    self.globalError.showError('Renaming your table ... ', 'load', -1);
    $.when(self.model.save({ name: newName }, {wait: true})).done(function() {
      self.globalError.showError('Saved', 'info', 3000);
    });
  },

  _changeTags: function(e) {
    var self = this;
    e.preventDefault();
    e.stopPropagation();
    if(!this.table.sqlView) {
      this.tags_dialog && this.tags_dialog.clean();
      cdb.god.trigger("closeDialogs");

      var tags_dialog = this.tags_dialog = new cdb.admin.TagsDialog({
        initial_value: this.table.get('tags'),
        template_name: 'table/views/edit_name',
        clean_on_hide: false,
        modal_class: 'edit_name_dialog',
        res: function(val) {
          if (val !== self.model.get('tags')) {
            // Show a loader, and when saves new tags
            // Take into account we don't trigger save event to
            // avoid change the whole application (same as description)
            self.model.notice('Saving ... ', 'load');
            $.when(self.model.save({ tags:val }, { silent:true })).done(function() {
              self.trigger('tagsChanged');
              self.model.notice('Saved', 'info', 3000);
            }).fail(function() {
              self.model.notice('Something has failed', 'error', 5000);
            });
          }
        }
      });

      cdb.god.bind("closeDialogs", tags_dialog.hide, tags_dialog);

      // when the table has horizontal scroll for some reason
      // object offset returned has the scroll added
      var $tags = $(e.target).closest("span.tags")
      var pos = $tags.offset();
      pos.left -= $(window).scrollLeft();
      pos.top -= $(window).scrollTop() + 6;

      var w = Math.max($tags.find("p").width() + 100, 280);
      tags_dialog.showAt(pos.left - 20, pos.top - 8);
    }
  }
});
<|endoftext|>


<commit_before>////////////////////////////////////////////////
//SUBMIT ROAD RAGE
////////////////////////////////////////////////
function submitRage(){
	$(document).ready(function(){

		$("#raterage").click(function(e) {

		  e.preventDefault();
		  var name = $("#name").val();
		  var score = $("input[type='radio'][name='score']:checked").val();
		  var city = $("#city").val();
		  var dataString = 'score='+score+'&city='+city+'&ref=mobile';
		  $.ajax({
			type:'POST',
			crossDomain: true,
			data:dataString,
			url:'http://www.monkeymeter.com/submit-app.php',
			success:function(data) {
			alert(data);
			  $( "#recent" ).trigger( "click" );
			}
		  });
		return false;

		});
	});
}

////////////////////////////////////////////////
//SHOW PAGE CONTENT/MENU
////////////////////////////////////////////////
function showPageContent(){
		$("#recentragers").css("display", "none");
		$("#forecastpage").css("display", "none");
		$("#newspage").css("display", "none");
		$("#topragerspage").css("display", "none");
		$("#recentusragerspage").css("display", "none");
		$(document).ready(function(){

				$("#rate").click(function(){
				$(".pages").css("display", "none");
				$("#rateyourroadrage").css("display", "inline-block");
			});

				$("#recent").click(function(){
				$(".pages").css("display", "none");
				$("#recentragers").css("display", "inline-block");
			});

				$("#forecast").click(function(){
				$(".pages").css("display", "none");
				$("#forecastpage").css("display", "inline-block");
			});

				$("#topragers").click(function(){
				$(".pages").css("display", "none");
				$("#topragerspage").css("display", "inline-block");
			});

				$("#news").click(function(){
				$(".pages").css("display", "none");
				$("#newspage").css("display", "inline-block");
			});

				$("#recentusragers").click(function(){
				$(".pages").css("display", "none");
				$("#recentusragerspage").css("display", "inline-block");
			});
		});
}

////////////////////////////////////////////////
//SHOW RECENT RAGERS FOR LOCATION
//AND GET TOTAL POINTS FOR CITY FORECAST
////////////////////////////////////////////////

var cityScore = 0;
var recentcityScore = 0;

function getScores(){
	var recentHTML = "

";
	var abc = Math.random();

	var totalPoints = 0;
	var recentPoints = 0; //first 10% of all entries, to compare with total ave, to see trend
	var tpCount = 0;

	$.ajax({
		url: "http://www.monkeymeter.com/json/scores.json?refresh=" + abc,
		//force to handle it as text
		dataType: "text",
		success: function(data) {

			//data downloaded so call parseJSON function
			//and pass downloaded data
			var json = $.parseJSON(data);

			//get recent data for the city the user is in
			var x = json.scores.length;
			var percX = x/15; //percentage of recent scores to grab
			var city = $("#city").val();

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

				if (city == json.scores[i].city){
					var gw = 20*json.scores[i].score; //graph
		            var z = json.scores[i].score * 1;
					totalPoints = totalPoints + z;
					tpCount = tpCount + 1;

					if (tpCount < percX){
						recentPoints = recentPoints + z;
					}

					if (tpCount < 50){  //limiting to 25 to show on screen.
						recentHTML =  recentHTML + "
"+json.scores[i].when+"	"+json.scores[i].score+"
";
					}
				}

			}
			recentHTML = recentHTML + "

";

			recentcityScore = recentPoints/percX;
			recentcityScore = recentcityScore.toFixed(2);
			cityScore = totalPoints/tpCount;
			$('#recentscores').html(recentHTML+"

");

		}
	});

}

////////////////////////////////////////////////
//SHOW FORECAST FOR CITY
////////////////////////////////////////////////

function getForecast(){
var fcScore = [];
fcScore[0] = cityScore;
var forecastHTML = "";
var ratings = [];
var fontcolor =[];
var ratingpic= [];

//gettings days of week
var d = new Date();
var weekday = new Array(7);
weekday[0]=  ["Sun", .02];
weekday[1] = ["Mon", .03];
weekday[2] = ["Tue", .03];
weekday[3] = ["Wed", .04];
weekday[4] = ["Thu", .04];
weekday[5] = ["Fri", .05];
weekday[6] = ["Sat", .04];

var n=weekday[d.getDay()];
var dayNum = d.getDay();
if (dayNum < 3){
	var day3 = weekday[dayNum+2][0];
	var day4 = weekday[dayNum+3][0];
	var day5 = weekday[dayNum+4][0];
	fcScore[1]=fcScore[0] + weekday[dayNum+1][1];
	fcScore[2]=fcScore[0] + weekday[dayNum+2][1];
	fcScore[3]=fcScore[0] + weekday[dayNum+3][1];
	fcScore[4]=fcScore[0] + weekday[dayNum+4][1];
}

if (dayNum ==3 ){
	var day3 = weekday[5][0];
	var day4 = weekday[6][0];
	var day5 = weekday[0][0];
	fcScore[1]=fcScore[0] + weekday[4][1];
	fcScore[2]=fcScore[0] + weekday[5][1];
	fcScore[3]=fcScore[0] + weekday[6][1] ;
	fcScore[4]=fcScore[0] + weekday[0][1];

}

if (dayNum ==4 ){
	var day3 = weekday[6][0];
	var day4 = weekday[0][0];
	var day5 = weekday[1][0];
	fcScore[1]=fcScore[0] + weekday[5][1];
	fcScore[2]=fcScore[0] + weekday[6][1];
	fcScore[3]=fcScore[0] + weekday[0][1] ;
	fcScore[4]=fcScore[0] + weekday[1][1];

}
if (dayNum ==5 ){
	var day3 = weekday[0][0];
	var day4 = weekday[1][0];
	var day5 = weekday[2][0];
	fcScore[1]=fcScore[0] + weekday[6][1];
	fcScore[2]=fcScore[0] + weekday[0][1];
	fcScore[3]=fcScore[0] + weekday[1][1];
	fcScore[4]=fcScore[0] + weekday[2][1];
}
if (dayNum ==6 ){
	var day3 = weekday[1][0];
	var day4 = weekday[2][0];
	var day5 = weekday[3][0];
	fcScore[1]=fcScore[0] + weekday[0][1];
	fcScore[2]=fcScore[0] + weekday[1][1];
	fcScore[3]=fcScore[0] + weekday[2][1];
	fcScore[4]=fcScore[0] + weekday[3][1];
}

//get rating level
for (var i = 0; i < 5; i++){
	if (fcScore[i] > 0)
		{
		ratings[i]="None";
		fontcolor[i] = "blue";
		ratingpic[i]="img/monkey-ok.png";
		}
	if (fcScore[i]  > 1)
		{
		ratings[i]="Low";
		fontcolor[i] = "green";
		ratingpic[i]="img/monkey-ok.png";
		}
	if (fcScore[i]  > 2)
		{
		ratings[i]="Ave";
		fontcolor[i] = "black";
		ratingpic[i]="img/monkey-ave.png";
		}
	if (fcScore[i] > 3)
		{
		ratings[i]="High";
		fontcolor[i] = "orange";
		ratingpic[i]="img/monkey-high.png";
		}
	if (fcScore[i]  > 4)
		{
		ratings[i]="Dangerous";
		fontcolor[i] = "red";
		ratingpic[i]="img/monkey-dan.png";
		}
}

//show trend
var arrow="";
var altarrow = "";
if (cityScore <= recentcityScore){
	arrow = "up.jpg";
	altarrow = "road rage has been increasing";
	fcScore[0] = fcScore[0] + .04;
	}
else {
	arrow = "down.jpg";
	altarrow = "road rage has been decreasing";
	fcScore[0] = fcScore[0] - .03;
	}

forecastHTML = "
Current rating in your area is: " + cityScore.toFixed(2) + ", and the recent trend is that "+altarrow+".

";

forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
Today
";
		forecastHTML = forecastHTML + "

"  + ratings[0] + "
" +  fcScore[0].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
Tomorrow
";
		forecastHTML = forecastHTML + "

"  + ratings[1] + "
" +  fcScore[1].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day3 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[2] + "
" +  fcScore[2].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day4 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[3] + "
" +  fcScore[3].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day5 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[4] + "
" +  fcScore[3].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

forecastHTML = forecastHTML + "
";

$('#forecastforcity').html(forecastHTML);
}

////////////////////////////////////////////////
//SHOW RECENT RAGERS THROUGHOUT US
////////////////////////////////////////////////

function getUSratings(){
	var recentHTML = "

";
	var abc = Math.random();

	$.ajax({
		url: "http://www.monkeymeter.com/json/scores.json?refresh=" + abc,
		//force to handle it as text
		dataType: "text",
		success: function(data) {

			//data downloaded so call parseJSON function
			//and pass downloaded data
			var json = $.parseJSON(data);

			//get recent data for the city the user is in
			var x = json.scores.length;

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

					var gw = 8*json.scores[i].score; //graph
		            var z = json.scores[i].score * 1;
					//show only year
					json.scores[i].when = json.scores[i].when.slice(0,10);

						recentHTML =  recentHTML + "
"+json.scores[i].city+"	"+json.scores[i].when+"	"+json.scores[i].score+"
";

			}
			recentHTML = recentHTML + "

";
			$('#recentusratings').html(recentHTML+"

");

		}
	});

}<commit_msg>Added files via upload<commit_after>////////////////////////////////////////////////
//SUBMIT ROAD RAGE
////////////////////////////////////////////////
function submitRage(){
	$(document).ready(function(){

		$("#raterage").click(function(e) {

		  e.preventDefault();
		  var name = $("#name").val();
		  var score = $("input[type='radio'][name='score']:checked").val();
		  var city = $("#city").val();
		  var dataString = 'score='+score+'&city='+city+'&ref=mobile';
		  $.ajax({
			type:'POST',
			crossDomain: true,
			data:dataString,
			url:'http://www.monkeymeter.com/submit-app.php',
			success:function(data) {
			alert(data);
			  $( "#recent" ).trigger( "click" );
			}
		  });
		return false;

		});
	});
}

////////////////////////////////////////////////
//SHOW PAGE CONTENT/MENU
////////////////////////////////////////////////
function showPageContent(){
		$("#recentragers").css("display", "none");
		$("#forecastpage").css("display", "none");
		$("#newspage").css("display", "none");
		$("#topragerspage").css("display", "none");
		$("#recentusragerspage").css("display", "none");
		$(document).ready(function(){

				$("#rate").click(function(){
				$(".pages").css("display", "none");
				$("#rateyourroadrage").css("display", "inline-block");
			});

				$("#recent").click(function(){
				$(".pages").css("display", "none");
				$("#recentragers").css("display", "inline-block");
			});

				$("#forecast").click(function(){
				$(".pages").css("display", "none");
				$("#forecastpage").css("display", "inline-block");
			});

				$("#topragers").click(function(){
				$(".pages").css("display", "none");
				$("#topragerspage").css("display", "inline-block");
			});

				$("#news").click(function(){
				$(".pages").css("display", "none");
				$("#newspage").css("display", "inline-block");
			});

				$("#recentusragers").click(function(){
				$(".pages").css("display", "none");
				$("#recentusragerspage").css("display", "inline-block");
			});
		});
}

////////////////////////////////////////////////
//SHOW RECENT RAGERS FOR LOCATION
//AND GET TOTAL POINTS FOR CITY FORECAST
////////////////////////////////////////////////

var cityScore = 0;
var recentcityScore = 0;

function getScores(){
	var recentHTML = "

";
	var abc = Math.random();

	var totalPoints = 0;
	var recentPoints = 0; //first 10% of all entries, to compare with total ave, to see trend
	var tpCount = 0;

	$.ajax({
		url: "http://www.monkeymeter.com/json/scores.json?refresh=" + abc,
		//force to handle it as text
		dataType: "text",
		success: function(data) {

			//data downloaded so call parseJSON function
			//and pass downloaded data
			var json = $.parseJSON(data);

			//get recent data for the city the user is in
			var x = json.scores.length;
			var percX = x/15; //percentage of recent scores to grab
			var city = $("#city").val();

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

				if (city == json.scores[i].city){
					var gw = 20*json.scores[i].score; //graph
		            var z = json.scores[i].score * 1;
					totalPoints = totalPoints + z;
					tpCount = tpCount + 1;

					if (tpCount < percX){
						recentPoints = recentPoints + z;
					}

					if (tpCount < 50){  //limiting to 25 to show on screen.
						recentHTML =  recentHTML + "
"+json.scores[i].when+"	"+json.scores[i].score+"
";
					}
				}

			}
			recentHTML = recentHTML + "

";

			recentcityScore = recentPoints/percX;
			recentcityScore = recentcityScore.toFixed(2);
			cityScore = totalPoints/tpCount;
			$('#recentscores').html(recentHTML+"

");

		}
	});

}

////////////////////////////////////////////////
//SHOW FORECAST FOR CITY
////////////////////////////////////////////////

function getForecast(){
var fcScore = [];
fcScore[0] = cityScore;
var forecastHTML = "";
var ratings = [];
var fontcolor =[];
var ratingpic= [];

//gettings days of week
var d = new Date();
var weekday = new Array(7);
weekday[0]=  ["Sun", .02];
weekday[1] = ["Mon", .03];
weekday[2] = ["Tue", .03];
weekday[3] = ["Wed", .04];
weekday[4] = ["Thu", .04];
weekday[5] = ["Fri", .05];
weekday[6] = ["Sat", .04];

var n=weekday[d.getDay()];
var dayNum = d.getDay();
if (dayNum < 3){
	var day3 = weekday[dayNum+2][0];
	var day4 = weekday[dayNum+3][0];
	var day5 = weekday[dayNum+4][0];
	fcScore[1]=fcScore[0] + weekday[dayNum+1][1];
	fcScore[2]=fcScore[0] + weekday[dayNum+2][1];
	fcScore[3]=fcScore[0] + weekday[dayNum+3][1];
	fcScore[4]=fcScore[0] + weekday[dayNum+4][1];
}

if (dayNum ==3 ){
	var day3 = weekday[5][0];
	var day4 = weekday[6][0];
	var day5 = weekday[0][0];
	fcScore[1]=fcScore[0] + weekday[4][1];
	fcScore[2]=fcScore[0] + weekday[5][1];
	fcScore[3]=fcScore[0] + weekday[6][1] ;
	fcScore[4]=fcScore[0] + weekday[0][1];

}

if (dayNum ==4 ){
	var day3 = weekday[6][0];
	var day4 = weekday[0][0];
	var day5 = weekday[1][0];
	fcScore[1]=fcScore[0] + weekday[5][1];
	fcScore[2]=fcScore[0] + weekday[6][1];
	fcScore[3]=fcScore[0] + weekday[0][1] ;
	fcScore[4]=fcScore[0] + weekday[1][1];

}
if (dayNum ==5 ){
	var day3 = weekday[0][0];
	var day4 = weekday[1][0];
	var day5 = weekday[2][0];
	fcScore[1]=fcScore[0] + weekday[6][1];
	fcScore[2]=fcScore[0] + weekday[0][1];
	fcScore[3]=fcScore[0] + weekday[1][1];
	fcScore[4]=fcScore[0] + weekday[2][1];
}
if (dayNum ==6 ){
	var day3 = weekday[1][0];
	var day4 = weekday[2][0];
	var day5 = weekday[3][0];
	fcScore[1]=fcScore[0] + weekday[0][1];
	fcScore[2]=fcScore[0] + weekday[1][1];
	fcScore[3]=fcScore[0] + weekday[2][1];
	fcScore[4]=fcScore[0] + weekday[3][1];
}

//get rating level
for (var i = 0; i < 5; i++){
	if (fcScore[i] > 0)
		{
		ratings[i]="None";
		fontcolor[i] = "blue";
		ratingpic[i]="img/monkey-ok.png";
		}
	if (fcScore[i]  > 1)
		{
		ratings[i]="Low";
		fontcolor[i] = "green";
		ratingpic[i]="img/monkey-ok.png";
		}
	if (fcScore[i]  > 2)
		{
		ratings[i]="Ave";
		fontcolor[i] = "black";
		ratingpic[i]="img/monkey-ave.png";
		}
	if (fcScore[i] > 3)
		{
		ratings[i]="High";
		fontcolor[i] = "orange";
		ratingpic[i]="img/monkey-high.png";
		}
	if (fcScore[i]  > 4)
		{
		ratings[i]="Dangerous";
		fontcolor[i] = "red";
		ratingpic[i]="img/monkey-dan.png";
		}
}

//show trend
var arrow="";
var altarrow = "";
if (cityScore <= recentcityScore){
	arrow = "up.jpg";
	altarrow = "road rage has been increasing";
	fcScore[0] = fcScore[0] + .04;
	}
else {
	arrow = "down.jpg";
	altarrow = "road rage has been decreasing";
	fcScore[0] = fcScore[0] - .03;
	}

forecastHTML = "
Current rating in your area is: " + cityScore.toFixed(2) + ", and the recent trend is that "+altarrow+".

";

forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
Today
";
		forecastHTML = forecastHTML + "

"  + ratings[0] + "
" +  fcScore[0].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
Tomorrow
";
		forecastHTML = forecastHTML + "

"  + ratings[1] + "
" +  fcScore[1].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day3 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[2] + "
" +  fcScore[2].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day4 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[3] + "
" +  fcScore[3].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day5 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[4] + "
" +  fcScore[3].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

forecastHTML = forecastHTML + "
";

$('#forecastforcity').html(forecastHTML);
}

////////////////////////////////////////////////
//SHOW RECENT RAGERS THROUGHOUT US
////////////////////////////////////////////////

function getUSratings(){
	var recentHTML = "

";
	var abc = Math.random();

	$.ajax({
		url: "http://www.monkeymeter.com/json/scores.json?refresh=" + abc,
		//force to handle it as text
		dataType: "text",
		success: function(data) {

			//data downloaded so call parseJSON function
			//and pass downloaded data
			var json = $.parseJSON(data);

			//get recent data for the city the user is in
			var x = json.scores.length;

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

					var gw = 8*json.scores[i].score; //graph
		            var z = json.scores[i].score * 1;
					//show only year
					json.scores[i].when = json.scores[i].when.slice(0,10);

						recentHTML =  recentHTML + "
"+json.scores[i].city+"	"+json.scores[i].when+"	"+json.scores[i].score+"
";

			}
			recentHTML = recentHTML + "

";
			$('#recentusratings').html(recentHTML+"

");

		}
	});

}<|endoftext|>


<commit_before>/*
 * color_generator.js
 * @flow
 */
import * as THREE from "three";
import type { Vector3 } from "oxalis/constants";

const GOLDEN_RATIO = 0.618033988749895;

const ColorGenerator = {
  distinctColorForId(id: number): Vector3 {
    let hue = id * GOLDEN_RATIO;
    hue %= 1;
    const color = new THREE.Color();
    color.setHSL(hue, 1, 0.5);
    return color.toArray();
  },
};

export default ColorGenerator;
<commit_msg>use stored colour palette instead of generating good colors (#1771)<commit_after>/*
 * color_generator.js
 * @flow
 */
import type { Vector3 } from "oxalis/constants";
import _ from "lodash";

const rawRgbs =
  [105, 212, 8, 173, 36, 13, 20, 102, 125, 217, 133, 18, 122, 168, 250, 92, 176, 153, 242, 117, 181, 0, 255, 193, 184, 15, 209, 0, 0, 123, 149, 211, 79, 246, 158, 220, 211, 18, 255, 123, 26, 106, 246, 18, 97, 255, 193, 132, 35, 35, 9, 141, 167, 123, 246, 132, 9, 132, 114, 0, 114, 246, 255, 158, 193, 255, 114, 97, 123, 158, 0, 0, 0, 79, 255, 0, 70, 149, 211, 255, 0, 185, 79, 211, 62, 0, 26, 237, 255, 176, 255, 123, 97, 70, 255, 123, 18, 167, 97, 211, 167, 167, 211, 79, 132, 106, 0, 193, 44, 97, 70, 0, 149, 246, 9, 62, 79, 167, 88, 9, 114, 97, 62, 9, 149, 0, 158, 106, 185, 255, 255, 114, 167, 246, 202, 149, 176, 185, 176, 176, 9, 44, 0, 79, 0, 202, 255, 79, 35, 0, 0, 185, 167, 158, 0, 53, 79, 123, 176, 26, 70, 193, 88, 211, 0, 114, 149, 53, 229, 167, 53, 246, 141, 149, 106, 18, 141, 229, 97, 193, 237, 211, 255, 158, 255, 158, 255, 79, 246, 149, 97, 255, 193, 185, 97, 237, 44, 53, 176, 106, 132, 70, 44, 88, 185, 132, 88, 141, 9, 255, 70, 79, 0, 220, 211, 176, 229, 149, 255, 0, 0, 9, 97, 62, 62, 237, 0, 132, 176, 0, 149, 106, 0, 0, 185, 167, 255, 167, 149, 193, 132, 44, 79, 114, 123, 114, 220, 70, 0, 9, 53, 0, 149, 202, 123, 0, 18, 211, 185, 237, 255, 88, 62, 149, 70, 132, 70, 176, 255, 79, 70, 202, 88, 229, 88, 106, 237, 141, 70, 123, 79, 18, 97, 114, 202, 0, 255, 237, 79, 149, 132, 185, 0, 202, 255, 220, 114, 18, 35, 185, 167, 0, 106, 158, 114, 106, 26, 185, 202, 0, 44, 35, 149, 141, 79, 176, 211, 9, 185, 70, 53, 0, 114, 255, 255, 246, 0, 97, 167, 202, 88, 211, 158, 114, 70, 193, 141, 202, 185, 18, 53, 97, 132, 255, 0, 70, 106, 123, 0, 35, 132, 70, 0, 62, 176, 79, 149, 193, 79, 255, 211, 255, 141, 9, 26, 88, 62, 70, 62, 97, 88, 149, 246, 167, 141, 246, 123, 255, 229, 255, 220, 255, 176, 202, 123, 70, 114, 185, 123, 255, 97, 158, 0, 255, 176, 0, 44, 18, 9, 88, 255, 79, 211, 202, 211, 176, 123, 18, 132, 53, 9, 44, 132, 35, 106, 18, 35, 114, 62, 255, 44, 35, 53, 70, 176, 246, 53, 229, 141, 255, 229, 158, 246, 132, 176, 97, 114, 62, 149, 62, 158, 193, 211, 88, 176, 158, 132, 211, 114, 97, 141, 246, 114, 202, 158, 79, 0, 211, 62, 185, 123, 176, 255, 97, 176, 202, 35, 62, 132, 149, 220, 35, 0, 35, 158, 141, 149, 70, 106, 0, 202, 18, 97, 0, 97, 97, 0, 132, 97, 79, 62, 9, 97, 176, 79, 255, 26, 255, 0, 88, 132, 0, 97, 202, 211, 97, 44, 211, 35, 149, 141, 44, 193, 185, 220, 167, 88, 35, 106, 229, 220, 44, 255, 202, 185, 132, 141, 0, 255, 88, 141, 237, 185, 255, 211, 176, 0, 132, 211, 255, 114, 255, 211, 79, 9, 158, 79, 88, 237, 97, 176, 132, 141, 106, 211, 193, 211, 246, 62, 70, 35, 220, 70, 202, 176, 255, 246, 220, 255, 88, 158, 18, 229, 193, 88, 106, 202, 176, 123, 123, 141, 167, 18, 114, 193, 255, 97, 62, 202, 114, 0, 114, 70, 44, 123, 193, 0, 193, 220, 211, 176, 149, 18, 97, 44, 70, 211, 123, 202, 255, 79, 97, 79, 141, 255, 158, 18, 79, 70, 70, 88, 97, 229, 211, 246, 246, 141, 167, 97, 53, 0, 141, 193, 255, 0, 211, 141, 79, 88, 185, 106, 211, 211, 158, 193, 0, 97, 44, 255, 211, 229, 149, 18, 26, 106, 211, 123, 53, 9, 114, 123, 211, 220, 0, 26, 44, 220, 0, 9, 158, 123, 53, 114, 106, 35, 202, 132, 123, 158, 9, 167, 255, 106, 0, 255, 141, 237, 193, 255, 185, 193, 211, 132, 229, 141, 97, 62, 44, 167, 97, 167, 176, 158, 176, 158, 132, 132, 97, 255, 123, 53, 88, 88, 193, 79, 193, 44, 141, 176, 0, 193, 185, 246, 255, 220, 79, 114, 97, 97, 114, 44, 26, 70, 9, 0, 132, 70, 141, 106, 62, 211, 132, 158, 255, 97, 0, 106, 158, 53, 0, 123, 246, 176, 53, 88, 35, 0, 167, 123, 141, 106, 158, 185, 141, 246, 88, 132, 97, 35, 9, 62, 158, 185, 88, 202, 62, 35, 176, 141, 211, 211, 193, 70, 123, 123, 176, 88, 132, 132, 106, 9, 70, 167, 62, 114, 70, 53, 35, 88, 35, 255, 0, 158, 62, 0, 62, 35, 0, 220, 246, 211, 0, 193, 255, 176, 97, 18, 158, 158, 0, 220, 185, 70, 88, 123, 246, 246, 193, 229, 97, 255, 211, 141, 158, 53, 88, 149, 141, 167, 97, 149, 176, 211, 26, 35, 35, 255, 176, 176, 132, 0, 132, 88, 106, 79, 176, 255, 18, 9, 35, 0, 53, 53, 123, 255, 193, 237, 106, 167, 97, 255, 26, 79, 114, 123, 26, 158, 149, 53, 255, 229, 220, 141, 211, 158, 0, 220, 0, 149, 53, 70, 62, 26, 44, 0, 132, 62, 185, 255, 114, 220, 237, 35, 0, 114, 149, 0, 0, 88, 246, 202, 158, 202, 106, 158, 255, 132, 202, 185, 176, 202, 0, 255, 149, 202, 70, 149, 158, 35, 132, 185, 97, 246, 255, 70, 26, 237, 149, 35, 141, 62, 237, 193, 123, 53, 114, 158, 211, 141, 97, 0, 114, 255, 149, 158, 53, 53, 97, 9, 220, 132, 246, 79, 44, 62, 255, 132, 106, 237, 193, 53, 88, 149, 220, 114, 149, 132, 220, 79, 132, 0, 193, 79, 185, 123, 176, 255, 114, 53, 53, 185, 193, 141, 229, 193, 114, 149, 79, 193, 255, 123, 123, 211, 158, 132, 220, 255, 255, 0, 220, 158, 26, 193, 106, 9, 0, 176, 123, 0, 53, 0, 62, 158, 9, 114, 97, 35, 35, 70, 158, 176, 53, 255, 0, 44, 88, 62, 88, 255, 26, 123, 255, 88, 211, 229, 88, 79, 0, 211, 211, 193, 0, 26, 176, 229, 70, 62, 97, 88, 167, 106, 79, 158, 123, 149, 193, 237, 149, 123, 176, 62, 70, 44, 220, 229, 62, 255, 246, 114, 141, 220, 18, 176, 211, 97, 0, 255, 53, 167, 18, 70, 70, 185, 237, 211, 114, 53, 149, 211, 114, 141, 0, 158, 193, 79, 106, 229, 97, 193, 167, 79, 70, 114, 141, 229, 9, 220, 53, 132, 35, 26, 106, 211, 158, 246, 70, 141, 211, 0, 88, 106, 149, 123, 79, 132, 114, 97, 211, 229, 79, 106, 193, 70, 255, 167, 255, 220, 158, 106, 35, 0, 18, 211, 106, 70, 149, 229, 149, 18, 18, 0, 123, 167, 158, 158, 88, 141, 141, 97, 114, 255, 149, 132, 70, 53, 62, 79, 132, 158, 9, 0, 149, 44, 62, 0, 141, 18, 88, 53, 106, 35, 202, 185, 176, 106, 79, 246, 149, 255, 229, 79, 35, 35, 9, 0, 70, 53, 35, 0, 97, 88, 70, 0, 246, 255, 0, 220, 106, 220, 114, 220, 114, 229, 255, 97, 35, 88, 132, 70, 35, 193, 35, 0, 114, 97, 185, 167, 79, 106, 185, 106, 114, 88, 62, 123, 79, 44, 149, 88, 97, 97, 202, 88, 88, 97, 79, 0, 35, 53, 79, 79, 193, 229, 237, 229, 255, 220, 141, 185, 149, 149, 141, 255, 193, 53, 211, 9, 79, 132, 26, 0, 132, 220, 62, 35, 62, 202, 149, 202, 229, 53, 149, 97, 185, 62, 220, 44, 158, 132, 132, 53, 106, 176, 0, 255, 97, 18, 53, 88, 229, 97, 220, 211, 149, 220, 149, 62, 211, 123, 246, 88, 88, 35, 229, 220, 132, 18, 0, 26, 132, 114, 185, 158, 70, 44, 44, 79, 0, 185, 220, 114, 141, 97, 53, 185, 237, 35, 149, 193, 158, 0, 53, 114, 176, 132, 141, 106, 141, 70, 220, 0, 220, 141, 44, 167, 246, 193, 97, 255, 246, 220, 255, 88, 79, 255, 255, 79, 220, 185, 211, 106, 53, 0, 176, 79, 35, 79, 132, 44, 53, 123, 220, 176, 132, 106, 0, 185, 53, 220, 185, 158, 202, 167, 220, 9, 0, 229, 237, 229, 106, 149, 18, 202, 106, 114, 149, 158, 149, 255, 88, 185, 114, 123, 149, 123, 35, 53, 35, 70, 88, 167, 255, 132, 79, 44, 44, 97, 44, 176, 229, 53, 114, 70, 132, 9, 35, 88, 176, 167, 53, 79, 88, 114, 0, 158, 149, 53, 255, 97, 123, 193, 114, 149, 9, 123, 88, 158, 237, 193, 70, 229, 255, 123, 193, 53, 158, 79, 35, 123, 255, 229, 185, 0, 185, 0, 0, 123, 123, 123, 88, 79, 211, 149, 211, 51, 102, 153, 128, 153, 179];

const rgbs: Array<Vector3> = _.chunk(rawRgbs, 3).map(rgb =>
  // $FlowFixMe Flow has troubles with understanding that chunk yields arrays of size 3
  rgb.map(el => el / 255),
);

const ColorGenerator = {
  distinctColorForId(id: number): Vector3 {
    return rgbs[id % rgbs.length];
  },
};

export default ColorGenerator;
<|endoftext|>


<commit_before>'use strict';

function Floating2DText(w, text, type, scene, syntax_checks) {
    this.__init__(w, text, type, scene, syntax_checks);
}

const TEMP_SMUDGE_FACTOR = 0.75;

Floating2DText.prototype = {

    material: null,
    dynamic_texture: null,

    current_background_color: null,

    tool_tip_text: null,

    _update_text: function() {
        if (this.text !== ICON_LEFT && this.text !== ICON_RIGHT && this.text !== ICON_CROSS) {
            if (this.type === TYPE_BUTTON || this.type === TYPE_CHECK_BOX || this.type === TYPE_TITLE || this.type === TYPE_TITLE_CONSTANT || this.type === TYPE_SUPER_TITLE_CONSTANT || this.type === TYPE_SUPER_TITLE) {
                if (this.current_background_color !== COLOR_TRANSPARENT) {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, this.texture_width / 2 - this.get_text_length() / 2, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                } else {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, this.texture_width / 2 - this.get_text_length() / 2, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                }
            } else {
                if (this.current_background_color !== COLOR_TRANSPARENT) {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, 0, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                } else {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, 0, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                }
            }
            this.dynamic_texture.needsUpdate = true;
        }
    },

    // NOTE : Values are different for testing purposes.

    _update_color: function() {
        if (this.text !== ICON_LEFT && this.text !== ICON_RIGHT && this.text !== ICON_CROSS) {
            if (this.type === TYPE_BUTTON || this.type === TYPE_CHECK_BOX || this.type === TYPE_TITLE || this.type === TYPE_TITLE_CONSTANT || this.type === TYPE_SUPER_TITLE_CONSTANT || this.type === TYPE_SUPER_TITLE) {
                if (this.current_background_color !== COLOR_TRANSPARENT) {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, this.texture_width / 2 - this.get_text_length() / 2, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                } else {
                    this.dynamic_texture.clear().drawText(this.text, this.texture_width / 2 - this.get_text_length() / 2, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                }
            } else {
                if (this.current_background_color !== COLOR_TRANSPARENT) {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, 0, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                } else {
                    this.dynamic_texture.clear().drawText(this.text, 0, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                }
            }
            this.dynamic_texture.needsUpdate = true;
        }
    },

    _update_width: function(width) {
        this.width = width;
        this.material.dispose();
        this.geometry.dispose();
        this.mesh.dispose();
        this.object3D.remove(this.mesh);
        this.initialize(false);
    },

    set_background_color: function(color) {
        if (is_list(color)) {
            this.default_background_color = color[COLOR_STRING_INDEX];
        } else {
            this.default_background_color = color;
        }
        this._update_text(this.get_text());
    },

    initialize: function(add_to_scene) {
        this.default_background_color = COLOR_TRANSPARENT;
        this.current_background_color = COLOR_TRANSPARENT;

        if (this.type === TYPE_TITLE || this.type === TYPE_TITLE_CONSTANT) {
            this.height = 26;
        } else {
            this.height = 16;
        }

        // PlaneGeometry takes in a width, height, optionalWidthSegments (default 1), optionalHeightSegments (default 1)
        this.geometry = new THREE.PlaneGeometry(this.width, this.height);

        if (this.text === ICON_LEFT || this.text === ICON_RIGHT || this.text === ICON_CROSS) {
            this.material = new THREE.MeshBasicMaterial({
                map : MANAGER_LOADING.get_texture(TEXTURE_GROUP_ICONS, this.text)
            });
            this.material.transparent = true;
        } else {
            this.texture_width = get_nearest_power_of_two_for_number(this.width * 2);
            var texture_height = get_nearest_power_of_two_for_number(this.height * 2);
            //var font_size = Math.round(texture_height * .8);
            this.font_size = texture_height;

            //l('Font size is : ' + font_size);

            this.dynamic_texture = new THREEx.DynamicTexture(this.texture_width, texture_height);
            if (this.type === TYPE_TITLE) {
                this.dynamic_texture.context.font = 'Bold ' + str(this.font_size) + 'px Arial';
            } else {
                this.dynamic_texture.context.font = str(this.font_size) + 'px Arial';
            }

            this.dynamic_texture.texture.anisotropy = MANAGER_RENDERER.renderer.capabilities.getMaxAnisotropy();

            this.material = new THREE.MeshBasicMaterial({
                map : this.dynamic_texture.texture
            });

            this.material.transparent = true;
            this.material.side = THREE.FrontSide;

            this._update_color();
            this._update_text();
        }

        this.mesh = new THREE.Mesh(this.geometry, this.material);

        /*
        // Shader testing
        this.shader_material = new THREE.ShaderMaterial({
            uniforms: {
                'c': {type: 'f', value: 1.0},
                'p': {type: 'f', value: 6},
                glowColor: {type: 'c', value: new THREE.Color(0xffff00)},
                viewVector: {type: 'v3', value: this.object3D.position}
            },
            vertexShader: MANAGER_SHADER.VERTEX_GLOW,
            fragmentShader: MANAGER_SHADER.FRAGMENT_GLOW,
            side: THREE.BackSide,
            blending: THREE.AdditiveBlending,
            transparent: true
        });

        // TODO : Investigate if shader_material needs to be cloned or not.
        this.glow = new THREE.Mesh(this.geometry.clone(), this.shader_material.clone());
        //this.glow.position = this.mesh.position;
        this.glow.scale.multiplyScalar(1.4);
        //

        this.object3D.add(this.glow);
        */

        //
        //

        this.object3D.add(this.mesh);

        if (!is_defined(add_to_scene)) {
            if (is_defined(this.scene)) {
                this.scene.add(this.object3D);
            }
        } else {
            if (add_to_scene) {
                this.scene.add(this.object3D);
            }
        }
    },

    __init__: function(w, text, type, scene, syntax_checks) {
        this.is_2D_text = true;

        if (is_defined(syntax_checks)) {
            // Inherit from TextSyntax.
            TextSyntax.call(this, syntax_checks);
        }

        // Inherit from FloatingText.
        FloatingText.call(this, w, text, type, scene);
        // Inherit from Interactive.
        Interactive.call(this);
        // Inherit from Visibility.
        Visibility.call(this);

        this.final_initialize();
    }

};
<commit_msg>general updating 109<commit_after>'use strict';

function Floating2DText(w, text, type, scene, syntax_checks) {
    this.__init__(w, text, type, scene, syntax_checks);
}

const TEMP_SMUDGE_FACTOR = 0.75;

Floating2DText.prototype = {

    material: null,
    dynamic_texture: null,

    current_background_color: null,

    tool_tip_text: null,

    _update_text: function() {
        if (this.text !== ICON_LEFT && this.text !== ICON_RIGHT && this.text !== ICON_CROSS) {
            if (this.type === TYPE_BUTTON || this.type === TYPE_CHECK_BOX || this.type === TYPE_TITLE || this.type === TYPE_TITLE_CONSTANT || this.type === TYPE_SUPER_TITLE_CONSTANT || this.type === TYPE_SUPER_TITLE) {
                if (this.current_background_color !== COLOR_TRANSPARENT) {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, this.texture_width / 2 - this.get_text_length() / 2, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                } else {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, this.texture_width / 2 - this.get_text_length() / 2, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                }
            } else {
                if (this.current_background_color !== COLOR_TRANSPARENT) {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, 0, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                } else {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, 0, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                }
            }
            this.dynamic_texture.needsUpdate = true;
        }
    },

    // NOTE : Values are different for testing purposes.

    _update_color: function() {
        if (this.text !== ICON_LEFT && this.text !== ICON_RIGHT && this.text !== ICON_CROSS) {
            if (this.type === TYPE_BUTTON || this.type === TYPE_CHECK_BOX || this.type === TYPE_TITLE || this.type === TYPE_TITLE_CONSTANT || this.type === TYPE_SUPER_TITLE_CONSTANT || this.type === TYPE_SUPER_TITLE) {
                if (this.current_background_color !== COLOR_TRANSPARENT) {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, this.texture_width / 2 - this.get_text_length() / 2, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                } else {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, this.texture_width / 2 - this.get_text_length() / 2, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                }
            } else {
                if (this.current_background_color !== COLOR_TRANSPARENT) {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, 0, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                } else {
                    this.dynamic_texture.clear(this.current_background_color).drawText(this.text, 0, this.font_size * TEMP_SMUDGE_FACTOR, this.current_color, this.current_background_color);
                }
            }
            this.dynamic_texture.needsUpdate = true;
        }
    },

    _update_width: function(width) {
        this.width = width;
        this.material.dispose();
        this.geometry.dispose();
        this.mesh.dispose();
        this.object3D.remove(this.mesh);
        this.initialize(false);
    },

    set_background_color: function(color) {
        if (is_list(color)) {
            this.default_background_color = color[COLOR_STRING_INDEX];
        } else {
            this.default_background_color = color;
        }
        this._update_text(this.get_text());
    },

    initialize: function(add_to_scene) {
        this.default_background_color = COLOR_TRANSPARENT;
        this.current_background_color = COLOR_TRANSPARENT;

        if (this.type === TYPE_TITLE || this.type === TYPE_TITLE_CONSTANT) {
            this.height = 26;
        } else {
            this.height = 16;
        }

        // PlaneGeometry takes in a width, height, optionalWidthSegments (default 1), optionalHeightSegments (default 1)
        this.geometry = new THREE.PlaneGeometry(this.width, this.height);

        if (this.text === ICON_LEFT || this.text === ICON_RIGHT || this.text === ICON_CROSS) {
            this.material = new THREE.MeshBasicMaterial({
                map : MANAGER_LOADING.get_texture(TEXTURE_GROUP_ICONS, this.text)
            });
            this.material.transparent = true;
        } else {
            this.texture_width = get_nearest_power_of_two_for_number(this.width * 2);
            var texture_height = get_nearest_power_of_two_for_number(this.height * 2);
            //var font_size = Math.round(texture_height * .8);
            this.font_size = texture_height;

            //l('Font size is : ' + font_size);

            this.dynamic_texture = new THREEx.DynamicTexture(this.texture_width, texture_height);
            if (this.type === TYPE_TITLE) {
                this.dynamic_texture.context.font = 'Bold ' + str(this.font_size) + 'px Arial';
            } else {
                this.dynamic_texture.context.font = str(this.font_size) + 'px Arial';
            }

            this.dynamic_texture.texture.anisotropy = MANAGER_RENDERER.renderer.capabilities.getMaxAnisotropy();

            this.material = new THREE.MeshBasicMaterial({
                map : this.dynamic_texture.texture
            });

            this.material.transparent = true;
            this.material.side = THREE.FrontSide;

            this._update_color();
            this._update_text();
        }

        this.mesh = new THREE.Mesh(this.geometry, this.material);

        /*
        // Shader testing
        this.shader_material = new THREE.ShaderMaterial({
            uniforms: {
                'c': {type: 'f', value: 1.0},
                'p': {type: 'f', value: 6},
                glowColor: {type: 'c', value: new THREE.Color(0xffff00)},
                viewVector: {type: 'v3', value: this.object3D.position}
            },
            vertexShader: MANAGER_SHADER.VERTEX_GLOW,
            fragmentShader: MANAGER_SHADER.FRAGMENT_GLOW,
            side: THREE.BackSide,
            blending: THREE.AdditiveBlending,
            transparent: true
        });

        // TODO : Investigate if shader_material needs to be cloned or not.
        this.glow = new THREE.Mesh(this.geometry.clone(), this.shader_material.clone());
        //this.glow.position = this.mesh.position;
        this.glow.scale.multiplyScalar(1.4);
        //

        this.object3D.add(this.glow);
        */

        //
        //

        this.object3D.add(this.mesh);

        if (!is_defined(add_to_scene)) {
            if (is_defined(this.scene)) {
                this.scene.add(this.object3D);
            }
        } else {
            if (add_to_scene) {
                this.scene.add(this.object3D);
            }
        }
    },

    __init__: function(w, text, type, scene, syntax_checks) {
        this.is_2D_text = true;

        if (is_defined(syntax_checks)) {
            // Inherit from TextSyntax.
            TextSyntax.call(this, syntax_checks);
        }

        // Inherit from FloatingText.
        FloatingText.call(this, w, text, type, scene);
        // Inherit from Interactive.
        Interactive.call(this);
        // Inherit from Visibility.
        Visibility.call(this);

        this.final_initialize();
    }

};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Text, View, StyleSheet, Button, FlatList, ScrollView } from 'react-native'

export default class PlayerBoxCell extends Component<Props> {
  render() {
    if (this.props.player.item.personId === undefined) {
      return (
        <View style={{ flex: 1, flexDirection: 'row' }}>
          {
            this.props.player.item.map((headerCategory, idx) => {
              const viewWidth = (headerCategory === 'Player' ? 140 : 60) // extra space for player name
              return (
                <View style={[styles.boxscoreHeaderView, { width: viewWidth }]} key={idx}>
                  <Text style={styles.boxscoreText}>
                    { headerCategory }
                  </Text>
                </View>
              )
            })
          }
        </View>
      )
    } else {
      return (
        <View style= {{ flex: 1, flexDirection: 'row' }}>
          <View style={styles.boxscoreStatNameView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.display_fi_last }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.pos }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.min }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.points }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.assists }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.totReb }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.steals }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.blocks }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.plusMinus }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.fgm }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.fga }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.fgp }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.tpm }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.tpa }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.tpp }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.ftm }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.fta }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.ftp }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.turnovers }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.defReb }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.plusMinus }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.pFouls }
            </Text>
          </View>
        </View>
      )
    }
  }
}

const styles = StyleSheet.create({
  boxscoreHeaderView: {
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomColor: '#D1D1D1',
    borderBottomWidth: 1
  },
  boxscoreText: {
    textAlign: 'center',
    color: '#D3D3D3'
  },
  boxscoreStatNameView: {
    width: 140,
    padding: 10,
    justifyContent: 'center',
     alignItems: 'center'
  },
  boxscoreStatView: {
    width: 60,
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center'
  }
})
<commit_msg>fix for incorrect stat showing under several boxscore headers<commit_after>import React, { Component } from 'react'
import { Text, View, StyleSheet, Button, FlatList, ScrollView } from 'react-native'

export default class PlayerBoxCell extends Component<Props> {
  render() {
    if (this.props.player.item.personId === undefined) {
      return (
        <View style={{ flex: 1, flexDirection: 'row' }}>
          {
            this.props.player.item.map((headerCategory, idx) => {
              const viewWidth = (headerCategory === 'Player' ? 140 : 60) // extra space for player name
              return (
                <View style={[styles.boxscoreHeaderView, { width: viewWidth }]} key={idx}>
                  <Text style={styles.boxscoreText}>
                    { headerCategory }
                  </Text>
                </View>
              )
            })
          }
        </View>
      )
    } else {
      return (
        <View style= {{ flex: 1, flexDirection: 'row' }}>
          <View style={styles.boxscoreStatNameView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.display_fi_last }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.pos }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.min }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.points }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.assists }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.totReb }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.steals }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.blocks }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.plusMinus }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.fgm }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.fga }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.fgp }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.tpm }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.tpa }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.tpp }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.ftm }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.fta }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.ftp }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.offReb }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.defReb }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.turnovers }
            </Text>
          </View>
          <View style={styles.boxscoreStatView}>
            <Text style={styles.boxscoreText}>
              { this.props.player.item.pFouls }
            </Text>
          </View>
        </View>
      )
    }
  }
}

const styles = StyleSheet.create({
  boxscoreHeaderView: {
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomColor: '#D1D1D1',
    borderBottomWidth: 1
  },
  boxscoreText: {
    textAlign: 'center',
    color: '#D3D3D3'
  },
  boxscoreStatNameView: {
    width: 140,
    padding: 10,
    justifyContent: 'center',
     alignItems: 'center'
  },
  boxscoreStatView: {
    width: 60,
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center'
  }
})
<|endoftext|>


<commit_before>import Debug from 'debug';
import errors from 'feathers-errors';
import bcrypt from 'bcryptjs';
import passport from 'passport';
import { Strategy } from 'passport-local';
import { exposeConnectMiddleware } from '../middleware';
import { successfulLogin } from '../middleware';

const debug = Debug('feathers-authentication:local');
const defaults = {
  usernameField: 'email',
  passwordField: 'password',
  passReqToCallback: true,
  session: false
};

export class Service {
  constructor(options = {}) {
    this.options = options;
  }

  buildCredentials(req, username) {
    const usernameField = this.options.usernameField;
    return new Promise(function(resolve) {
      const params = {
        query: {
          [usernameField]: username
        }
      };
      resolve(params);
    });
  }

  checkCredentials(req, username, password, done) {
    this.app.service(this.options.localEndpoint).buildCredentials(req, username, password)
      // Look up the user
      .then(params => this.app.service(this.options.userEndpoint).find(params))
      .then(users => {
        // Paginated services return the array of results in the data attribute.
        let user = users[0] || users.data && users.data[0];

        // Handle bad username.
        if (!user) {
          return done(null, false);
        }

        return user;
      })
      .then(user => {
        const crypto = this.options.bcrypt || bcrypt;
        // Check password
        const hash = user[this.options.passwordField];

        if (!hash) {
          return done(new Error(`User record in the database is missing a '${this.options.passwordField}'`));
        }

        crypto.compare(password, hash, function(error, result) {
          // Handle 500 server error.
          if (error) {
            return done(error);
          }

          return done(null, result ? user : false);
        });
      })
      .catch(done);
  }

  // POST /auth/local
  create(data, params) {
    const options = this.options;
    let app = this.app;

    // Validate username and password, then generate a JWT and return it
    return new Promise(function(resolve, reject){
      let middleware = passport.authenticate('local', { session: options.session }, function(error, user) {
        if (error) {
          return reject(error);
        }

        // Login failed.
        if (!user) {
          return reject(new errors.NotAuthenticated('Invalid login.'));
        }

        // Get a new JWT and the associated user from the Auth token service and send it back to the client.
        return app.service(options.tokenEndpoint)
                  .create(user)
                  .then(resolve)
                  .catch(reject);
      });

      middleware(params.req);
    });
  }

  setup(app) {
    // attach the app object to the service context
    // so that we can call other services
    this.app = app;

    // prevent regular service events from being dispatched
    if (typeof this.filter === 'function') {
      this.filter(() => false);
    }
  }
}

export default function(options){
  options = Object.assign({}, defaults, options);
  debug('configuring local authentication service with options', options);

  return function() {
    const app = this;

    // Initialize our service with any options it requires
    app.use(options.localEndpoint, exposeConnectMiddleware, new Service(options), successfulLogin(options));

    // Get our initialize service to that we can bind hooks
    const localService = app.service(options.localEndpoint);

    // Register our local auth strategy and get it to use the passport callback function
    debug('registering passport-local strategy');
    passport.use(new Strategy(options, localService.checkCredentials.bind(localService)));
  };
}
<commit_msg>Allow multiple username fields for local auth (#283)<commit_after>import Debug from 'debug';
import errors from 'feathers-errors';
import bcrypt from 'bcryptjs';
import passport from 'passport';
import { Strategy } from 'passport-local';
import { exposeConnectMiddleware } from '../middleware';
import { successfulLogin } from '../middleware';

const debug = Debug('feathers-authentication:local');
const defaults = {
  usernameField: 'email',
  passwordField: 'password',
  passReqToCallback: true,
  session: false
};

export class Service {
  constructor(options = {}) {
    this.options = options;
  }

  buildCredentials(req) {
    const { usernameField, usernameFields } = this.options;
    return new Promise((resolve, reject) => {
      let field = usernameField;
      if (usernameFields) {
        field = usernameFields.find((f) => !!req.body[f]);
        if (!field) {
          return reject(new Error('Missing identity field.'));
        }
      }

      const params = {
        query: {
          [field]: req.body[field],
        }
      };

      resolve(params);
    });
  }

  checkCredentials(req, username, password, done) {
    this.app.service(this.options.localEndpoint).buildCredentials(req, username, password)
      // Look up the user
      .then(params => this.app.service(this.options.userEndpoint).find(params))
      .then(users => {
        // Paginated services return the array of results in the data attribute.
        const user = users[0] || users.data && users.data[0];

        // Handle bad username.
        if (!user) {
          return done(null, false);
        }

        return user;
      })
      .then(user => {
        const crypto = this.options.bcrypt || bcrypt;
        // Check password
        const hash = user[this.options.passwordField];

        if (!hash) {
          return done(new Error(`User record in the database is missing a '${this.options.passwordField}'`));
        }

        crypto.compare(password, hash, function(error, result) {
          // Handle 500 server error.
          if (error) {
            return done(error);
          }

          return done(null, result ? user : false);
        });
      })
      .catch(done);
  }

  // POST /auth/local
  create(data, params) {
    const options = this.options;
    let app = this.app;

    // Validate username and password, then generate a JWT and return it
    return new Promise(function(resolve, reject){
      let middleware = passport.authenticate('local', { session: options.session }, function(error, user) {
        if (error) {
          return reject(error);
        }

        // Login failed.
        if (!user) {
          return reject(new errors.NotAuthenticated('Invalid login.'));
        }

        // Get a new JWT and the associated user from the Auth token service and send it back to the client.
        return app.service(options.tokenEndpoint)
                  .create(user)
                  .then(resolve)
                  .catch(reject);
      });

      middleware(params.req);
    });
  }

  setup(app) {
    // attach the app object to the service context
    // so that we can call other services
    this.app = app;

    // prevent regular service events from being dispatched
    if (typeof this.filter === 'function') {
      this.filter(() => false);
    }
  }
}

export default function(options){
  options = Object.assign({}, defaults, options);
  debug('configuring local authentication service with options', options);

  return function() {
    const app = this;

    // Initialize our service with any options it requires
    app.use(options.localEndpoint, exposeConnectMiddleware, new Service(options), successfulLogin(options));

    // Get our initialize service to that we can bind hooks
    const localService = app.service(options.localEndpoint);

    // Register our local auth strategy and get it to use the passport callback function
    debug('registering passport-local strategy');
    passport.use(new Strategy(options, localService.checkCredentials.bind(localService)));
  };
}
<|endoftext|>


<commit_before>import { HttpStorageClient, VfsStorageClient, InMemoryDarBuffer } from 'substance'
import { WebAppChrome } from 'substance-texture'
import StencilaArchive from './StencilaArchive'

import {
  _renderStencilaApp,
  _setupStencilaChildContext,
  _initStencilaContext,
  _initStencilaArchive
} from './stencilaAppHelpers'

export default class StencilaWebApp extends WebAppChrome {

  render($$) {
    return _renderStencilaApp($$, this)
  }

  _setupChildContext() {
    return _setupStencilaChildContext(this.context)
  }

  _initContext(context) {
    return _initStencilaContext(context)
  }

  _getArchiveClass() {
    return StencilaArchive
  }

  _initArchive(archive, context) {
    return _initStencilaArchive(archive, context)
  }
}
<commit_msg>Fix linter.<commit_after>import { WebAppChrome } from 'substance-texture'
import StencilaArchive from './StencilaArchive'

import {
  _renderStencilaApp,
  _setupStencilaChildContext,
  _initStencilaContext,
  _initStencilaArchive
} from './stencilaAppHelpers'

export default class StencilaWebApp extends WebAppChrome {

  render($$) {
    return _renderStencilaApp($$, this)
  }

  _setupChildContext() {
    return _setupStencilaChildContext(this.context)
  }

  _initContext(context) {
    return _initStencilaContext(context)
  }

  _getArchiveClass() {
    return StencilaArchive
  }

  _initArchive(archive, context) {
    return _initStencilaArchive(archive, context)
  }
}
<|endoftext|>