<commit_before>import MetadataItem from './MetadataItem';

let DEFAULT_INTERPRETATIONS = {
  'undefined': 'categorical',
  'null': 'categorical',
  boolean: 'categorical',
  integer: 'ordinal',
  number: 'ordinal',
  date: 'categorical',
  string: 'categorical',
  object: 'categorical'
};

let ATTRIBUTE_GENERALITY = [
  'object',
  'string',
  'number',
  'integer'
];

let FILTER_STATES = {
  NO_FILTERS: 0,
  FILTERED: 1,
  EXCLUDED: 2
};

class DatasetCache {
  constructor (model) {
    this.model = model;
  }
  get cachedPromises () {
    if (!this._cachedPromises) {
      this._cachedPromises = {};
    }
    return this._cachedPromises;
  }
  set cachedPromises (value) {
    this._cachedPromises = value;
  }
  get filter () {
    if (!this._filter) {
      this._filter = {};
    }
    return this._filter;
  }
  set filter (value) {
    this._filter = value;
    // Invalidate filteredHistogram, pageHistogram, and currentDataPage
    delete this.cachedPromises.filteredHistogram;
    delete this.cachedPromises.pageHistogram;
    delete this.cachedPromises.currentDataPage;
    this.model.trigger('rl:updatePage');
  }
  get page () {
    if (!this._page) {
      this.page = {
        offset: 0,
        limit: 100
      };
    }
    return this._page;
  }
  set page (value) {
    // We have to show at least one data item
    value.limit = Math.max(1, value.limit);
    // Don't let the offset go lower than zero
    value.offset = Math.max(0, value.offset);
    // Align offset to limit-defined pages
    value.offset = value.limit * Math.floor(value.offset / value.limit);

    if (!this._page || value.offset !== this._page.offset || value.limit !== this._page.limit) {
      // Tentatively set the new page until we can
      // validate that offset doesn't exceed the
      // number of items that we have
      this._page = value;
      // Invalidate pageHistogram and currentDataPage
      delete this.cachedPromises.pageHistogram;
      delete this.cachedPromises.currentDataPage;
      this.model.trigger('rl:updatePage');

      if (this._cachedPromises && this._cachedPromises.filteredHistogram) {
        this._cachedPromises.filteredHistogram.then(filteredHistogram => {
          let maxItems = filteredHistogram.__passedFilters__[0].count;
          if (value.offset >= maxItems) {
            // Move back to the top page
            value.offset = value.limit * Math.floor(maxItems / value.limit);
            this.page = value;
          }
        });
      }
    }
  }
  get schema () {
    // Do we have the schema already in our metadata,
    // and TODO: is it current (check the file's updated flag
    // in girder, or check the last time the mongodb was modified)
    /* let meta = this.model.getMeta();
    let girderUpdate = this.model.get('updated');
    if (!meta || !meta.lastUpdated || !girderUpdate ||
      new Date(meta.lastUpdated) < new Date(girderUpdate)) {
      // With an out-of-date schema, we should trash any cached
      // histograms, and re-run schema inference
      delete meta['schema'];
      delete this.cachedPromises.schema;
    }*/

    if (!this.cachedPromises.schema) {
      let metaSchema = this.model.getMeta('schema');
      if (metaSchema) {
        // We already have up-to-date schema information in the metadata
        this.cachedPromises.schema = Promise.resolve(metaSchema);
      } else {
        // Actually hit the endpoint that does a pass to infer
        // the (potentially new) schema. This invalidates any histograms
        // or data that we have
        this.cachedPromises = {};
        this.cachedPromises.schema = this.restRequest({
          path: 'dataset/inferSchema',
          type: 'POST'
        }).then(newSchema => {
          // Inferring a new schema will update a few things;
          // we want to fetch our model as well
          return this.model.fetch().then(() => {
            this.model.trigger('rl:updatedSchema');
            return newSchema;
          });
        });
      }
    }
    return this.cachedPromises.schema;
  }
  get overviewHistogram () {
    if (!this.cachedPromises.overviewHistogram) {
      this.cachedPromises.overviewHistogram = this.schema.then(schema => {
        return this.restRequest({
          path: 'dataset/getHistograms',
          type: 'POST',
          data: {
            binSettings: JSON.stringify(this.model.getBinSettings(schema))
            // cache: true
          }
        }, 'rl:loadedHistogram');
      });
    }
    return this.cachedPromises.overviewHistogram;
  }
  get filteredHistogram () {
    if (!this.cachedPromises.filteredHistogram) {
      this.cachedPromises.filteredHistogram = this.schema.then(schema => {
        return this.restRequest({
          path: 'dataset/getHistograms',
          type: 'POST',
          data: {
            binSettings: JSON.stringify(this.model.getBinSettings(schema)),
            filter: this.filter
            // cache: true
          }
        }, 'rl:loadedHistogram');
      });
    }
    return this.cachedPromises.filteredHistogram;
  }
  get pageHistogram () {
    if (!this.cachedPromises.pageHistogram) {
      this.cachedPromises.pageHistogram = this.schema.then(schema => {
        return this.restRequest({
          path: 'dataset/getHistograms',
          type: 'POST',
          data: {
            binSettings: JSON.stringify(this.model.getBinSettings(schema)),
            filter: this.filter,
            limit: this.page.limit,
            offset: this.page.offset
            // Don't cache the page histograms on the server
          }
        }, 'rl:loadedHistogram');
      });
    }
    return this.cachedPromises.pageHistogram;
  }
  get currentDataPage () {
    if (!this.cachedPromises.currentDataPage) {
      this.cachedPromises.currentDataPage = this.schema.then(schema => {
        return this.restRequest({
          path: 'download',
          type: 'GET',
          data: {
            extraParameters: JSON.stringify({
              fileType: this.model.getMeta('format'),
              outputType: 'json',
              offset: this.page.offset,
              limit: this.page.limit
            })
          }
        }, 'rl:loadedData');
      });
    }
    return this.cachedPromises.currentDataPage;
  }
  restRequest (parameters, successEvent) {
    if (!this.model.getId()) {
      // We still haven't synced our basic info with the
      // server yet... so leave the value as null
      return null;
    } else {
      let promise = this.model.restRequest(parameters);
      if (successEvent) {
        promise.then(() => {
          this.model.trigger(successEvent);
        });
      }
      return promise;
    }
  }
}

let Dataset = MetadataItem.extend({
  initialize: function () {
    // Backbone.extend doesn't respect
    // getters and setters, so we split
    // all the cached information out into
    // its own non-Backbone cache class
    this.cache = new DatasetCache(this);
    this.dropped = false;
  },
  save: function () {
    // It's possible for a dataset to be dropped from the project
    // but someone is still hanging on to a reference to this
    // object. In this case, we want to prevent any future
    // attempts to save any changes
    if (this.dropped) {
      return Promise.resolve();
    } else {
      return MetadataItem.prototype.save.apply(this);
    }
  },
  autoDetectAttributeInterpretation: function (schema, attrName) {
    // Go with the default interpretation for the attribute type
    return DEFAULT_INTERPRETATIONS[this.getAttributeType(schema, attrName)];
  },
  getAttributeInterpretation: function (schema, attrName) {
    let attrSpec = schema[attrName];
    if (attrSpec.interpretation) {
      // The user has specified an interpretation
      return attrSpec.interpretation;
    } else {
      // auto-detect the interpretation
      return this.autoDetectAttributeInterpretation(schema, attrName);
    }
  },
  autoDetectAttributeType: function (schema, attrName) {
    let attrSpec = schema[attrName];
    // Find the most specific type that can accomodate all the values
    let attrType = 'object';
    let count = 0;
    for (let dataType of ATTRIBUTE_GENERALITY) {
      if (dataType in attrSpec && attrSpec[dataType].count >= count) {
        attrType = dataType;
        count = attrSpec[dataType].count;
      }
    }
    // TODO: if the histograms are available, use them to infer
    // whether to jump further into booleans (e.g. everything is
    // 0/1, y/n, true/false, etc) - this will require sending
    // (and storing) custom falsey strings in place of the
    // FALSEY_STRINGS list in general_purpose/binUtils.js,
    // with any dependent server-side logic
    return attrType;
  },
  getAttributeType: function (schema, attrName) {
    let attrSpec = schema[attrName];
    if (attrSpec.coerceToType) {
      // The user has specified a data type
      return attrSpec.coerceToType;
    } else {
      // auto-detect the data type
      return this.autoDetectAttributeType(schema, attrName);
    }
  },
  getBinSettings: function (schema) {
    let binSettings = {};
    // Assemble the parameters for how we want to see each attribute.
    // For now, other than attempting to auto-infer type and interpretation,
    // we rely on the default behavior
    Object.keys(schema).forEach(attrName => {
      binSettings[attrName] = {
        coerceToType: this.getAttributeType(schema, attrName),
        interpretation: this.getAttributeInterpretation(schema, attrName)
      };
    });
    return binSettings;
  },
  getTypeSpec: function () {
    let schema = this.getMeta('schema') || {};
    let result = {
      name: this.get('name'),
      attributes: {}
    };
    Object.keys(schema).forEach(attrName => {
      result.attributes[attrName] = this.getAttributeType(schema, attrName);
    });
    return result;
  },
  setAttributeType: function (attrName, dataType) {
    return this.cache.schema.then(schema => {
      if (dataType === null) {
        delete schema[attrName].coerceToType;
      } else {
        schema[attrName].coerceToType = dataType;
      }
      this.setMeta('schema', schema);
      let savePromise = this.save();
      this.cache.cachedPromises = {};
      this.trigger('rl:updatedSchema');
      return savePromise;
    });
  },
  setAttributeInterpretation: function (attrName, interpretation) {
    return this.cache.schema.then(schema => {
      if (interpretation === null) {
        delete schema[attrName].interpretation;
      } else {
        schema[attrName].interpretation = interpretation;
      }
      this.setMeta('schema', schema);
      let savePromise = this.save();
      this.cache.cachedPromises = {};
      this.trigger('rl:updatedSchema');
      return savePromise;
    });
  },
  getFilteredState: function (attrName) {
    // TODO
    return FILTER_STATES.NO_FILTERS;
  },
  setPage: function (offset, limit) {
    this.cache.page = {
      offset,
      limit
    };
  },
  setOffset: function (offset) {
    this.setPage(offset, this.cache.page.limit);
  },
  setLimit: function (limit) {
    this.setPage(this.cache.page.offset, limit);
  },
  seekNext: function () {
    this.setPage(this.cache.page.offset + this.cache.page.limit,
                 this.cache.page.limit);
  },
  seekPrev: function () {
    this.setPage(this.cache.page.offset - this.cache.page.limit,
                 this.cache.page.limit);
  },
  seekFirst: function () {
    this.setPage(0, this.cache.page.limit);
  },
  seekLast: function () {
    this.cache.filteredHistogram.then(filteredHistogram => {
      let lastItem = filteredHistogram.__passedFilters__[0].count;
      this.setPage(lastItem, this.cache.page.limit);
    });
  }
});

Dataset.DEFAULT_INTERPRETATIONS = DEFAULT_INTERPRETATIONS;
Dataset.FILTER_STATES = FILTER_STATES;
export default Dataset;
<commit_msg>Point dataset download from the client to the old select endpoint<commit_after>import MetadataItem from './MetadataItem';

let DEFAULT_INTERPRETATIONS = {
  'undefined': 'categorical',
  'null': 'categorical',
  boolean: 'categorical',
  integer: 'ordinal',
  number: 'ordinal',
  date: 'categorical',
  string: 'categorical',
  object: 'categorical'
};

let ATTRIBUTE_GENERALITY = [
  'object',
  'string',
  'number',
  'integer'
];

let FILTER_STATES = {
  NO_FILTERS: 0,
  FILTERED: 1,
  EXCLUDED: 2
};

class DatasetCache {
  constructor (model) {
    this.model = model;
  }
  get cachedPromises () {
    if (!this._cachedPromises) {
      this._cachedPromises = {};
    }
    return this._cachedPromises;
  }
  set cachedPromises (value) {
    this._cachedPromises = value;
  }
  get filter () {
    if (!this._filter) {
      this._filter = {};
    }
    return this._filter;
  }
  set filter (value) {
    this._filter = value;
    // Invalidate filteredHistogram, pageHistogram, and currentDataPage
    delete this.cachedPromises.filteredHistogram;
    delete this.cachedPromises.pageHistogram;
    delete this.cachedPromises.currentDataPage;
    this.model.trigger('rl:updatePage');
  }
  get page () {
    if (!this._page) {
      this.page = {
        offset: 0,
        limit: 100
      };
    }
    return this._page;
  }
  set page (value) {
    // We have to show at least one data item
    value.limit = Math.max(1, value.limit);
    // Don't let the offset go lower than zero
    value.offset = Math.max(0, value.offset);
    // Align offset to limit-defined pages
    value.offset = value.limit * Math.floor(value.offset / value.limit);

    if (!this._page || value.offset !== this._page.offset || value.limit !== this._page.limit) {
      // Tentatively set the new page until we can
      // validate that offset doesn't exceed the
      // number of items that we have
      this._page = value;
      // Invalidate pageHistogram and currentDataPage
      delete this.cachedPromises.pageHistogram;
      delete this.cachedPromises.currentDataPage;
      this.model.trigger('rl:updatePage');

      if (this._cachedPromises && this._cachedPromises.filteredHistogram) {
        this._cachedPromises.filteredHistogram.then(filteredHistogram => {
          let maxItems = filteredHistogram.__passedFilters__[0].count;
          if (value.offset >= maxItems) {
            // Move back to the top page
            value.offset = value.limit * Math.floor(maxItems / value.limit);
            this.page = value;
          }
        });
      }
    }
  }
  get schema () {
    // Do we have the schema already in our metadata,
    // and TODO: is it current (check the file's updated flag
    // in girder, or check the last time the mongodb was modified)
    /* let meta = this.model.getMeta();
    let girderUpdate = this.model.get('updated');
    if (!meta || !meta.lastUpdated || !girderUpdate ||
      new Date(meta.lastUpdated) < new Date(girderUpdate)) {
      // With an out-of-date schema, we should trash any cached
      // histograms, and re-run schema inference
      delete meta['schema'];
      delete this.cachedPromises.schema;
    }*/

    if (!this.cachedPromises.schema) {
      let metaSchema = this.model.getMeta('schema');
      if (metaSchema) {
        // We already have up-to-date schema information in the metadata
        this.cachedPromises.schema = Promise.resolve(metaSchema);
      } else {
        // Actually hit the endpoint that does a pass to infer
        // the (potentially new) schema. This invalidates any histograms
        // or data that we have
        this.cachedPromises = {};
        this.cachedPromises.schema = this.restRequest({
          path: 'dataset/inferSchema',
          type: 'POST'
        }).then(newSchema => {
          // Inferring a new schema will update a few things;
          // we want to fetch our model as well
          return this.model.fetch().then(() => {
            this.model.trigger('rl:updatedSchema');
            return newSchema;
          });
        });
      }
    }
    return this.cachedPromises.schema;
  }
  get overviewHistogram () {
    if (!this.cachedPromises.overviewHistogram) {
      this.cachedPromises.overviewHistogram = this.schema.then(schema => {
        return this.restRequest({
          path: 'dataset/getHistograms',
          type: 'POST',
          data: {
            binSettings: JSON.stringify(this.model.getBinSettings(schema))
            // cache: true
          }
        }, 'rl:loadedHistogram');
      });
    }
    return this.cachedPromises.overviewHistogram;
  }
  get filteredHistogram () {
    if (!this.cachedPromises.filteredHistogram) {
      this.cachedPromises.filteredHistogram = this.schema.then(schema => {
        return this.restRequest({
          path: 'dataset/getHistograms',
          type: 'POST',
          data: {
            binSettings: JSON.stringify(this.model.getBinSettings(schema)),
            filter: this.filter
            // cache: true
          }
        }, 'rl:loadedHistogram');
      });
    }
    return this.cachedPromises.filteredHistogram;
  }
  get pageHistogram () {
    if (!this.cachedPromises.pageHistogram) {
      this.cachedPromises.pageHistogram = this.schema.then(schema => {
        return this.restRequest({
          path: 'dataset/getHistograms',
          type: 'POST',
          data: {
            binSettings: JSON.stringify(this.model.getBinSettings(schema)),
            filter: this.filter,
            limit: this.page.limit,
            offset: this.page.offset
            // Don't cache the page histograms on the server
          }
        }, 'rl:loadedHistogram');
      });
    }
    return this.cachedPromises.pageHistogram;
  }
  get currentDataPage () {
    if (!this.cachedPromises.currentDataPage) {
      this.cachedPromises.currentDataPage = this.schema.then(schema => {
        if (this.model.getMeta('format') === 'mongodb.collection') {
          return this.restRequest({
            path: 'database/select',
            type: 'GET',
            data: {
              format: 'dict',
              offset: this.page.offset,
              limit: this.page.limit
            }
          }, 'rl:loadedData').then(resp => resp.data);
        } else {
          return this.restRequest({
            path: 'download',
            type: 'GET',
            data: {
              extraParameters: JSON.stringify({
                fileType: this.model.getMeta('format'),
                outputType: 'json',
                offset: this.page.offset,
                limit: this.page.limit
              })
            }
          }, 'rl:loadedData');
        }
      });
    }
    return this.cachedPromises.currentDataPage;
  }
  restRequest (parameters, successEvent) {
    if (!this.model.getId()) {
      // We still haven't synced our basic info with the
      // server yet... so leave the value as null
      return null;
    } else {
      let promise = this.model.restRequest(parameters);
      if (successEvent) {
        promise.then(() => {
          this.model.trigger(successEvent);
        });
      }
      return promise;
    }
  }
}

let Dataset = MetadataItem.extend({
  initialize: function () {
    // Backbone.extend doesn't respect
    // getters and setters, so we split
    // all the cached information out into
    // its own non-Backbone cache class
    this.cache = new DatasetCache(this);
    this.dropped = false;
  },
  save: function () {
    // It's possible for a dataset to be dropped from the project
    // but someone is still hanging on to a reference to this
    // object. In this case, we want to prevent any future
    // attempts to save any changes
    if (this.dropped) {
      return Promise.resolve();
    } else {
      return MetadataItem.prototype.save.apply(this);
    }
  },
  autoDetectAttributeInterpretation: function (schema, attrName) {
    // Go with the default interpretation for the attribute type
    return DEFAULT_INTERPRETATIONS[this.getAttributeType(schema, attrName)];
  },
  getAttributeInterpretation: function (schema, attrName) {
    let attrSpec = schema[attrName];
    if (attrSpec.interpretation) {
      // The user has specified an interpretation
      return attrSpec.interpretation;
    } else {
      // auto-detect the interpretation
      return this.autoDetectAttributeInterpretation(schema, attrName);
    }
  },
  autoDetectAttributeType: function (schema, attrName) {
    let attrSpec = schema[attrName];
    // Find the most specific type that can accomodate all the values
    let attrType = 'object';
    let count = 0;
    for (let dataType of ATTRIBUTE_GENERALITY) {
      if (dataType in attrSpec && attrSpec[dataType].count >= count) {
        attrType = dataType;
        count = attrSpec[dataType].count;
      }
    }
    // TODO: if the histograms are available, use them to infer
    // whether to jump further into booleans (e.g. everything is
    // 0/1, y/n, true/false, etc) - this will require sending
    // (and storing) custom falsey strings in place of the
    // FALSEY_STRINGS list in general_purpose/binUtils.js,
    // with any dependent server-side logic
    return attrType;
  },
  getAttributeType: function (schema, attrName) {
    let attrSpec = schema[attrName];
    if (attrSpec.coerceToType) {
      // The user has specified a data type
      return attrSpec.coerceToType;
    } else {
      // auto-detect the data type
      return this.autoDetectAttributeType(schema, attrName);
    }
  },
  getBinSettings: function (schema) {
    let binSettings = {};
    // Assemble the parameters for how we want to see each attribute.
    // For now, other than attempting to auto-infer type and interpretation,
    // we rely on the default behavior
    Object.keys(schema).forEach(attrName => {
      binSettings[attrName] = {
        coerceToType: this.getAttributeType(schema, attrName),
        interpretation: this.getAttributeInterpretation(schema, attrName)
      };
    });
    return binSettings;
  },
  getTypeSpec: function () {
    let schema = this.getMeta('schema') || {};
    let result = {
      name: this.get('name'),
      attributes: {}
    };
    Object.keys(schema).forEach(attrName => {
      result.attributes[attrName] = this.getAttributeType(schema, attrName);
    });
    return result;
  },
  setAttributeType: function (attrName, dataType) {
    return this.cache.schema.then(schema => {
      if (dataType === null) {
        delete schema[attrName].coerceToType;
      } else {
        schema[attrName].coerceToType = dataType;
      }
      this.setMeta('schema', schema);
      let savePromise = this.save();
      this.cache.cachedPromises = {};
      this.trigger('rl:updatedSchema');
      return savePromise;
    });
  },
  setAttributeInterpretation: function (attrName, interpretation) {
    return this.cache.schema.then(schema => {
      if (interpretation === null) {
        delete schema[attrName].interpretation;
      } else {
        schema[attrName].interpretation = interpretation;
      }
      this.setMeta('schema', schema);
      let savePromise = this.save();
      this.cache.cachedPromises = {};
      this.trigger('rl:updatedSchema');
      return savePromise;
    });
  },
  getFilteredState: function (attrName) {
    // TODO
    return FILTER_STATES.NO_FILTERS;
  },
  setPage: function (offset, limit) {
    this.cache.page = {
      offset,
      limit
    };
  },
  setOffset: function (offset) {
    this.setPage(offset, this.cache.page.limit);
  },
  setLimit: function (limit) {
    this.setPage(this.cache.page.offset, limit);
  },
  seekNext: function () {
    this.setPage(this.cache.page.offset + this.cache.page.limit,
                 this.cache.page.limit);
  },
  seekPrev: function () {
    this.setPage(this.cache.page.offset - this.cache.page.limit,
                 this.cache.page.limit);
  },
  seekFirst: function () {
    this.setPage(0, this.cache.page.limit);
  },
  seekLast: function () {
    this.cache.filteredHistogram.then(filteredHistogram => {
      let lastItem = filteredHistogram.__passedFilters__[0].count;
      this.setPage(lastItem, this.cache.page.limit);
    });
  }
});

Dataset.DEFAULT_INTERPRETATIONS = DEFAULT_INTERPRETATIONS;
Dataset.FILTER_STATES = FILTER_STATES;
export default Dataset;
<|endoftext|>


<commit_before>"use strict";

/**

 * Module dependencies

 */
var content_length = 500;
var link_length = 200;

module.exports = function(sequelize, DataTypes) {
  var Message = sequelize.define("Message", {
    // id autogenerated by sequelize
    content: { type: DataTypes.STRING(content_length) },
    link: { type: DataTypes.STRING(link_length) },
    sentDateTimeUTC: { type: DataTypes.DATE, allowNull: false, defaultValue: new Date() },
  }, {
      classMethods:{
        associate: function(models) {
          Message.belongsTo(models.Channel);
          Message.belongsTo(models.User);
          Message.belongsTo(models.MessageType);
        },
        contentLength: function(){
          return 500;
        }
      },
      indexes:[{
        name: 'message_channel_idx',
        method: 'BTREE',
        fields: ['ChannelId']
      }]
  });

  return Message;
};
<commit_msg>agrego relacion 'ProjectIntegration - Message'<commit_after>"use strict";

/**

 * Module dependencies

 */
var content_length = 500;
var link_length = 200;

module.exports = function(sequelize, DataTypes) {
  var Message = sequelize.define("Message", {
    // id autogenerated by sequelize
    content: { type: DataTypes.STRING(content_length) },
    link: { type: DataTypes.STRING(link_length) },
    sentDateTimeUTC: { type: DataTypes.DATE, allowNull: false, defaultValue: new Date() },
  }, {
      classMethods:{
        associate: function(models) {
          Message.belongsTo(models.Channel);
          Message.belongsTo(models.User);
          Message.belongsTo(models.MessageType);
          Message.belongsTo(models.ProjectIntegration, {constraints: false});
        },
        contentLength: function(){
          return 500;
        }
      },
      indexes:[{
        name: 'message_channel_idx',
        method: 'BTREE',
        fields: ['ChannelId']
      }]
  });

  return Message;
};
<|endoftext|>


<commit_before>const COLORS = {
  channel: {
    closed: '#4b3d67',
    public: '#17ac10',
    private: '#b60202',
  },
  state: {
    premium: '#00c5ff',
    alert: 'rgb(255, 94, 0)',
    editable: '#fdffdb',
    investor: 'rgb(183, 158, 110)',
  },
  gray: {
    bold: '#333',
    base: '#585858', // Matches `textgray`
    semiBold: '#6d6d6d',
    medium: '#999',
    regular: '#ccc',
    semiLight: '#e8e8e8',
    light: '#eee',
    hint: '#f7f7f7',
  },
  utility: {
    transparent: 'rgba(255, 255, 255, 0.001)',
  },
};

export const COLOR_NAMES = Object
  .keys(COLORS)
  .reduce(
    (memo, namespace) =>
      memo.concat(Object.keys(COLORS[namespace]).map(color =>
        `${namespace}.${color}`)),
    [],
  );

export default COLORS;
<commit_msg>Aliases public<commit_after>const COLORS = {
  channel: {
    closed: '#4b3d67',
    public: '#17ac10',
    open: '#17ac10', // alias `public`
    private: '#b60202',
  },
  state: {
    premium: '#00c5ff',
    alert: 'rgb(255, 94, 0)',
    editable: '#fdffdb',
    investor: 'rgb(183, 158, 110)',
  },
  gray: {
    bold: '#333',
    base: '#585858', // Matches `textgray`
    semiBold: '#6d6d6d',
    medium: '#999',
    regular: '#ccc',
    semiLight: '#e8e8e8',
    light: '#eee',
    hint: '#f7f7f7',
  },
  utility: {
    transparent: 'rgba(255, 255, 255, 0.001)',
  },
};

export const COLOR_NAMES = Object
  .keys(COLORS)
  .reduce(
    (memo, namespace) =>
      memo.concat(Object.keys(COLORS[namespace]).map(color =>
        `${namespace}.${color}`)),
    [],
  );

export default COLORS;
<|endoftext|>


<commit_before>function Place(name, color, price, amounts, housePrice) {
	this.name = name;
	this.color = color;
	this.price = price;
	this.amounts = amounts;
	this.housePrice = housePrice;
	this.houses = 0;
}

Place.prototype.visit = function (player) {
	if (!this.owner) {
		offerBuying.call(this, player);
	} else if (this.owner != player) {
		player.pay(this.amounts[this.houses], this.owner);
	} else if (this.houses < 5) {
		for (var i = 0, field; field = fields[i]; i++) {
			if (field instanceof Place && field.color == this.color) {
				if (field.owner != player) {
					return;
				}
			}
		}
		ask('do you want to buy a house at ' + this.name + ' for ' + this.housePrice + '?', player, function () {
			if (player.money < this.housePrice) {
				say('you do not enough money to buy a house at ' + this.name + ' for ' + this.housePrice + '.', player);
			} else {
				player.pay(this.housePrice);
				this.houses++;
				this.div.querySelector('.earns').textContent = this.getEarns();
			}
		}.bind(this));
	}
}

Place.prototype.getEarns = function () {
	return this.amounts[this.houses];
};

Place.prototype.updateEarns = function () {
};
<commit_msg>Monopoly: Fix a typo<commit_after>function Place(name, color, price, amounts, housePrice) {
	this.name = name;
	this.color = color;
	this.price = price;
	this.amounts = amounts;
	this.housePrice = housePrice;
	this.houses = 0;
}

Place.prototype.visit = function (player) {
	if (!this.owner) {
		offerBuying.call(this, player);
	} else if (this.owner != player) {
		player.pay(this.amounts[this.houses], this.owner);
	} else if (this.houses < 5) {
		for (var i = 0, field; field = fields[i]; i++) {
			if (field instanceof Place && field.color == this.color) {
				if (field.owner != player) {
					return;
				}
			}
		}
		ask('do you want to buy a house at ' + this.name + ' for ' + this.housePrice + '?', player, function () {
			if (player.money < this.housePrice) {
				say('you do not have enough money to buy a house at ' + this.name + ' for ' + this.housePrice + '.', player);
			} else {
				player.pay(this.housePrice);
				this.houses++;
				this.div.querySelector('.earns').textContent = this.getEarns();
			}
		}.bind(this));
	}
}

Place.prototype.getEarns = function () {
	return this.amounts[this.houses];
};

Place.prototype.updateEarns = function () {
};
<|endoftext|>


<commit_before>const swap = require('reaks/swap')
const isFunction = require('lodash/isFunction')
module.exports = (condition, cases) => ctx => {
  const cond = isFunction(condition) ? condition(ctx) : condition
  return swap(() => (cond() ? cases['truthy'] : cases['falsy'])(ctx))
}
<commit_msg>switchBoolean : empty by default<commit_after>const swap = require("reaks/swap")
const isFunction = require("lodash/isFunction")
const empty = require("./empty")

module.exports = (condition, cases) => ctx => {
  const cond = isFunction(condition) ? condition(ctx) : condition
  return swap(() => (cases[cond() ? "truthy" : "falsy"] || empty)(ctx))
}
<|endoftext|>


<commit_before>/* global process, __dirname */

/**
 * Configuration dependencies
 */

var cwd = process.cwd()
var path = require('path')
var settings = require('./settings')
var setup = require('./setup')
var client = require('./redis').getClient()
var logger = require('./logger')(settings.logger)
require('./mailer').getMailer()
require('./database')()
var authenticator = require('../lib/authenticator')
var express = require('express')
var cons = require('consolidate')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var session = require('express-session')
var RedisStore = require('connect-redis')(session)
var connectFlash = require('connect-flash')
var cors = require('cors')
var sessionStore = new RedisStore({ client: client })

/**
 * Read setup token if the server is in out-of-box mode
 */

setup.isOOB(function (err, oob) {
  if (err) { return console.log(err) }
  if (oob) {
    setup.readSetupToken(function (err, token) {
      if (err) { return console.log(err) }
      settings.setupToken = token
    })
  }
})

/**
 * Exports
 */

module.exports = function (server) {
  /**
   * Disable default header
   */

  server.disable('x-powered-by')

  /**
   * Views configuration
   */

  var engine = settings.view_engine || 'jade'
  server.engine(engine, cons[engine])
  server.set('view engine', engine)

  // First, look for views in the project directory.
  // If absent, look in the package views directory.
  server.set('views', [
    path.join(cwd, 'views'),
    path.join(__dirname, '..', 'views')
  ])

  /**
   * Settings
   */

  Object.keys(settings).forEach(function (key) {
    server.set(key, settings[key])
  })

  /**
   * Request Parsing
   */

  server.use(cookieParser(settings.cookie_secret))
  server.use(bodyParser.urlencoded({ extended: false }))
  server.use(bodyParser.json())

  /**
   * Express Session
   */

  if (process.env.NODE_ENV === 'production') {
    server.use(session({
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      secret: settings.session_secret,
      proxy: true,
      cookie: {
        secure: true
      }
    }))
  } else {
    server.use(session({
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      secret: settings.session_secret
    }))
  }

  /**
   * Flash messaging
   */

  server.use(connectFlash())

  /**
   * Set user on request
   */

  server.use(authenticator.setUserOnRequest)

  /**
   * Cross-Origin Support
   */

  server.use(cors())

  /**
   * Logging
   */

  server.use(logger.middleware())

  /**
   * Serve Static Files
   *
   * First, look for files in the project `public` directory.
   * If absent, look in the package `public` directory.
   */

  server.use(express.static(path.join(cwd, 'public')))
  server.use(express.static(path.join(__dirname, '..', 'public')))

  /**
   * OpenID Provider Metadata Properties
   */

  var parameters = [
    'issuer',
    'authorization_endpoint',
    'token_endpoint',
    'userinfo_endpoint',
    'jwks_uri',
    'registration_endpoint',
    'scopes_supported',
    'response_types_supported',
    'response_modes_supported',
    'grant_types_supported',
    'acr_values_supported',
    'subject_types_supported',
    'id_token_signing_alg_values_supported',
    'id_token_encryption_alg_values_supported',
    'id_token_encryption_enc_values_supported',
    'userinfo_signing_alg_values_supported',
    'userinfo_encryption_alg_values_supported',
    'userinfo_encryption_enc_values_supported',
    'request_object_signing_alg_values_supported',
    'request_object_encryption_alg_values_supported',
    'request_object_encryption_enc_values_supported',
    'token_endpoint_auth_methods_supported',
    'token_endpoint_auth_signing_alg_values_supported',
    'display_values_supported',
    'claim_types_supported',
    'claims_supported',
    'service_documentation',
    'claims_locales_supported',
    'ui_locales_supported',
    'claims_parameter_supported',
    'request_parameter_supported',
    'request_uri_parameter_supported',
    'require_request_uri_registration',
    'op_policy_uri',
    'op_tos_uri',
    'check_session_iframe',
    'end_session_endpoint'
  ]

  /**
   * Build Provider Configuration Info from Metadata
   */

  server.OpenIDConfiguration = parameters.reduce(function (config, param) {
    var value = settings[param]
    if (value) { config[param] = value }
    return config
  }, {})
}
<commit_msg>Added version check to server.js<commit_after>/* global process, __dirname */

// Ensure running a compatible version of Node before getting too far...
var semver = require('semver')
var packageJson = require('../package.json')
if (packageJson.engines &&
    packageJson.engines.node &&
    !semver.satisfies(process.versions.node, packageJson.engines.node)) {
    console.error('Incompatible version of node - running [%s] but require [%s]',
            process.versions.node, packageJson.engines.node)
    process.exit(1)
}

/**
 * Configuration dependencies
 */

var cwd = process.cwd()
var path = require('path')
var settings = require('./settings')
var setup = require('./setup')
var client = require('./redis').getClient()
var logger = require('./logger')(settings.logger)
require('./mailer').getMailer()
require('./database')()
var authenticator = require('../lib/authenticator')
var express = require('express')
var cons = require('consolidate')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var session = require('express-session')
var RedisStore = require('connect-redis')(session)
var connectFlash = require('connect-flash')
var cors = require('cors')
var sessionStore = new RedisStore({ client: client })

/**
 * Read setup token if the server is in out-of-box mode
 */

setup.isOOB(function (err, oob) {
  if (err) { return console.log(err) }
  if (oob) {
    setup.readSetupToken(function (err, token) {
      if (err) { return console.log(err) }
      settings.setupToken = token
    })
  }
})

/**
 * Exports
 */

module.exports = function (server) {
  /**
   * Disable default header
   */

  server.disable('x-powered-by')

  /**
   * Views configuration
   */

  var engine = settings.view_engine || 'jade'
  server.engine(engine, cons[engine])
  server.set('view engine', engine)

  // First, look for views in the project directory.
  // If absent, look in the package views directory.
  server.set('views', [
    path.join(cwd, 'views'),
    path.join(__dirname, '..', 'views')
  ])

  /**
   * Settings
   */

  Object.keys(settings).forEach(function (key) {
    server.set(key, settings[key])
  })

  /**
   * Request Parsing
   */

  server.use(cookieParser(settings.cookie_secret))
  server.use(bodyParser.urlencoded({ extended: false }))
  server.use(bodyParser.json())

  /**
   * Express Session
   */

  if (process.env.NODE_ENV === 'production') {
    server.use(session({
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      secret: settings.session_secret,
      proxy: true,
      cookie: {
        secure: true
      }
    }))
  } else {
    server.use(session({
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      secret: settings.session_secret
    }))
  }

  /**
   * Flash messaging
   */

  server.use(connectFlash())

  /**
   * Set user on request
   */

  server.use(authenticator.setUserOnRequest)

  /**
   * Cross-Origin Support
   */

  server.use(cors())

  /**
   * Logging
   */

  server.use(logger.middleware())

  /**
   * Serve Static Files
   *
   * First, look for files in the project `public` directory.
   * If absent, look in the package `public` directory.
   */

  server.use(express.static(path.join(cwd, 'public')))
  server.use(express.static(path.join(__dirname, '..', 'public')))

  /**
   * OpenID Provider Metadata Properties
   */

  var parameters = [
    'issuer',
    'authorization_endpoint',
    'token_endpoint',
    'userinfo_endpoint',
    'jwks_uri',
    'registration_endpoint',
    'scopes_supported',
    'response_types_supported',
    'response_modes_supported',
    'grant_types_supported',
    'acr_values_supported',
    'subject_types_supported',
    'id_token_signing_alg_values_supported',
    'id_token_encryption_alg_values_supported',
    'id_token_encryption_enc_values_supported',
    'userinfo_signing_alg_values_supported',
    'userinfo_encryption_alg_values_supported',
    'userinfo_encryption_enc_values_supported',
    'request_object_signing_alg_values_supported',
    'request_object_encryption_alg_values_supported',
    'request_object_encryption_enc_values_supported',
    'token_endpoint_auth_methods_supported',
    'token_endpoint_auth_signing_alg_values_supported',
    'display_values_supported',
    'claim_types_supported',
    'claims_supported',
    'service_documentation',
    'claims_locales_supported',
    'ui_locales_supported',
    'claims_parameter_supported',
    'request_parameter_supported',
    'request_uri_parameter_supported',
    'require_request_uri_registration',
    'op_policy_uri',
    'op_tos_uri',
    'check_session_iframe',
    'end_session_endpoint'
  ]

  /**
   * Build Provider Configuration Info from Metadata
   */

  server.OpenIDConfiguration = parameters.reduce(function (config, param) {
    var value = settings[param]
    if (value) { config[param] = value }
    return config
  }, {})
}
<|endoftext|>


<commit_before>;(function($, w, doc){

  "use strict";

  // Local object for method references
  var Nav = {};

  // Namespace
  Nav.ns = "Navigation";

  // Start defining methods here
  Nav.isScreenSize = function( sizeString ) {

    var size = window.getComputedStyle(document.body,':before').getPropertyValue('content');

    if( size && size.indexOf( sizeString ) !=-1 ) {
      return true;
    } else {
      return false;
    }

  };

  Nav.createSmallView = function(parentMenu, subMenu) {

    // don't run this code if it already ran, please
    if( parentMenu.hasClass('responsive-nav') ) {
      return;
    }

    var anchorText = parentMenu.find('a').first().text();
    var idSlug = anchorText.toLowerCase().replace(/ /g,"-");
    var randomNumber= Math.floor( Math.random()*9999 );
    var slug = idSlug + randomNumber;

    subMenu.attr('aria-expanded', 'false').attr('id', slug);
    parentMenu.addClass('is-expandable').addClass('responsive-nav');
    parentMenu.find('a').first().after('<button type="button" aria-controls="' + slug + '" class="ui-toggle-button" data-text="close">open</button>');

    parentMenu.find('.ui-toggle-button').first().on('click', function() {

      var button = $(this);
      var buttonText = button.text();
      var inverseText = button.attr('data-text');

      if( subMenu.attr('aria-expanded') === 'false' ) {
        subMenu.attr('aria-expanded', 'true');
        subMenu.focus();
      } else {
        subMenu.attr('aria-expanded', 'false');
        button.focus();
      }

      // toggle the button text
      button.attr('data-text', buttonText).text(inverseText);

    });

  }; // Nav.createSmallView

  Nav.destroySmallView = function(parentMenu, subMenu) {

    subMenu.removeAttr('aria-expanded');
    parentMenu.removeClass('is-expandable');
    parentMenu.find('.ui-toggle-button').remove();
    parentMenu.removeClass('responsive-nav');

  }; // Nav.destroySmallView

  // Menu toggle
  $('.nav-menu-toggle').on('click', function(e) {

    e.preventDefault();

    var self = $(this);
    var body = $('body');
    var targetId = self.attr('aria-controls');
    var targetZone = $('#' + targetId);

    if( body.hasClass('nav-is-active') ) {

      body.removeClass('nav-is-active');
      targetZone.attr('aria-expanded', 'false');

    } else {

      body.addClass('nav-is-active');
      targetZone.attr('aria-expanded', 'true').focus();

    }

  }); // menu toggle

  /*
    Set the stage for anything with children
  */

  $('.menu-item').each(function(){

    var self = $(this);
    var parentMenu = self;
    var menuChildren = self.children().length;
    var subMenu = self.find('ul').first();
    var subMenuAnchor;
    var parentContainer;
    var subMenu;

    // check to see if any menus have children
    if(menuChildren > 1) {

      subMenuAnchor = self.find('.menu-sub').find('a');

      // add class for children flag
      self.addClass('has-children');

      subMenu = self.find('.menu-sub');

      // focus event
      subMenuAnchor.on('focus', function() {
        $(this).closest('.menu-item.has-children').addClass('child-has-focus');
      });

      // blur event
      subMenuAnchor.on('blur', function() {

        parentContainer = $(this).closest('.menu-item.has-children');

        if( parentContainer.find('.menu-sub').find('ul > li').children(':focus').length === 0 ) {
          parentContainer.removeClass('child-has-focus');
        }

      });

      if( Nav.isScreenSize( 'mediumscreen' ) || Nav.isScreenSize( 'smallscreen' ) ) {
        Nav.createSmallView(parentMenu, subMenu);
      }

    } // if has children

  }); // each menu-item

  // Resize event to create and destory the small screen navigation
  if( $('.menu-item.has-children').length > 0 ) {
    $(window).on('resize', function() {

      if( Nav.isScreenSize( 'mediumscreen' ) || Nav.isScreenSize( 'smallscreen' ) ) {

        $(('.menu-item.has-children')).each(function(){

          var parentMenu = $(this);
          var subMenu = parentMenu.find('.menu-sub');

          Nav.createSmallView(parentMenu, subMenu);

        }); // each menu with children

      } else {

        $(('.menu-item.has-children')).each(function(){

          var parentMenu = $(this);
          var subMenu = parentMenu.find('.menu-sub');

          Nav.destroySmallView(parentMenu, subMenu);

        }); // each menu with children

      }

    }); // resize
  }// if has-children

} )( jQuery, this, this.document );<commit_msg>updated responsive navigation to work with sub menus<commit_after>;(function($, w, doc){

  "use strict";

  // Local object for method references
  var Nav = {};

  // Namespace
  Nav.ns = "Navigation";

  // Start defining methods here
  Nav.isScreenSize = function( sizeString ) {

    var size = window.getComputedStyle(document.body,':before').getPropertyValue('content');

    if( size && size.indexOf( sizeString ) !=-1 ) {
      return true;
    } else {
      return false;
    }

  };

  Nav.createSmallView = function(parentMenu, subMenu) {

    // don't run this code if it already ran, please
    if( parentMenu.hasClass('responsive-nav') ) {
      return;
    }

    var anchorText = parentMenu.find('a').first().text();
    var idSlug = anchorText.toLowerCase().replace(/ /g,"-");
    var randomNumber= Math.floor( Math.random()*9999 );
    var slug = idSlug + randomNumber;

    subMenu.attr('aria-expanded', 'false').attr('id', slug);
    parentMenu.addClass('is-expandable').addClass('responsive-nav');
    parentMenu.find('a').first().after('<button type="button" aria-controls="' + slug + '" class="ui-toggle-button" data-text="close">open</button>');

    parentMenu.find('.ui-toggle-button').first().on('click', function() {

      var button = $(this);
      var buttonText = button.text();
      var inverseText = button.attr('data-text');

      if( subMenu.attr('aria-expanded') === 'false' ) {
        subMenu.attr('aria-expanded', 'true');
        subMenu.focus();
      } else {
        subMenu.attr('aria-expanded', 'false');
        button.focus();
      }

      // toggle the button text
      button.attr('data-text', buttonText).text(inverseText);

    });

  }; // Nav.createSmallView

  Nav.destroySmallView = function(parentMenu, subMenu) {

    subMenu.removeAttr('aria-expanded');
    parentMenu.removeClass('is-expandable');
    parentMenu.find('.ui-toggle-button').remove();
    parentMenu.removeClass('responsive-nav');

  }; // Nav.destroySmallView

  // Menu toggle
  $('.nav-menu-toggle').on('click', function(e) {

    e.preventDefault();

    var self = $(this);
    var body = $('body');
    var targetId = self.attr('aria-controls');
    var targetZone = $('#' + targetId);

    if( body.hasClass('nav-is-active') ) {

      body.removeClass('nav-is-active');
      targetZone.attr('aria-expanded', 'false');

    } else {

      body.addClass('nav-is-active');
      targetZone.attr('aria-expanded', 'true').focus();

    }

  }); // menu toggle

  /*
    Set the stage for anything with children
  */

  $('.menu-item').each(function(){

    var self = $(this);
    var parentMenu = self;
    var menuChildren = self.children().length;
    var subMenu = self.find('ul').first();
    var subMenuAnchor;
    var parentContainer;
    var subMenu;

    // check to see if any menus have children
    if(menuChildren > 1) {

      subMenuAnchor = self.find('.menu-sub').find('a');

      // add class for children flag
      self.addClass('has-children');

      subMenu = self.find('.menu-sub');

      // focus event
      subMenuAnchor.on('focus', function() {
        $(this).closest('.menu-item.has-children').addClass('child-has-focus');
      });

      // blur event
      subMenuAnchor.on('blur', function() {

        parentContainer = $(this).closest('.menu-item.has-children');

        if( parentContainer.find('.menu-sub').find('ul > li').children(':focus').length === 0 ) {
          parentContainer.removeClass('child-has-focus');
        }

      });

      if( Nav.isScreenSize( 'mediumscreen' ) || Nav.isScreenSize( 'smallscreen' ) ) {
        Nav.createSmallView(parentMenu, subMenu);
      }

    } // if has children

  }); // each menu-item

  // Resize event to create and destory the small screen navigation
  if( $('.menu-item.has-children').length > 0 ) {

    $(window).on('resize', function() {

      if( Nav.isScreenSize( 'mediumscreen' ) || Nav.isScreenSize( 'smallscreen' ) ) {

        $(('.menu-item.has-children')).each(function(){

          var parentMenu = $(this);
          var subMenu = parentMenu.find('.menu-sub');

          Nav.createSmallView(parentMenu, subMenu);

        }); // each menu with children

      } else {

        $('.menu-item.has-children').each(function(){

          var parentMenu = $(this);
          var subMenu = parentMenu.find('.menu-sub');

          Nav.destroySmallView(parentMenu, subMenu);

        }); // each menu with children

      }

    }); // resize
  }// if has-children

} )( jQuery, this, this.document );<|endoftext|>


<commit_before>/**
 * Bridge proxy
 *
 */

var events = require('events');

/**
 * config options:{
 * 		port:int //only processes with root permissions can listen on privileged ports, ie: sudo node bridgeproxy.js
 * }
 */
function WSBridgeProxy(config, callback) {

	// Simple websocket server
	var me = this;
	events.EventEmitter.call(me);

	var freeServerConnections = {
		'/': []
	};
	var freeClientConnections = {
		'/': []
	};

	if (config.server) {

		me.server = (new(require('ws').Server)({
			server: config.server
		}, function() {

			console.log('bridgeproxy websocket listening on: ' + config.port);

			if ((typeof callback) == 'function') {
				callback();
			}
		}));

		if (config.server && config.port) {
			config.server.listen(config.port, callback);
		}

	} else if (config.port) {

		me.server = (new(require('ws').Server)({
			port: config.port
		}, function() {

			console.log('bridgeproxy websocket listening on: ' + config.port);

			if ((typeof callback) == 'function') {
				callback();
			}
		}));

	} else {
		throw new Error('Expected server or port, in config');
	}

	var domains = [];
	var getDomain = function(ws) {

		var domain = ws.upgradeReq.url.toLowerCase();
		if (!domain) {
			domain = '/';
		}

		if (domains.indexOf(domain) < 0) {
			domains.push(domain);
			freeServerConnections[domain] = [];
			freeClientConnections[domain] = [];
		}

		return domain;

	}

	me.server.on('connection', function(wsclient) {

		var domain = getDomain(wsclient);

		if (me._isSocketAttemptingAuth(wsclient)) {

			if (me._authorizeSocketAsServerConnection(wsclient, config.basicauth)) {
				freeServerConnections[domain].push(wsclient)
				me.emit('server.connect', wsclient);

				var handleServerEarlyDisconnect = function() {
					var i = freeServerConnections[domain].indexOf(wsclient)
					if (i >= 0) {
						freeServerConnections[domain].splice(i, 1);
						console.log('server closed early: ' + JSON.stringify(arguments));
						me.emit('server.close', wsclient);
					}
				};

				wsclient.on('close', handleServerEarlyDisconnect).on('error', handleServerEarlyDisconnect);

			} else {
				console.log('drop server connection, failed basicauth');
				wsclient.close(3000, 'bridge basic auth attempt invalid');
				return;
			}
		} else {

			freeClientConnections[domain].push(wsclient);
			me.emit('client.connect', wsclient);
			me._bufferSocket(wsclient);

			var handleClientEarlyDisconnect = function() {
				var i = freeClientConnections[domain].indexOf(wsclient)
				if (i >= 0) {
					freeClientConnections[domain].splice(i, 1);
					console.log('client closed early');
					me.emit('client.close', wsclient);
				}

			};

			wsclient.on('close', handleClientEarlyDisconnect).on('error', handleClientEarlyDisconnect);

		}

		while (freeServerConnections[domain].length && freeClientConnections[domain].length) {

			var server = freeServerConnections[domain].shift();
			var client = freeClientConnections[domain].shift();
			me._connectSockets(server, client);

		}

	}).on('close', function() {

		console.log('bridge server closed');

	}).on('error', function(err) {
		throw err;
	});

};

WSBridgeProxy.prototype.__proto__ = events.EventEmitter.prototype;

WSBridgeProxy.prototype._bufferSocket = function(wsclient) {
	var me = this;
	if (!me._flushBuffers) {

		me._bufferedClients = [];
		me._buffers = [];
		me._handlers = [];

		me._flushBuffers = function(server, client) {
			var i = me._bufferedClients.indexOf(client);
			if (me._buffers[i].length) {

				me.emit('buffer.flush', wsclient, buffer);

				me._buffers[i].forEach(function(message) {
					//client.emit('message', message);
					try {
						console.log('send to server buffered: ' + message);
						server.send(message);
					} catch (e) {
						console.log('client flush buffer error: ' + e.message);
					}
				});

				me.emit('buffer.close', wsclient);
			}

			me._bufferedClients.splice(i, 1);
			me._buffers.splice(i, 1);
			client.removeListener('message', me._handlers[i]);
			me._handlers.splice(i, 1);
		}

		me.on('pair', me._flushBuffers);
	}

	me._bufferedClients.push(wsclient);
	var buffer = [];
	me._buffers.push(buffer);
	var handler = function message(data, flags) {

		if (buffer.length == 0) {
			me.emit('buffer.create', wsclient);
		}

		buffer.push(data);
		me.emit('buffer', wsclient, data);
	}
	me._handlers.push(handler);
	wsclient.on('message', handler);

};

WSBridgeProxy.prototype._isSocketAttemptingAuth = function(wsclient) {
	return (typeof wsclient.upgradeReq.headers.authorization) != 'undefined'
};

WSBridgeProxy.prototype._authorizeSocketAsServerConnection = function(wsclient, basicauth) {
	var atob = require('atob');
	var b64auth = wsclient.upgradeReq.headers.authorization.split(' ')[1];
	var auth = atob(b64auth);
	if (auth === basicauth) {
		return true;
	} else {
		console.log('bridge basic auth attempt invalid: ' + b64auth + ' = ' + auth + ' | ' + basicauth)
		return false;
	}
};

WSBridgeProxy.prototype._connectSockets = function(wsserver, wsclient) {

	var me = this;
	var server = wsserver;
	var client = wsclient;

	var cleanup = function() {
		if (client && server) {
			me.emit('unpair', server, client);
		}
		if (client) {
			client = null;
			wsclient.close();

		}
		if (server) {
			server = null;
			wsserver.close();
		}

	}

	server.on('message', function() {
		try {
			client.send.apply(client, arguments);
		} catch (e) {
			console.log('send to client error: ' + e.message);
			//cleanup();
		}
	}).on('close', cleanup).on('error', cleanup);
	client.on('message', function() {
		try {
			server.send.apply(server, arguments);
		} catch (e) {
			console.log('send to server error: ' + e.message);
			//cleanup();
		}
	}).on('close', cleanup).on('error', cleanup);

	me.emit('pair', server, client);

}

WSBridgeProxy.prototype.close = function() {

	var me = this;
	me.server.close();

}

module.exports = WSBridgeProxy;

/**
 * can be run directly from the command line. ie: sudo node bridgeproxy.js port username:password
 */

if (process.argv) {
	if (!process.argc) {
		process.argc = process.argv.length;
	}

	var fs = require('fs');
	fs.realpath(process.argv[1], function(err, p1) {

		fs.realpath(__filename, function(err, p2) {

			//console.log(p1+' '+p2);

			if (p1 === p2) {

				console.log(process.argv);

				if (process.argc >= 3) {
					var opt = {
						port: parseInt(process.argv[2])
					};
					if (process.argc > 3) {
						opt.basicauth = process.argv[3];
					}
					new WSBridgeProxy(opt);
				} else {
					new WSBridgeProxy(require('./bridgeproxy.json'));
				}

			}

		});
	});
}<commit_msg>send notification to server when client connects this will need to be discarded by server connection<commit_after>/**
 * Bridge proxy
 *
 */

var events = require('events');

/**
 * config options:{
 * 		port:int //only processes with root permissions can listen on privileged ports, ie: sudo node bridgeproxy.js
 * }
 */
function WSBridgeProxy(config, callback) {

	// Simple websocket server
	var me = this;
	events.EventEmitter.call(me);

	var freeServerConnections = {
		'/': []
	};
	var freeClientConnections = {
		'/': []
	};

	if (config.server) {

		me.server = (new(require('ws').Server)({
			server: config.server
		}, function() {

			console.log('bridgeproxy websocket listening on: ' + config.port);

			if ((typeof callback) == 'function') {
				callback();
			}
		}));

		if (config.server && config.port) {
			config.server.listen(config.port, callback);
		}

	} else if (config.port) {

		me.server = (new(require('ws').Server)({
			port: config.port
		}, function() {

			console.log('bridgeproxy websocket listening on: ' + config.port);

			if ((typeof callback) == 'function') {
				callback();
			}
		}));

	} else {
		throw new Error('Expected server or port, in config');
	}

	var domains = [];
	var getDomain = function(ws) {

		var domain = ws.upgradeReq.url.toLowerCase();
		if (!domain) {
			domain = '/';
		}

		if (domains.indexOf(domain) < 0) {
			domains.push(domain);
			freeServerConnections[domain] = [];
			freeClientConnections[domain] = [];
		}

		return domain;

	}

	me.server.on('connection', function(wsclient) {

		var domain = getDomain(wsclient);

		if (me._isSocketAttemptingAuth(wsclient)) {

			if (me._authorizeSocketAsServerConnection(wsclient, config.basicauth)) {
				freeServerConnections[domain].push(wsclient)
				me.emit('server.connect', wsclient);

				var handleServerEarlyDisconnect = function() {
					var i = freeServerConnections[domain].indexOf(wsclient)
					if (i >= 0) {
						freeServerConnections[domain].splice(i, 1);
						console.log('server closed early: ' + JSON.stringify(arguments));
						me.emit('server.close', wsclient);
					}
				};

				wsclient.on('close', handleServerEarlyDisconnect).on('error', handleServerEarlyDisconnect);

			} else {
				console.log('drop server connection, failed basicauth');
				wsclient.close(3000, 'bridge basic auth attempt invalid');
				return;
			}
		} else {

			freeClientConnections[domain].push(wsclient);
			me.emit('client.connect', wsclient);
			me._bufferSocket(wsclient);

			var handleClientEarlyDisconnect = function() {
				var i = freeClientConnections[domain].indexOf(wsclient)
				if (i >= 0) {
					freeClientConnections[domain].splice(i, 1);
					console.log('client closed early');
					me.emit('client.close', wsclient);
				}

			};

			wsclient.on('close', handleClientEarlyDisconnect).on('error', handleClientEarlyDisconnect);

		}

		while (freeServerConnections[domain].length && freeClientConnections[domain].length) {

			var server = freeServerConnections[domain].shift();
			var client = freeClientConnections[domain].shift();
			me._connectSockets(server, client);

		}

	}).on('close', function() {

		console.log('bridge server closed');

	}).on('error', function(err) {
		throw err;
	});

};

WSBridgeProxy.prototype.__proto__ = events.EventEmitter.prototype;

WSBridgeProxy.prototype._bufferSocket = function(wsclient) {
	var me = this;
	if (!me._flushBuffers) {

		me._bufferedClients = [];
		me._buffers = [];
		me._handlers = [];

		me._flushBuffers = function(server, client) {
			var i = me._bufferedClients.indexOf(client);
			if (me._buffers[i].length) {

				me.emit('buffer.flush', wsclient, buffer);

				me._buffers[i].forEach(function(message) {
					//client.emit('message', message);
					try {
						console.log('send to server buffered: ' + message);
						server.send(message);
					} catch (e) {
						console.log('client flush buffer error: ' + e.message);
					}
				});

				me.emit('buffer.close', wsclient);
			}

			me._bufferedClients.splice(i, 1);
			me._buffers.splice(i, 1);
			client.removeListener('message', me._handlers[i]);
			me._handlers.splice(i, 1);
		}

		me.on('pair', me._flushBuffers);
	}

	me._bufferedClients.push(wsclient);
	var buffer = [];
	me._buffers.push(buffer);
	var handler = function message(data, flags) {

		if (buffer.length == 0) {
			me.emit('buffer.create', wsclient);
		}

		buffer.push(data);
		me.emit('buffer', wsclient, data);
	}
	me._handlers.push(handler);
	wsclient.on('message', handler);

};

WSBridgeProxy.prototype._isSocketAttemptingAuth = function(wsclient) {
	return (typeof wsclient.upgradeReq.headers.authorization) != 'undefined'
};

WSBridgeProxy.prototype._authorizeSocketAsServerConnection = function(wsclient, basicauth) {
	var atob = require('atob');
	var b64auth = wsclient.upgradeReq.headers.authorization.split(' ')[1];
	var auth = atob(b64auth);
	if (auth === basicauth) {
		return true;
	} else {
		console.log('bridge basic auth attempt invalid: ' + b64auth + ' = ' + auth + ' | ' + basicauth)
		return false;
	}
};

WSBridgeProxy.prototype._connectSockets = function(wsserver, wsclient) {

	var me = this;
	var server = wsserver;
	var client = wsclient;

	var cleanup = function() {
		if (client && server) {
			me.emit('unpair', server, client);
		}
		if (client) {
			client = null;
			wsclient.close();

		}
		if (server) {
			server = null;
			wsserver.close();
		}

	}

	server.on('message', function() {
		try {
			client.send.apply(client, arguments);
		} catch (e) {
			console.log('send to client error: ' + e.message);
			//cleanup();
		}
	}).on('close', cleanup).on('error', cleanup);
	client.on('message', function() {
		try {
			server.send.apply(server, arguments);
		} catch (e) {
			console.log('send to server error: ' + e.message);
			//cleanup();
		}
	}).on('close', cleanup).on('error', cleanup);

	server.send('CLIENT CONNECT');

	//will cause client buffered data to be sent.
	me.emit('pair', server, client);

}

WSBridgeProxy.prototype.close = function() {

	var me = this;
	me.server.close();

}

module.exports = WSBridgeProxy;

/**
 * can be run directly from the command line. ie: sudo node bridgeproxy.js port username:password
 */

if (process.argv) {
	if (!process.argc) {
		process.argc = process.argv.length;
	}

	var fs = require('fs');
	fs.realpath(process.argv[1], function(err, p1) {

		fs.realpath(__filename, function(err, p2) {

			//console.log(p1+' '+p2);

			if (p1 === p2) {

				console.log(process.argv);

				if (process.argc >= 3) {
					var opt = {
						port: parseInt(process.argv[2])
					};
					if (process.argc > 3) {
						opt.basicauth = process.argv[3];
					}
					new WSBridgeProxy(opt);
				} else {
					new WSBridgeProxy(require('./bridgeproxy.json'));
				}

			}

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


<commit_before>/**
 * @file Tool definition for the PC dual purpose selection tool. Provides event
 * handlers and special logic for the selection tool ONLY. Allows selection of
 * entire objects, rotation, scaling and node/segment adjustment.
 **/
"use strict";

module.exports = function(paper) {
  var tool = new paper.Tool();

  // Paper global extenders
  var Path = paper.Path;
  var Point = paper.Point;
  var Rectangle = paper.Rectangle;
  var project = paper.project;

  // Handy internal vars
  var selectionRectangle = null;
  var selectionRectangleScale = null;
  var selectionRectangleRotation = null;
  var segment, path;
  var hitOptions = {
    segments: true,
    stroke: true,
    fill: true,
    tolerance: 5
  };

  // Externalize deseletion
  paper.deselect = function() {
    if (selectionRectangle) selectionRectangle.remove();
  }

  // Tool identification (for building out tool palette)
  tool.name = 'tools.select';
  tool.key = 'select';

  tool.onMouseDown = function(event) {
    segment = path = null;

    var hitResult = project.hitTest(event.point, hitOptions);

    // If we didn't hit anything with hitTest...
    if (!hitResult) {
      // Find any items that are Paths (not layers) that contain the point
      var item = getBoundSelection(event.point);

      // If we actually found something, fake a fill hitResult
      if (item) {
        hitResult = {
          type: 'fill', // SURE it is ;)
          item: item
        };
      } else {
        // Deselect if nothing clicked (feels natural for deselection)
        if (selectionRectangle !== null) {
          selectionRectangle.remove();
          selectionRectangle = null;
        }

        return;
      }
    }

    if (event.modifiers.shift) {
      if (hitResult.type === 'segment') {
        hitResult.segment.remove();
      }
      return;
    }

    if (hitResult) {
      path = hitResult.item;

      if (hitResult.type === 'segment') {
        if (selectionRectangle !== null && path.name === "selection rectangle") {
          if (hitResult.segment.index >= 2 && hitResult.segment.index <= 4) {
            // Rotation hitbox
            selectionRectangleRotation = 0;
          } else {
            // Scale hitbox
            selectionRectangleScale = event.point.subtract(selectionRectangle.bounds.center).length / path.scaling.x;
          }
        } else {
          segment = hitResult.segment;
        }
      } else if (hitResult.type === 'stroke' && path !== selectionRectangle) {
        var location = hitResult.location;
        segment = path.insert(location.index + 1, event.point);
        //path.smooth();
      }

      if ((selectionRectangle === null || selectionRectangle.ppath !== path) && selectionRectangle !== path) {
        initSelectionRectangle(path);
      }
    }

    // If a fill hit, move the path
    if (hitResult.type === 'fill') {
      project.activeLayer.addChild(hitResult.item);
    }
  };

  tool.onMouseDrag = function(event) {
    if (selectionRectangleScale !== null) {
      // Path scale adjustment
      var ratio = event.point.subtract(selectionRectangle.bounds.center).length / selectionRectangleScale;
      var scaling = new Point(ratio, ratio);
      selectionRectangle.scaling = scaling;
      selectionRectangle.ppath.scaling = scaling;
      return;
    } else if (selectionRectangleRotation !== null) {
      // Path rotation adjustment
      var rotation = event.point.subtract(selectionRectangle.pivot).angle + 90;
      selectionRectangle.ppath.rotation = rotation;
      selectionRectangle.rotation = rotation;
      return;
    }

    if (segment) {
      // Individual path segment position adjustment
      segment.point.x += event.delta.x;
      segment.point.y += event.delta.y;

      // Smooth -only- non-polygonal paths
      if (!path.data.isPolygonal) path.smooth();

      initSelectionRectangle(path);
    } else if (path) {
      // Path translate position adjustment
      if (path !== selectionRectangle) {
        path.position.x += event.delta.x;
        path.position.y += event.delta.y;
        selectionRectangle.position.x += event.delta.x;
        selectionRectangle.position.y += event.delta.y;
      } else {
        selectionRectangle.position.x += event.delta.x;
        selectionRectangle.position.y += event.delta.y;
        selectionRectangle.ppath.position.x += event.delta.x;
        selectionRectangle.ppath.position.y += event.delta.y;
      }
    }
  };

  tool.onMouseMove = function(event) {
    project.activeLayer.selected = false;

    var boundItem = getBoundSelection(event.point);

    if (event.item) {
      event.item.selected = true;
      paper.setCursor('copy');
    } else if (boundItem) {
      boundItem.selected = true;
      paper.setCursor('move');
    } else {
      paper.setCursor();
    }

    if (selectionRectangle) {
      selectionRectangle.selected = true;
    }
  };

  tool.onMouseUp = function(event) {
    selectionRectangleScale = null;
    selectionRectangleRotation = null;
  };

  tool.onKeyDown = function (event) {
    if (event.key === 'delete' && selectionRectangle) {
      selectionRectangle.ppath.remove();
      selectionRectangle.remove();
      selectionRectangle = null;
    }
  };

  function initSelectionRectangle(path) {
    if (selectionRectangle !== null) selectionRectangle.remove();

    var reset = path.rotation === 0 && path.scaling.x === 1 && path.scaling.y === 1;
    var bounds;

    if (reset) {
      // Actually reset bounding box
      bounds = path.bounds;
      path.pInitialBounds = path.bounds;
    } else {
      // No bounding box reset
      bounds = path.pInitialBounds;
    }

    var b = bounds.clone().expand(10, 10);

    selectionRectangle = new Path.Rectangle(b);
    selectionRectangle.pivot = selectionRectangle.position;
    selectionRectangle.insert(2, new Point(b.center.x, b.top));
    selectionRectangle.insert(2, new Point(b.center.x, b.top - 25));
    selectionRectangle.insert(2, new Point(b.center.x, b.top));

    if (!reset) {
      selectionRectangle.position = path.bounds.center;
      selectionRectangle.rotation = path.rotation;
      selectionRectangle.scaling = path.scaling;
    }

    selectionRectangle.strokeWidth = 2;
    selectionRectangle.strokeColor = 'blue';
    selectionRectangle.name = "selection rectangle";
    selectionRectangle.selected = true;
    selectionRectangle.ppath = path;
    selectionRectangle.ppath.pivot = selectionRectangle.pivot;
  }

  function getBoundSelection(point) {
    // Check for items that are overlapping a rect around the event point
    var items = project.getItems({
      overlapping: new Rectangle(point.x - 2, point.y - 2,point.x + 2, point.y + 2)
    });

    var item = null;
    _.each(items, function (i) {
      if (i instanceof Path) {
        if (i.contains(point)) {
          item = i;
        }
      }
    });

    return item;
  }
};

<commit_msg>Transition to globally based selection rectangle for #12<commit_after>/**
 * @file Tool definition for the PC dual purpose selection tool. Provides event
 * handlers and special logic for the selection tool ONLY. Allows selection of
 * entire objects, rotation, scaling and node/segment adjustment.
 **/
"use strict";

module.exports = function(paper) {
  var tool = new paper.Tool();

  // Paper global extenders
  var Path = paper.Path;
  var Point = paper.Point;
  var Rectangle = paper.Rectangle;
  var project = paper.project;

  // Handy internal vars
  paper.selectRect = null;
  var selectionRectangleScale = null;
  var selectionRectangleRotation = null;
  var segment, path;
  var hitOptions = {
    segments: true,
    stroke: true,
    fill: true,
    tolerance: 5
  };

  // Externalize deseletion
  paper.deselect = function() {
    if (paper.selectRect) paper.selectRect.remove();
  }

  // Tool identification (for building out tool palette)
  tool.name = 'tools.select';
  tool.key = 'select';

  tool.onMouseDown = function(event) {
    segment = path = null;

    var hitResult = project.hitTest(event.point, hitOptions);

    // If we didn't hit anything with hitTest...
    if (!hitResult) {
      // Find any items that are Paths (not layers) that contain the point
      var item = getBoundSelection(event.point);

      // If we actually found something, fake a fill hitResult
      if (item) {
        hitResult = {
          type: 'fill', // SURE it is ;)
          item: item
        };
      } else {
        // Deselect if nothing clicked (feels natural for deselection)
        if (paper.selectRect !== null) {
          paper.selectRect.remove();
          paper.selectRect = null;
        }

        return;
      }
    }

    if (event.modifiers.shift) {
      if (hitResult.type === 'segment') {
        hitResult.segment.remove();
      }
      return;
    }

    if (hitResult) {
      path = hitResult.item;

      if (hitResult.type === 'segment') {
        if (paper.selectRect !== null && path.name === "selection rectangle") {
          if (hitResult.segment.index >= 2 && hitResult.segment.index <= 4) {
            // Rotation hitbox
            selectionRectangleRotation = 0;
          } else {
            // Scale hitbox
            selectionRectangleScale = event.point.subtract(paper.selectRect.bounds.center).length / path.scaling.x;
          }
        } else {
          segment = hitResult.segment;
        }
      } else if (hitResult.type === 'stroke' && path !== paper.selectRect) {
        var location = hitResult.location;
        segment = path.insert(location.index + 1, event.point);
        //path.smooth();
      }

      if ((paper.selectRect === null || paper.selectRect.ppath !== path) && paper.selectRect !== path) {
        initSelectionRectangle(path);
      }
    }

    // If a fill hit, move the path
    if (hitResult.type === 'fill') {
      project.activeLayer.addChild(hitResult.item);
    }
  };

  tool.onMouseDrag = function(event) {
    if (selectionRectangleScale !== null) {
      // Path scale adjustment
      var ratio = event.point.subtract(paper.selectRect.bounds.center).length / selectionRectangleScale;
      var scaling = new Point(ratio, ratio);
      paper.selectRect.scaling = scaling;
      paper.selectRect.ppath.scaling = scaling;
      return;
    } else if (selectionRectangleRotation !== null) {
      // Path rotation adjustment
      var rotation = event.point.subtract(paper.selectRect.pivot).angle + 90;
      paper.selectRect.ppath.rotation = rotation;
      paper.selectRect.rotation = rotation;
      return;
    }

    if (segment) {
      // Individual path segment position adjustment
      segment.point.x += event.delta.x;
      segment.point.y += event.delta.y;

      // Smooth -only- non-polygonal paths
      if (!path.data.isPolygonal) path.smooth();

      initSelectionRectangle(path);
    } else if (path) {
      // Path translate position adjustment
      if (path !== paper.selectRect) {
        path.position.x += event.delta.x;
        path.position.y += event.delta.y;
        paper.selectRect.position.x += event.delta.x;
        paper.selectRect.position.y += event.delta.y;
      } else {
        paper.selectRect.position.x += event.delta.x;
        paper.selectRect.position.y += event.delta.y;
        paper.selectRect.ppath.position.x += event.delta.x;
        paper.selectRect.ppath.position.y += event.delta.y;
      }
    }
  };

  tool.onMouseMove = function(event) {
    project.activeLayer.selected = false;

    var boundItem = getBoundSelection(event.point);

    if (event.item) {
      event.item.selected = true;
      paper.setCursor('copy');
    } else if (boundItem) {
      boundItem.selected = true;
      paper.setCursor('move');
    } else {
      paper.setCursor();
    }

    if (paper.selectRect) {
      paper.selectRect.selected = true;
    }
  };

  tool.onMouseUp = function(event) {
    selectionRectangleScale = null;
    selectionRectangleRotation = null;
  };

  tool.onKeyDown = function (event) {
    if (event.key === 'delete' && paper.selectRect) {
      paper.selectRect.ppath.remove();
      paper.selectRect.remove();
      paper.selectRect = null;
    }
  };

  function initSelectionRectangle(path) {
    if (paper.selectRect !== null) paper.selectRect.remove();

    var reset = path.rotation === 0 && path.scaling.x === 1 && path.scaling.y === 1;
    var bounds;

    if (reset) {
      // Actually reset bounding box
      bounds = path.bounds;
      path.pInitialBounds = path.bounds;
    } else {
      // No bounding box reset
      bounds = path.pInitialBounds;
    }

    var b = bounds.clone().expand(10, 10);

    paper.selectRect = new Path.Rectangle(b);
    paper.selectRect.pivot = paper.selectRect.position;
    paper.selectRect.insert(2, new Point(b.center.x, b.top));
    paper.selectRect.insert(2, new Point(b.center.x, b.top - 25));
    paper.selectRect.insert(2, new Point(b.center.x, b.top));

    if (!reset) {
      paper.selectRect.position = path.bounds.center;
      paper.selectRect.rotation = path.rotation;
      paper.selectRect.scaling = path.scaling;
    }

    paper.selectRect.strokeWidth = 2;
    paper.selectRect.strokeColor = 'blue';
    paper.selectRect.name = "selection rectangle";
    paper.selectRect.selected = true;
    paper.selectRect.ppath = path;
    paper.selectRect.ppath.pivot = paper.selectRect.pivot;
  }

  function getBoundSelection(point) {
    // Check for items that are overlapping a rect around the event point
    var items = project.getItems({
      overlapping: new Rectangle(point.x - 2, point.y - 2,point.x + 2, point.y + 2)
    });

    var item = null;
    _.each(items, function (i) {
      if (i instanceof Path) {
        if (i.contains(point)) {
          item = i;
        }
      }
    });

    return item;
  }
};

<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import FullTradeCard from '../fulltrade/FullTradeCard';

export default class TradesGrid extends Component {

    static propTypes = {
        actions: PropTypes.object.isRequired,
        activeTradeIndex: PropTypes.number.isRequired,
        ticks: PropTypes.object.isRequired,
        currency: PropTypes.string.isRequired,
        ticksForAllSymbols: PropTypes.object.isRequired,
        trades: PropTypes.array.isRequired,
        contracts: PropTypes.object.isRequired,
        currency: PropTypes.string.isRequired,
    };

    render() {
        const { actions, activeTradeIndex, currency, trades, ticksForAllSymbols, contracts } = this.props;

        return (

                {trades.map((trade, index) =>
                    (contracts[trade.symbol] && <FullTradeCard
                        key={index}
                        index={index}
                        currency={currency}
                        actions={actions}
                        trade={trade}
                        isActive={index === activeTradeIndex}
                        ticks={ticksForAllSymbols[trade.symbol]}
                        contract={contracts[trade.symbol]}
                        currency={currency}
                    />)
                )}

        );
    }
}
<commit_msg>Rename ticks to ticksForAllSymbols<commit_after>import React, { PropTypes, Component } from 'react';
import FullTradeCard from '../fulltrade/FullTradeCard';

export default class TradesGrid extends Component {

    static propTypes = {
        actions: PropTypes.object.isRequired,
        activeTradeIndex: PropTypes.number.isRequired,
        currency: PropTypes.string.isRequired,
        ticksForAllSymbols: PropTypes.object.isRequired,
        trades: PropTypes.array.isRequired,
        contracts: PropTypes.object.isRequired,
    };

    render() {
        const { actions, activeTradeIndex, currency, trades, ticksForAllSymbols, contracts } = this.props;

        return (

                {trades.map((trade, index) =>
                    (contracts[trade.symbol] && <FullTradeCard
                        key={index}
                        index={index}
                        currency={currency}
                        actions={actions}
                        trade={trade}
                        isActive={index === activeTradeIndex}
                        ticks={ticksForAllSymbols[trade.symbol]}
                        contract={contracts[trade.symbol]}
                    />)
                )}

        );
    }
}
<|endoftext|>


<commit_before>import { useState, useEffect } from 'react'
import loadScript from './load-script'
import removeScript from './remove-script'

const useGoogleLogout = ({
  jsSrc = 'https://apis.google.com/js/api.js',
  onFailure,
  clientId,
  cookiePolicy,
  loginHint,
  hostedDomain,
  fetchBasicProfile,
  discoveryDocs,
  uxMode,
  redirectUri,
  scope,
  accessType,
  onLogoutSuccess
}) => {
  const [loaded, setLoaded] = useState(false)

  const signOut = () => {
    if (window.gapi) {
      const auth2 = window.gapi.auth2.getAuthInstance()
      if (auth2 != null) {
        auth2.then(
          () => {
            auth2.signOut().then(auth2.disconnect().then(onLogoutSuccess))
          },
          err => onFailure(err)
        )
      }
    }
  }

  useEffect(() => {
    loadScript(document, 'script', 'google-login', jsSrc, () => {
      const params = {
        client_id: clientId,
        cookie_policy: cookiePolicy,
        login_hint: loginHint,
        hosted_domain: hostedDomain,
        fetch_basic_profile: fetchBasicProfile,
        discoveryDocs,
        ux_mode: uxMode,
        redirect_uri: redirectUri,
        scope,
        access_type: accessType
      }
      window.gapi.load('auth2', () => {
        if (!window.gapi.auth2.getAuthInstance()) {
          window.gapi.auth2.init(params).then(
            () => setLoaded(true),
            err => onFailure(err)
          )
        } else {
          setLoaded(true)
        }
      })
    })

    return () => {
      removeScript(document, 'google-login')
    }
  }, [])

  return { signOut, loaded }
}

export default useGoogleLogout
<commit_msg>useGoogleLogout: Stabilize signOut reference (#390)<commit_after>import { useState, useEffect, useCallback } from 'react'
import loadScript from './load-script'
import removeScript from './remove-script'

const useGoogleLogout = ({
  jsSrc = 'https://apis.google.com/js/api.js',
  onFailure,
  clientId,
  cookiePolicy,
  loginHint,
  hostedDomain,
  fetchBasicProfile,
  discoveryDocs,
  uxMode,
  redirectUri,
  scope,
  accessType,
  onLogoutSuccess
}) => {
  const [loaded, setLoaded] = useState(false)

  const signOut = useCallback(() => {
    if (window.gapi) {
      const auth2 = window.gapi.auth2.getAuthInstance()
      if (auth2 != null) {
        auth2.then(
          () => {
            auth2.signOut().then(auth2.disconnect().then(onLogoutSuccess))
          },
          err => onFailure(err)
        )
      }
    }
  }, [onLogoutSuccess])

  useEffect(() => {
    loadScript(document, 'script', 'google-login', jsSrc, () => {
      const params = {
        client_id: clientId,
        cookie_policy: cookiePolicy,
        login_hint: loginHint,
        hosted_domain: hostedDomain,
        fetch_basic_profile: fetchBasicProfile,
        discoveryDocs,
        ux_mode: uxMode,
        redirect_uri: redirectUri,
        scope,
        access_type: accessType
      }
      window.gapi.load('auth2', () => {
        if (!window.gapi.auth2.getAuthInstance()) {
          window.gapi.auth2.init(params).then(
            () => setLoaded(true),
            err => onFailure(err)
          )
        } else {
          setLoaded(true)
        }
      })
    })

    return () => {
      removeScript(document, 'google-login')
    }
  }, [])

  return { signOut, loaded }
}

export default useGoogleLogout
<|endoftext|>


<commit_before>// Basic Info Endpoints

const express = require("express")
const v2 = express.Router()

// Returns company info
v2.get("/", (req, res, next) => {
  global.db.collection("info").find({},{"_id": 0 }).toArray((err, doc) => {
    if (err) {
      return next(err)
    }
    res.json(doc[0])
  })
})

module.exports = v2
<commit_msg>update info to async<commit_after>// Basic Info Endpoints

const express = require("express")
const v2 = express.Router()
const asyncHandle = require("express-async-handler")

// Returns company info
v2.get("/", asyncHandle(async (req, res) => {
  const data = await global.db
    .collection("info")
    .find({},{"_id": 0 })
    .toArray()
  res.json(data[0])
}))

module.exports = v2
<|endoftext|>


<commit_before>angular
    .module('ngVibrant')
    .directive('vibrant', vibrant);

function vibrant($vibrant) {
    var directive = {
        restrict: 'E',
        scope: {
            vibrant: '=' //Model
        },
        link: link
    };

    return directive;

    function link(scope, element) {
        var swatches = $vibrant(element[0]);
        scope.vibrant = swatches;
    }
}
<commit_msg>Calculate vibrant colors on image load<commit_after>angular
    .module('ngVibrant')
    .directive('vibrant', vibrant);

function vibrant($vibrant) {
    var directive = {
        restrict: 'E',
        scope: {
            vibrant: '=' //Model
        },
        link: link
    };

    return directive;

    function link(scope, element) {
        scope.vibrant = [];
        element.on('load', function() {
            var swatches = $vibrant(element[0]);
            scope.vibrant = swatches;
        });
    }
}
<|endoftext|>


<commit_before>let fs = require('fs')
let path = require('path');
let proc = require('child_process');

const PROJECT_DIR = process.cwd();
process.env.PROJECT_DIR = PROJECT_DIR;

namespace('doc', function () {
  task('generate', ['doc:clobber'], function () {
    var cmd = '../node-jsdoc-toolkit/app/run.js -n -r=100 ' +
        '-t=../node-jsdoc-toolkit/templates/codeview -d=./doc/ ./lib';
    jake.logger.log('Generating docs ...');
    jake.exec([cmd], function () {
      jake.logger.log('Done.');
      complete();
    });
  }, {async: true});

  task('clobber', function () {
    var cmd = 'rm -fr ./doc/*';
    jake.exec([cmd], function () {
      jake.logger.log('Clobbered old docs.');
      complete();
    });
  }, {async: true});

});

desc('Generate docs for Jake');
task('doc', ['doc:generate']);

npmPublishTask('jake', function () {
  this.packageFiles.include([
    'Makefile',
    'jakefile.js',
    'README.md',
    'package.json',
    'usage.txt',
    'lib/**',
    'bin/**',
    'test/**'
    ]);
  this.packageFiles.exclude([
    'test/tmp'
  ]);
});

jake.Task['publish:package'].directory = PROJECT_DIR;

namespace('test', function () {

  let integrationTest = task('integration', ['publish:package'], async function () {
    let pkg = JSON.parse(fs.readFileSync(`${PROJECT_DIR}/package.json`).toString());
    let version = pkg.version;

    proc.execSync('rm -rf ./node_modules');
    // Install from the actual package, run tests from the packaged binary
    proc.execSync(`mkdir -p node_modules/.bin && mv ${PROJECT_DIR}/pkg/jake-v` +
        `${version} node_modules/jake && ln -s ${process.cwd()}` +
      '/node_modules/jake/bin/cli.js ./node_modules/.bin/jake');

    let testArgs = [];
    if (process.env.filter) {
      testArgs.push(process.env.filter);
    }
    else {
      testArgs.push('*.js');
    }
    let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, {
      stdio: 'inherit'
    });
    return new Promise((resolve, reject) => {
      spawned.on('exit', () => {
        if (!(process.env.noclobber || process.env.noClobber)) {
          proc.execSync('rm -rf tmp_publish && rm -rf package.json' +
              ' && rm -rf package-lock.json && rm -rf node_modules');
          // Rather than invoking 'clobber' task
          jake.rmRf(`${PROJECT_DIR}/pkg`);
        }
        resolve();
      });
    });

  });

  integrationTest.directory = `${PROJECT_DIR}/test/integration`;

  let unitTest = task('unit', async function () {
    let testArgs = [];
    if (process.env.filter) {
      testArgs.push(process.env.filter);
    }
    else {
      testArgs.push('*.js');
    }
    let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, {
      stdio: 'inherit'
    });
  });

  unitTest.directory = `${PROJECT_DIR}/test/unit`;
});

task('test', ['test:unit', 'test:integration']);
<commit_msg>Added description for tets task<commit_after>let fs = require('fs')
let path = require('path');
let proc = require('child_process');

const PROJECT_DIR = process.cwd();
process.env.PROJECT_DIR = PROJECT_DIR;

namespace('doc', function () {
  task('generate', ['doc:clobber'], function () {
    var cmd = '../node-jsdoc-toolkit/app/run.js -n -r=100 ' +
        '-t=../node-jsdoc-toolkit/templates/codeview -d=./doc/ ./lib';
    jake.logger.log('Generating docs ...');
    jake.exec([cmd], function () {
      jake.logger.log('Done.');
      complete();
    });
  }, {async: true});

  task('clobber', function () {
    var cmd = 'rm -fr ./doc/*';
    jake.exec([cmd], function () {
      jake.logger.log('Clobbered old docs.');
      complete();
    });
  }, {async: true});

});

desc('Generate docs for Jake');
task('doc', ['doc:generate']);

npmPublishTask('jake', function () {
  this.packageFiles.include([
    'Makefile',
    'jakefile.js',
    'README.md',
    'package.json',
    'usage.txt',
    'lib/**',
    'bin/**',
    'test/**'
    ]);
  this.packageFiles.exclude([
    'test/tmp'
  ]);
});

jake.Task['publish:package'].directory = PROJECT_DIR;

namespace('test', function () {

  let integrationTest = task('integration', ['publish:package'], async function () {
    let pkg = JSON.parse(fs.readFileSync(`${PROJECT_DIR}/package.json`).toString());
    let version = pkg.version;

    proc.execSync('rm -rf ./node_modules');
    // Install from the actual package, run tests from the packaged binary
    proc.execSync(`mkdir -p node_modules/.bin && mv ${PROJECT_DIR}/pkg/jake-v` +
        `${version} node_modules/jake && ln -s ${process.cwd()}` +
      '/node_modules/jake/bin/cli.js ./node_modules/.bin/jake');

    let testArgs = [];
    if (process.env.filter) {
      testArgs.push(process.env.filter);
    }
    else {
      testArgs.push('*.js');
    }
    let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, {
      stdio: 'inherit'
    });
    return new Promise((resolve, reject) => {
      spawned.on('exit', () => {
        if (!(process.env.noclobber || process.env.noClobber)) {
          proc.execSync('rm -rf tmp_publish && rm -rf package.json' +
              ' && rm -rf package-lock.json && rm -rf node_modules');
          // Rather than invoking 'clobber' task
          jake.rmRf(`${PROJECT_DIR}/pkg`);
        }
        resolve();
      });
    });

  });

  integrationTest.directory = `${PROJECT_DIR}/test/integration`;

  let unitTest = task('unit', async function () {
    let testArgs = [];
    if (process.env.filter) {
      testArgs.push(process.env.filter);
    }
    else {
      testArgs.push('*.js');
    }
    let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, {
      stdio: 'inherit'
    });
  });

  unitTest.directory = `${PROJECT_DIR}/test/unit`;
});

desc('Runs all tests');
task('test', ['test:unit', 'test:integration']);
<|endoftext|>


<commit_before>/**
 * Child Class
 *
 * Defines a visualization child.
 *
 * Options:
 *  height - Integer
 *  width - Integer
 *  flotr - A set of flotr options
 */
(function () {

var

  V = humblevis,

  CN_CHILD = 'humble-vis-child',

  T_CHILD       = '

';

function Child (options) {

  options = options || {};

  var
    name = options.name,
    node = bonzo.create(T_CHILD)[0];

  if (name) bonzo(node).addClass(name);

  this.options = options;
  this.node = node;
}

Child.prototype = {

  render : function (element) {

    var
      node = this.node,
      options = this.options;

    element = element || options.element;

    if (!element) throw 'No element to render within.';

    if (options.width) {
      bonzo(this.node).css({width : options.width});
    } else {
      options.width = parseInt(bonzo(this.node).css('width'), 10);
    }

    if (options.height) {
      bonzo(this.node).css({height : options.height});
    } else {
      options.height = parseInt(bonzo(this.node).css('height'), 10);
    }

    this.container = element;
    bonzo(element).append(this.node);

  },
};

V.Child = Child;

})();
<commit_msg>Fixed extra comma.<commit_after>/**
 * Child Class
 *
 * Defines a visualization child.
 *
 * Options:
 *  height - Integer
 *  width - Integer
 *  flotr - A set of flotr options
 */
(function () {

var

  V = humblevis,

  CN_CHILD = 'humble-vis-child',

  T_CHILD       = '

';

function Child (options) {

  options = options || {};

  var
    name = options.name,
    node = bonzo.create(T_CHILD)[0];

  if (name) bonzo(node).addClass(name);

  this.options = options;
  this.node = node;
}

Child.prototype = {

  render : function (element) {

    var
      node = this.node,
      options = this.options;

    element = element || options.element;

    if (!element) throw 'No element to render within.';

    if (options.width) {
      bonzo(this.node).css({width : options.width});
    } else {
      options.width = parseInt(bonzo(this.node).css('width'), 10);
    }

    if (options.height) {
      bonzo(this.node).css({height : options.height});
    } else {
      options.height = parseInt(bonzo(this.node).css('height'), 10);
    }

    this.container = element;
    bonzo(element).append(this.node);
  }
};

V.Child = Child;

})();
<|endoftext|>