<commit_before>var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var PanelWithOptionsView = require('../../../../components/view-options/panel-with-options-view');
var ScrollView = require('../../../../components/scroll/scroll-view');
var DataContentView = require('./data-content-view');
var DataSQLView = require('./data-sql-view');
var TabPaneView = require('../../../../components/tab-pane/tab-pane-view');
var TabPaneCollection = require('../../../../components/tab-pane/tab-pane-collection');
var Toggler = require('../../../../components/toggler/toggler-view');
var UndoButtons = require('../../../../components/undo-redo/undo-redo-view');
var Infobox = require('../../../../components/infobox/infobox-factory');
var InfoboxModel = require('../../../../components/infobox/infobox-model');
var InfoboxCollection = require('../../../../components/infobox/infobox-collection');
var TableStats = require('../../../../components/modals/add-widgets/tablestats');
var DataColumnsModel = require('./data-columns-model');
var Notifier = require('../../../../components/notifier/notifier');
var SQLUtils = require('../../../../helpers/sql-utils');
var cdb = require('cartodb.js');
var errorParser = require('../../../../helpers/error-parser');

module.exports = CoreView.extend({

  initialize: function (opts) {
    if (!opts.widgetDefinitionsCollection) throw new Error('widgetDefinitionsCollection is required');
    if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.configModel) throw new Error('configModel is required');
    if (!opts.stackLayoutModel) throw new Error('StackLayoutModel is required');
    if (!opts.userActions) throw new Error('userActions is required');

    this._layerDefinitionModel = opts.layerDefinitionModel;
    this._widgetDefinitionsCollection = opts.widgetDefinitionsCollection;

    this._userActions = opts.userActions;
    this._configModel = opts.configModel;
    this._editorModel = opts.editorModel;
    this._stackLayoutModel = opts.stackLayoutModel;
    this._nodeModel = this._layerDefinitionModel.getAnalysisDefinitionNodeModel();
    this._querySchemaModel = this._nodeModel.querySchemaModel;

    this._clearSQLModel = new Backbone.Model({
      visible: false
    });

    this._sqlModel = this._layerDefinitionModel.sqlModel;

    this._SQL = new cdb.SQL({
      user: this._configModel.get('user_name'),
      sql_api_template: this._configModel.get('sql_api_template'),
      api_key: this._configModel.get('api_key')
    });

    this._infoboxModel = new InfoboxModel({
      state: ''
    });

    this._tableStats = new TableStats({
      configModel: this._configModel
    });

    this._columnsModel = new DataColumnsModel({}, {
      layerDefinitionModel: this._layerDefinitionModel,
      widgetDefinitionsCollection: this._widgetDefinitionsCollection,
      tableStats: this._tableStats
    });

    this._codemirrorModel = new Backbone.Model({
      content: this._querySchemaModel.get('query'),
      readonly: false
    });

    this._configPanes();
    this._initBinds();
    this._initData();
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    return this;
  },

  _initData: function () {
    if (!this._hasFetchedQuerySchema()) {
      this._querySchemaModel.fetch();
    } else {
      this._onQuerySchemaStatusChange();
    }
  },

  _onQuerySchemaChange: function () {
    if (this._hasFetchedQuerySchema()) {
      this._codemirrorModel.set({content: this._querySchemaModel.get('query')});
    }
  },

  _onQuerySchemaStatusChange: function () {
    if (this._hasFetchedQuerySchema()) {
      this._columnsModel.createColumnCollection();
    }
  },

  _hasFetchedQuerySchema: function () {
    return this._querySchemaModel.get('status') === 'fetched';
  },

  _initBinds: function () {
    this.listenTo(this._editorModel, 'change:edition', this._onChangeEdition);
    this.add_related_model(this._editorModel);

    this._querySchemaModel.on('change:query', this._onQuerySchemaChange, this);
    this._querySchemaModel.on('change:status', this._onQuerySchemaStatusChange, this);
    this._querySchemaModel.on('change:query_errors', this._showErrors, this);
    this.add_related_model(this._querySchemaModel);

    this._sqlModel.bind('undo redo', function () {
      this._codemirrorModel.set('content', this._sqlModel.get('content'));
    }, this);
    this.add_related_model(this._sqlModel);
  },

  _parseSQL: function () {
    var query = this._codemirrorModel.get('content');
    var altersData = SQLUtils.altersData(query);

    if (altersData) {
      var notification = Notifier.addNotification({
        status: 'loading',
        info: _t('editor.data.notifier.sql-alter-loading'),
        closable: false
      });

      this._sqlModel.set('content', query);

      this._SQL.execute(query, null, {
        success: function () {
          notification.set({
            status: 'success',
            info: _t('editor.data.notifier.sql-alter-success'),
            closable: true
          });
          this._applyDefaultSQL();
        }.bind(this),
        error: function (errors) {
          Notifier.removeNotification(notification);
          this._codemirrorModel.set('errors', this._parseErrors(errors));
        }.bind(this)
      });
    } else {
      // Parser errors SQL here and saving
      this._querySchemaModel.set({
        query: query
      });

      this._querySchemaModel.fetch({
        success: this._saveSQL.bind(this)
      });
    }
  },

  _showErrors: function (model) {
    var errors = this._querySchemaModel.get('query_errors');
    this._codemirrorModel.set('errors', this._parseErrors(errors));

    if (errors && errors.length > 0) {
      Notifier.addNotification({
        status: 'error',
        info: _t('editor.data.notifier.sql-error'),
        closable: true,
        delay: 10000
      });
    }
  },

  _parseErrors: function (errors) {
    return errors.map(function (error) {
      return {
        message: error
      };
    });
  },

  _saveSQL: function () {
    var query = this._codemirrorModel.get('content');
    this._sqlModel.set('content', query);
    this._userActions.saveAnalysisSourceQuery(query, this._nodeModel, this._layerDefinitionModel);
    this._querySchemaModel.set('query_errors', []);

    Notifier.addNotification({
      status: 'success',
      info: _t('editor.data.notifier.sql-success'),
      closable: true,
      delay: 10000
    });

    this._checkClearButton();
  },

  _applyDefaultSQL: function () {
    var originalQuery = this._defaultSQL();
    this._codemirrorModel.set({ content: originalQuery });
    this._sqlModel.set('content', originalQuery);
    this._userActions.saveAnalysisSourceQuery(originalQuery, this._nodeModel, this._layerDefinitionModel);
    this._querySchemaModel.set('query_errors', []);
    this._clearSQLModel.set({ visible: false });
    this._querySchemaModel.resetDueToAlteredData();
  },

  _checkClearButton: function () {
    var custom_sql = this._codemirrorModel.get('content').toLowerCase();
    var default_sql = this._defaultSQL().toLowerCase();
    this._clearSQLModel.set({visible: custom_sql !== default_sql});
  },

  _clearSQL: function () {
    var sql = this._defaultSQL();
    this._codemirrorModel.set({content: sql});
    this._saveSQL();
  },

  _defaultSQL: function () {
    return 'SELECT * FROM ' + this._layerDefinitionModel.getTableName();
  },

  _hasAnalysisApplied: function () {
    return this._nodeModel.get('type') !== 'source';
  },

  _onChangeEdition: function () {
    var edition = this._editorModel.get('edition');
    var isAnalysis = this._hasAnalysisApplied();

    if (edition && isAnalysis) {
      this._codemirrorModel.set({readonly: true});
      this._infoboxModel.set({state: 'readonly'});
    } else {
      this._codemirrorModel.set({readonly: false});
      this._infoboxModel.set({state: ''});
    }

    var index = edition ? 1 : 0;
    this._collectionPane.at(index).set({ selected: true });
  },

  _configPanes: function () {
    var self = this;
    var tabPaneTabs = [{
      selected: !this._editorModel.get('edition'),
      createContentView: function () {
        return new ScrollView({
          createContentView: function () {
            return new DataContentView({
              className: 'Editor-content',
              stackLayoutModel: self._stackLayoutModel,
              widgetDefinitionsCollection: self._widgetDefinitionsCollection,
              columnsModel: self._columnsModel,
              userActions: self._userActions,
              infoboxModel: self._infoboxModel
            });
          }
        });
      },
      createActionView: function () {
        return new CoreView();
      }
    }, {
      selected: this._editorModel.get('edition'),
      createContentView: function () {
        return new DataSQLView({
          layerDefinitionModel: self._layerDefinitionModel,
          codemirrorModel: self._codemirrorModel,
          onApplyEvent: self._parseSQL.bind(self)
        });
      },
      createActionView: function () {
        var isAnalysis = self._hasAnalysisApplied();
        if (!isAnalysis) {
          self._checkClearButton();
          return new UndoButtons({
            trackModel: self._sqlModel,
            editorModel: self._editorModel,
            clearModel: self._clearSQLModel,
            applyButton: true,
            clearButton: true,
            onApplyClick: self._parseSQL.bind(self),
            onClearClick: self._clearSQL.bind(self)
          });
        }
      }
    }];

    this._collectionPane = new TabPaneCollection(tabPaneTabs);
  },

  _confirmReadOnly: function () {
    this._infoboxModel.set({state: ''});
  },

  _initViews: function () {
    var self = this;

    var infoboxSstates = [
      {
        state: 'readonly',
        createContentView: function () {
          return Infobox.createConfirm({
            type: 'code',
            title: _t('editor.data.messages.sql-readonly.title'),
            body: _t('editor.data.messages.sql-readonly.body'),
            confirmLabel: _t('editor.data.messages.sql-readonly.accept')
          });
        },
        mainAction: self._confirmReadOnly.bind(self)
      },
      {
        state: 'no-data',
        createContentView: function () {
          return Infobox.createInfo({
            type: 'alert',
            title: _t('editor.data.messages.empty-data.title'),
            body: _t('editor.data.messages.empty-data.body')
          });
        },
        mainAction: self._confirmReadOnly.bind(self)
      }
    ];

    var infoboxCollection = new InfoboxCollection(infoboxSstates);

    var panelWithOptionsView = new PanelWithOptionsView({
      className: 'Editor-content',
      editorModel: self._editorModel,
      infoboxModel: self._infoboxModel,
      infoboxCollection: infoboxCollection,
      createContentView: function () {
        return new TabPaneView({
          collection: self._collectionPane
        });
      },
      createControlView: function () {
        return new Toggler({
          editorModel: self._editorModel,
          labels: [_t('editor.data.data-toggle.values'), _t('editor.data.data-toggle.cartocss')]
        });
      },
      createActionView: function () {
        return new TabPaneView({
          collection: self._collectionPane,
          createContentKey: 'createActionView'
        });
      }
    });

    this.$el.append(panelWithOptionsView.render().el);
    this.addView(panelWithOptionsView);
  }

});
<commit_msg>Fixed linter<commit_after>var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var PanelWithOptionsView = require('../../../../components/view-options/panel-with-options-view');
var ScrollView = require('../../../../components/scroll/scroll-view');
var DataContentView = require('./data-content-view');
var DataSQLView = require('./data-sql-view');
var TabPaneView = require('../../../../components/tab-pane/tab-pane-view');
var TabPaneCollection = require('../../../../components/tab-pane/tab-pane-collection');
var Toggler = require('../../../../components/toggler/toggler-view');
var UndoButtons = require('../../../../components/undo-redo/undo-redo-view');
var Infobox = require('../../../../components/infobox/infobox-factory');
var InfoboxModel = require('../../../../components/infobox/infobox-model');
var InfoboxCollection = require('../../../../components/infobox/infobox-collection');
var TableStats = require('../../../../components/modals/add-widgets/tablestats');
var DataColumnsModel = require('./data-columns-model');
var Notifier = require('../../../../components/notifier/notifier');
var SQLUtils = require('../../../../helpers/sql-utils');
var cdb = require('cartodb.js');

module.exports = CoreView.extend({

  initialize: function (opts) {
    if (!opts.widgetDefinitionsCollection) throw new Error('widgetDefinitionsCollection is required');
    if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.configModel) throw new Error('configModel is required');
    if (!opts.stackLayoutModel) throw new Error('StackLayoutModel is required');
    if (!opts.userActions) throw new Error('userActions is required');

    this._layerDefinitionModel = opts.layerDefinitionModel;
    this._widgetDefinitionsCollection = opts.widgetDefinitionsCollection;

    this._userActions = opts.userActions;
    this._configModel = opts.configModel;
    this._editorModel = opts.editorModel;
    this._stackLayoutModel = opts.stackLayoutModel;
    this._nodeModel = this._layerDefinitionModel.getAnalysisDefinitionNodeModel();
    this._querySchemaModel = this._nodeModel.querySchemaModel;

    this._clearSQLModel = new Backbone.Model({
      visible: false
    });

    this._sqlModel = this._layerDefinitionModel.sqlModel;

    this._SQL = new cdb.SQL({
      user: this._configModel.get('user_name'),
      sql_api_template: this._configModel.get('sql_api_template'),
      api_key: this._configModel.get('api_key')
    });

    this._infoboxModel = new InfoboxModel({
      state: ''
    });

    this._tableStats = new TableStats({
      configModel: this._configModel
    });

    this._columnsModel = new DataColumnsModel({}, {
      layerDefinitionModel: this._layerDefinitionModel,
      widgetDefinitionsCollection: this._widgetDefinitionsCollection,
      tableStats: this._tableStats
    });

    this._codemirrorModel = new Backbone.Model({
      content: this._querySchemaModel.get('query'),
      readonly: false
    });

    this._configPanes();
    this._initBinds();
    this._initData();
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    return this;
  },

  _initData: function () {
    if (!this._hasFetchedQuerySchema()) {
      this._querySchemaModel.fetch();
    } else {
      this._onQuerySchemaStatusChange();
    }
  },

  _onQuerySchemaChange: function () {
    if (this._hasFetchedQuerySchema()) {
      this._codemirrorModel.set({content: this._querySchemaModel.get('query')});
    }
  },

  _onQuerySchemaStatusChange: function () {
    if (this._hasFetchedQuerySchema()) {
      this._columnsModel.createColumnCollection();
    }
  },

  _hasFetchedQuerySchema: function () {
    return this._querySchemaModel.get('status') === 'fetched';
  },

  _initBinds: function () {
    this.listenTo(this._editorModel, 'change:edition', this._onChangeEdition);
    this.add_related_model(this._editorModel);

    this._querySchemaModel.on('change:query', this._onQuerySchemaChange, this);
    this._querySchemaModel.on('change:status', this._onQuerySchemaStatusChange, this);
    this._querySchemaModel.on('change:query_errors', this._showErrors, this);
    this.add_related_model(this._querySchemaModel);

    this._sqlModel.bind('undo redo', function () {
      this._codemirrorModel.set('content', this._sqlModel.get('content'));
    }, this);
    this.add_related_model(this._sqlModel);
  },

  _parseSQL: function () {
    var query = this._codemirrorModel.get('content');
    var altersData = SQLUtils.altersData(query);

    if (altersData) {
      var notification = Notifier.addNotification({
        status: 'loading',
        info: _t('editor.data.notifier.sql-alter-loading'),
        closable: false
      });

      this._sqlModel.set('content', query);

      this._SQL.execute(query, null, {
        success: function () {
          notification.set({
            status: 'success',
            info: _t('editor.data.notifier.sql-alter-success'),
            closable: true
          });
          this._applyDefaultSQL();
        }.bind(this),
        error: function (errors) {
          Notifier.removeNotification(notification);
          this._codemirrorModel.set('errors', this._parseErrors(errors));
        }.bind(this)
      });
    } else {
      // Parser errors SQL here and saving
      this._querySchemaModel.set({
        query: query
      });

      this._querySchemaModel.fetch({
        success: this._saveSQL.bind(this)
      });
    }
  },

  _showErrors: function (model) {
    var errors = this._querySchemaModel.get('query_errors');
    this._codemirrorModel.set('errors', this._parseErrors(errors));

    if (errors && errors.length > 0) {
      Notifier.addNotification({
        status: 'error',
        info: _t('editor.data.notifier.sql-error'),
        closable: true,
        delay: 10000
      });
    }
  },

  _parseErrors: function (errors) {
    return errors.map(function (error) {
      return {
        message: error
      };
    });
  },

  _saveSQL: function () {
    var query = this._codemirrorModel.get('content');
    this._sqlModel.set('content', query);
    this._userActions.saveAnalysisSourceQuery(query, this._nodeModel, this._layerDefinitionModel);
    this._querySchemaModel.set('query_errors', []);

    Notifier.addNotification({
      status: 'success',
      info: _t('editor.data.notifier.sql-success'),
      closable: true,
      delay: 10000
    });

    this._checkClearButton();
  },

  _applyDefaultSQL: function () {
    var originalQuery = this._defaultSQL();
    this._codemirrorModel.set({ content: originalQuery });
    this._sqlModel.set('content', originalQuery);
    this._userActions.saveAnalysisSourceQuery(originalQuery, this._nodeModel, this._layerDefinitionModel);
    this._querySchemaModel.set('query_errors', []);
    this._clearSQLModel.set({ visible: false });
    this._querySchemaModel.resetDueToAlteredData();
  },

  _checkClearButton: function () {
    var custom_sql = this._codemirrorModel.get('content').toLowerCase();
    var default_sql = this._defaultSQL().toLowerCase();
    this._clearSQLModel.set({visible: custom_sql !== default_sql});
  },

  _clearSQL: function () {
    var sql = this._defaultSQL();
    this._codemirrorModel.set({content: sql});
    this._saveSQL();
  },

  _defaultSQL: function () {
    return 'SELECT * FROM ' + this._layerDefinitionModel.getTableName();
  },

  _hasAnalysisApplied: function () {
    return this._nodeModel.get('type') !== 'source';
  },

  _onChangeEdition: function () {
    var edition = this._editorModel.get('edition');
    var isAnalysis = this._hasAnalysisApplied();

    if (edition && isAnalysis) {
      this._codemirrorModel.set({readonly: true});
      this._infoboxModel.set({state: 'readonly'});
    } else {
      this._codemirrorModel.set({readonly: false});
      this._infoboxModel.set({state: ''});
    }

    var index = edition ? 1 : 0;
    this._collectionPane.at(index).set({ selected: true });
  },

  _configPanes: function () {
    var self = this;
    var tabPaneTabs = [{
      selected: !this._editorModel.get('edition'),
      createContentView: function () {
        return new ScrollView({
          createContentView: function () {
            return new DataContentView({
              className: 'Editor-content',
              stackLayoutModel: self._stackLayoutModel,
              widgetDefinitionsCollection: self._widgetDefinitionsCollection,
              columnsModel: self._columnsModel,
              userActions: self._userActions,
              infoboxModel: self._infoboxModel
            });
          }
        });
      },
      createActionView: function () {
        return new CoreView();
      }
    }, {
      selected: this._editorModel.get('edition'),
      createContentView: function () {
        return new DataSQLView({
          layerDefinitionModel: self._layerDefinitionModel,
          codemirrorModel: self._codemirrorModel,
          onApplyEvent: self._parseSQL.bind(self)
        });
      },
      createActionView: function () {
        var isAnalysis = self._hasAnalysisApplied();
        if (!isAnalysis) {
          self._checkClearButton();
          return new UndoButtons({
            trackModel: self._sqlModel,
            editorModel: self._editorModel,
            clearModel: self._clearSQLModel,
            applyButton: true,
            clearButton: true,
            onApplyClick: self._parseSQL.bind(self),
            onClearClick: self._clearSQL.bind(self)
          });
        }
      }
    }];

    this._collectionPane = new TabPaneCollection(tabPaneTabs);
  },

  _confirmReadOnly: function () {
    this._infoboxModel.set({state: ''});
  },

  _initViews: function () {
    var self = this;

    var infoboxSstates = [
      {
        state: 'readonly',
        createContentView: function () {
          return Infobox.createConfirm({
            type: 'code',
            title: _t('editor.data.messages.sql-readonly.title'),
            body: _t('editor.data.messages.sql-readonly.body'),
            confirmLabel: _t('editor.data.messages.sql-readonly.accept')
          });
        },
        mainAction: self._confirmReadOnly.bind(self)
      },
      {
        state: 'no-data',
        createContentView: function () {
          return Infobox.createInfo({
            type: 'alert',
            title: _t('editor.data.messages.empty-data.title'),
            body: _t('editor.data.messages.empty-data.body')
          });
        },
        mainAction: self._confirmReadOnly.bind(self)
      }
    ];

    var infoboxCollection = new InfoboxCollection(infoboxSstates);

    var panelWithOptionsView = new PanelWithOptionsView({
      className: 'Editor-content',
      editorModel: self._editorModel,
      infoboxModel: self._infoboxModel,
      infoboxCollection: infoboxCollection,
      createContentView: function () {
        return new TabPaneView({
          collection: self._collectionPane
        });
      },
      createControlView: function () {
        return new Toggler({
          editorModel: self._editorModel,
          labels: [_t('editor.data.data-toggle.values'), _t('editor.data.data-toggle.cartocss')]
        });
      },
      createActionView: function () {
        return new TabPaneView({
          collection: self._collectionPane,
          createContentKey: 'createActionView'
        });
      }
    });

    this.$el.append(panelWithOptionsView.render().el);
    this.addView(panelWithOptionsView);
  }

});
<|endoftext|>


<commit_before>/**
 * Slideshow plugin for jQuery.
 *
 * Transitions are done using CSS3 with progressive fallback to jQuery fadeIn.
 *
 * @dependencies jQuery, Modernizr
 * @author Chiel Robben <chiel@pephers.org>
 * @url https://github.com/Pephers/Slideshow
 * @license MIT
 */
(function ($, Modernizr, window, undefined) {

    'use strict';

    /**
     * Constructor
     *
     * @param {object} element
     * @param {object} options
     */
    var Slideshow = function (element, options) {

        var defaults = {
            auto: true,
            interval: 5000,
            duration: 600,
            pause: true,
            zIndexOffset: 0,
            previous: undefined,
            next: undefined,
            onChange: undefined
        };

        this.$element = $(element);
        this.$window = $(window);
        this.$slides = this.$element.children();
        this.isRunning = undefined;
        this.slideCount = this.$slides.length - 1;
        this.currentSlide = 0;
        this.options = $.extend({}, defaults, options);

        if (this.slideCount > 0) {
            this.init();
        }

    };

    Slideshow.prototype = {

        /**
         * Initialize the slideshow
         */
        init: function () {

            var self = this;

            // Hide all images but the first one
            if (Modernizr.csstransitions) {
                self.$slides.eq(self.currentSlide).addClass('slide-active');
            } else {

                self.$slides.css(
                    'zIndex',
                    self.options.zIndexOffset + 1
                ).hide().eq(self.currentSlide).css(
                    'zIndex',
                    self.options.zIndexOffset + 2
                ).show();

            }

            // Start the slideshow on load
            self.$window.on('load', function () {

                self.$element.addClass('slideshow-ready');
                self.setHeight();
                self.start();

            });

            if (self.options.next) {

                self.options.next.on('click', function (e) {

                    self.nextSlide.call(self);

                    e.preventDefault();

                });

            }

            if (self.options.previous) {

                self.options.previous.on('click', function (e) {

                    self.previousSlide.call(self);

                    e.preventDefault();

                });

            }

            // Pause slideshow when the mouse cursor is hovering
            if (!Modernizr.touch && this.options.pause) {

                self.$element.on({

                    mouseenter: function (e) {
                        self.stop();
                    },

                    mouseleave: function (e) {
                        self.start();
                    }

                });

            }

            // Set height of the slideshow when window is resized
            self.$window.on('resize', function () {
                self.setHeight();
            });

        },

        /**
         * Start the slideshow
         */
        start: function () {

            var self = this;

            // Prevent multiple timers from running at once
            if (self.isRunning) {
                clearInterval(self.isRunning);
            }

            if (self.options.auto) {

                self.isRunning = setInterval(function () {
                    self.nextSlide();
                }, self.options.interval);

            }

        },

        /**
         * Stop the slideshow
         */
        stop: function () {
            clearInterval(this.isRunning);
        },

        /**
         * Slide to the next image
         */
        nextSlide: function () {

            var slide = this.currentSlide === this.slideCount ? 0 : this.currentSlide + 1;

            this.changeSlide(slide);

        },

        /**
         * Slide to the previous image
         */
        previousSlide: function () {

            var slide = this.currentSlide === 0 ? this.slideCount : this.currentSlide - 1;

            this.changeSlide(slide);

        },

        /**
         * Change to the slide specified.
         *
         * @param {int} slide
         */
        changeSlide: function (slide) {

            var self = this,
                previousSlide = slide > self.slideCount ? (self.slideCount - 1) : (slide <= 0 ? self.slideCount : (slide - 1));

            self.currentSlide = slide;

            if (Modernizr.csstransitions) {
                self.$slides.removeClass('slide-active').eq(self.currentSlide).addClass('slide-active');
            } else {

                self.$slides.css(
                    'zIndex',
                    self.options.zIndexOffset + 1
                ).eq(self.currentSlide).css(
                    'zIndex',
                    self.options.zIndexOffset + 2
                ).fadeIn(self.options.duration, function () {
                    self.$slides.eq(previousSlide).hide();
                });

            }

            // Execute callback function if set
            if (self.options.onChange) {
                self.options.onChange.call(self);
            }

        },

        /**
         * Set height of the slideshow container
         */
        setHeight: function () {

            var height = this.$slides.eq(this.currentSlide).height();

            this.$element[0].style.height = height + 'px';

        }

    };

    /**
     * Expose as jQuery plugin in Singleton fashion so it can only be
     * initialized once per element.
     */
    $.fn.slideshow = function (options) {

        return this.each(function () {

            if (!$.data(this, 'slideshow')) {
                $.data(this, 'slideshow', new Slideshow(this, options));
            }

        });

    };

})(jQuery, Modernizr, window);
<commit_msg>Reset interval after changing slide manually<commit_after>/**
 * Slideshow plugin for jQuery.
 *
 * Transitions are done using CSS3 with progressive fallback to jQuery fadeIn.
 *
 * @dependencies jQuery, Modernizr
 * @author Chiel Robben <chiel@pephers.org>
 * @url https://github.com/Pephers/Slideshow
 * @license MIT
 */
(function ($, Modernizr, window, undefined) {

    'use strict';

    /**
     * Constructor
     *
     * @param {object} element
     * @param {object} options
     */
    var Slideshow = function (element, options) {

        var defaults = {
            auto: true,
            interval: 5000,
            duration: 600,
            pause: true,
            zIndexOffset: 0,
            previous: undefined,
            next: undefined,
            onChange: undefined
        };

        this.$element = $(element);
        this.$window = $(window);
        this.$slides = this.$element.children();
        this.isRunning = undefined;
        this.slideCount = this.$slides.length - 1;
        this.currentSlide = 0;
        this.options = $.extend({}, defaults, options);

        if (this.slideCount > 0) {
            this.init();
        }

    };

    Slideshow.prototype = {

        /**
         * Initialize the slideshow
         */
        init: function () {

            var self = this;

            // Hide all images but the first one
            if (Modernizr.csstransitions) {
                self.$slides.eq(self.currentSlide).addClass('slide-active');
            } else {

                self.$slides.css(
                    'zIndex',
                    self.options.zIndexOffset + 1
                ).hide().eq(self.currentSlide).css(
                    'zIndex',
                    self.options.zIndexOffset + 2
                ).show();

            }

            // Start the slideshow on load
            self.$window.on('load', function () {

                self.$element.addClass('slideshow-ready');
                self.setHeight();
                self.start();

            });

            if (self.options.next) {

                self.options.next.on('click', function (e) {

                    self.nextSlide.call(self);

                    // Reset interval
                    self.start.call(self);

                    e.preventDefault();

                });

            }

            if (self.options.previous) {

                self.options.previous.on('click', function (e) {

                    self.previousSlide.call(self);

                    // Reset interval
                    self.start.call(self);

                    e.preventDefault();

                });

            }

            // Pause slideshow when the mouse cursor is hovering
            if (!Modernizr.touch && this.options.pause) {

                self.$element.on({

                    mouseenter: function (e) {
                        self.stop();
                    },

                    mouseleave: function (e) {
                        self.start();
                    }

                });

            }

            // Set height of the slideshow when window is resized
            self.$window.on('resize', function () {
                self.setHeight();
            });

        },

        /**
         * Start the slideshow
         */
        start: function () {

            var self = this;

            // Prevent multiple timers from running at once
            if (self.isRunning) {
                clearInterval(self.isRunning);
            }

            if (self.options.auto) {

                self.isRunning = setInterval(function () {
                    self.nextSlide();
                }, self.options.interval);

            }

        },

        /**
         * Stop the slideshow
         */
        stop: function () {
            clearInterval(this.isRunning);
        },

        /**
         * Slide to the next image
         */
        nextSlide: function () {

            var slide = this.currentSlide === this.slideCount ? 0 : this.currentSlide + 1;

            this.changeSlide(slide);

        },

        /**
         * Slide to the previous image
         */
        previousSlide: function () {

            var slide = this.currentSlide === 0 ? this.slideCount : this.currentSlide - 1;

            this.changeSlide(slide);

        },

        /**
         * Change to the slide specified.
         *
         * @param {int} slide
         */
        changeSlide: function (slide) {

            var self = this,
                previousSlide = slide > self.slideCount ? (self.slideCount - 1) : (slide <= 0 ? self.slideCount : (slide - 1));

            self.currentSlide = slide;

            if (Modernizr.csstransitions) {
                self.$slides.removeClass('slide-active').eq(self.currentSlide).addClass('slide-active');
            } else {

                self.$slides.css(
                    'zIndex',
                    self.options.zIndexOffset + 1
                ).eq(self.currentSlide).css(
                    'zIndex',
                    self.options.zIndexOffset + 2
                ).fadeIn(self.options.duration, function () {
                    self.$slides.eq(previousSlide).hide();
                });

            }

            // Execute callback function if set
            if (self.options.onChange) {
                self.options.onChange.call(self);
            }

        },

        /**
         * Set height of the slideshow container
         */
        setHeight: function () {

            var height = this.$slides.eq(this.currentSlide).height();

            this.$element[0].style.height = height + 'px';

        }

    };

    /**
     * Expose as jQuery plugin in Singleton fashion so it can only be
     * initialized once per element.
     */
    $.fn.slideshow = function (options) {

        return this.each(function () {

            if (!$.data(this, 'slideshow')) {
                $.data(this, 'slideshow', new Slideshow(this, options));
            }

        });

    };

})(jQuery, Modernizr, window);
<|endoftext|>


<commit_before>// TODO inject this dependency
var ADB = require('./ADB').getInstance();

var Worker = require('webworker-threads').Worker;
var colors = require('colors/safe');
var express = require('express');

var queue = [];

var worker = new Worker(function() {
  this.onmessage = function(event) {
    postMessage(event.data);
    //self.close();
  };
});

worker.onmessage = function(event) {
  if ("recipient" in event.data) queue.push(event.data);
  else if (queue.length) ADB.sms(queue.shift());
  else console.log("I'm done for now !");
};

var checkQueue = function() {
  worker.postMessage({
    message: "Checking queue ..."
  });
};

setInterval(checkQueue, 1000 * 10);

var app = express();

app.get('/sms/:recipient/:message', function(req, res) {
  console.log(colors.blue(JSON.stringify(req.params, null, 2)));
  worker.postMessage(req.params);
  res.send(req.params);
});

var server = app.listen(3000, function() {
  var host = server.address().address;
  var port = server.address().port;
  console.log(colors.green('listening at http://%s:%s'), host, port);
});

/*
var testPhone = process.argv.slice(2);
var id = setInterval(function(i) {
  return function() {
    if (i > 5) clearInterval(id);
    worker.postMessage({
      recipient: testPhone,
      message: 'test ' + (++i) + ' on 5'
    });
  };
}, 250);
*/
<commit_msg>changed to port 5555<commit_after>// TODO inject this dependency
var ADB = require('./ADB').getInstance();

var Worker = require('webworker-threads').Worker;
var colors = require('colors/safe');
var express = require('express');

var queue = [];

var worker = new Worker(function() {
  this.onmessage = function(event) {
    postMessage(event.data);
    //self.close();
  };
});

worker.onmessage = function(event) {
  if ("recipient" in event.data) queue.push(event.data);
  else if (queue.length) ADB.sms(queue.shift());
  else console.log("I'm done for now !");
};

var checkQueue = function() {
  worker.postMessage({
    message: "Checking queue ..."
  });
};

setInterval(checkQueue, 1000 * 10);

var app = express();

app.get('/sms/:recipient/:message', function(req, res) {
  console.log(colors.blue(JSON.stringify(req.params, null, 2)));
  worker.postMessage(req.params);
  res.send(req.params);
});

// TODO inject port
var server = app.listen(5555, function() {
  var host = server.address().address;
  var port = server.address().port;
  console.log(colors.green('listening at http://%s:%s'), host, port);
});

/*
var testPhone = process.argv.slice(2);
var id = setInterval(function(i) {
  return function() {
    if (i > 5) clearInterval(id);
    worker.postMessage({
      recipient: testPhone,
      message: 'test ' + (++i) + ' on 5'
    });
  };
}, 250);
*/
<|endoftext|>


<commit_before>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw, sync) {
      function getURL() {
        return url = API_URL + path;
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL(), !sync);
      if (!sync) {
        xhr.onreadystatechange = function () {
          if (this.readyState == 4) {
            if (this.status >= 200 && this.status < 300 || this.status === 304) {
              cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
            } else {
              cb({request: this, error: this.status});
            }
          }
        };
      }
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
      if (sync) return xhr.response;
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        var command = username ? "/users/"+username : "/user";

        _request("GET", command, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // Follow user
      // -------

      this.follow = function(username, cb) {
        _request("PUT", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Unfollow user
      // -------

      this.unfollow = function(username, cb) {
        _request("DELETE", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(branch, path, cb) {
        _request("GET", repoPath + "/contents/" + path + "?ref=" + branch, null, cb, 'raw');
      };

      this.contentsSync = function(branch, path) {
        return _request("GET", repoPath + "/contents/" + path + "?ref=" + branch, null, null, 'raw', true);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path; });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Create the gist
      // --------
      // {
      //  "description": "the description for this gist",
      //    "public": true,
      //    "files": {
      //      "file1.txt": {
      //        "content": "String file contents"
      //      }
      //    }
      // }

      this.create = function(options, cb){
        _request("POST","/gists", options, cb);
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);
<commit_msg>parse link header async, cb with ALL org repos<commit_after>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw, sync) {
      function getURL() {
        return url = API_URL + path;
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL(), !sync);
      if (!sync) {
        xhr.onreadystatechange = function () {
          if (this.readyState == 4) {
            if (this.status >= 200 && this.status < 300 || this.status === 304) {
              cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true, this);
            } else {
              cb({request: this, error: this.status});
            }
          }
        };
      }
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
      if (sync) return xhr.response;
    }

    function _parseLinkHeader(err, response, xhr, cb) {
      var link = xhr.getResponseHeader('link');

      if (!err && link) {
        var parts = link.split(',');
        var length = parts.length;

        var links = {};

        var section;
        var url;
        var name;

        for (var i = 0; i < length; i++) {
          section = parts[i].split(';');

          if (section.length !== 2) {
            throw new Error('section could not be split on ';'');
          }

          url = section[0].replace(/<(.*)>/, '$1').trim();
          name = section[1].replace(/rel="(.*)"/, '$1').trim();

          links[name] = url;
        }

        if (links['next']) {
          _request('GET', links['next'].split(API_URL)[1], null, function(err, res, xhr) {
            if (typeof response.concat === 'function') {
              response = response.concat(res);
            } else if (typeof response === 'string') {
              response += res;
            }

            _parseLinkHeader(err, response, xhr, cb);
          });
        } else {
          cb(err, response);
        }
      } else {
        cb(err, response);
      }
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        var command = username ? "/users/"+username : "/user";

        _request("GET", command, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res, xhr) {
          _parseLinkHeader(err, res, xhr, cb);
        });
      };

      // Follow user
      // -------

      this.follow = function(username, cb) {
        _request("PUT", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Unfollow user
      // -------

      this.unfollow = function(username, cb) {
        _request("DELETE", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(branch, path, cb) {
        _request("GET", repoPath + "/contents/" + path + "?ref=" + branch, null, cb, 'raw');
      };

      this.contentsSync = function(branch, path) {
        return _request("GET", repoPath + "/contents/" + path + "?ref=" + branch, null, null, 'raw', true);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path; });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Create the gist
      // --------
      // {
      //  "description": "the description for this gist",
      //    "public": true,
      //    "files": {
      //      "file1.txt": {
      //        "content": "String file contents"
      //      }
      //    }
      // }

      this.create = function(options, cb){
        _request("POST","/gists", options, cb);
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const j = require('../../lib/transform');
const randomstring = require('randomstring');

const Generator = require('../../lib/generator');
const OAUTH2_STRATEGY_MAPPINGS = {
  google: 'passport-google-oauth20',
  facebook: 'passport-facebook',
  github: 'passport-github'
};

module.exports = class AuthGenerator extends Generator {
  prompting() {
    const prompts = [{
      type: 'checkbox',
      name: 'strategies',
      message: 'What authentication providers do you want to use? Other PassportJS strategies not in this list can still be configured manually.',
      default: 'providers',
      choices: [{
        name: 'Username + Password (Local)',
        value: 'local'
      }, {
        name: 'Google',
        value: 'google'
      }, {
        name: 'Facebook',
        value: 'facebook'
      }, {
        name: 'GitHub',
        value: 'github'
      }]
    }, {
      name: 'entity',
      message: 'What is the name of the user (entity) service?',
      default: 'users'
    }];

    return this.prompt(prompts).then(props => {
      this.props = Object.assign(this.props, props);
    });
  }

  _transformCode(code) {
    const ast = j(code);
    const appDeclaration = ast.findDeclaration('app');
    const configureServices = ast.findConfigure('services');
    const requireCall = 'const authentication = require(\'./authentication\');';

    if (appDeclaration.length === 0) {
      throw new Error('Could not find \'app\' variable declaration in app.js to insert database configuration. Did you modify app.js?');
    }

    if (configureServices.length === 0) {
      throw new Error('Could not find .configure(services) call in app.js after which to insert database configuration. Did you modify app.js?');
    }

    appDeclaration.insertBefore(requireCall);
    configureServices.insertBefore('app.configure(authentication);');

    return ast.toSource();
  }

  _writeConfiguration(context) {
    const config = Object.assign({}, this.defaultConfig);

    config.authentication = {
      secret: randomstring.generate(64),
      strategies: [ 'jwt' ],
      path: '/authentication',
      service: context.kebabEntity
    };

    if (context.strategies.indexOf('local') !== -1) {
      config.authentication.strategies.push('local');
    }

    context.strategies.forEach(strategy => {
      if (OAUTH2_STRATEGY_MAPPINGS[strategy]) {
        const strategyConfig = {
          clientID: `your ${strategy} client id`,
          clientSecret: `your ${strategy} client secret`
        };

        if (strategy === 'facebook') {
          strategyConfig.scope = ['public_profile', 'email'];
        }

        config.authentication[strategy] = strategyConfig;
      }
    });

    this.conflicter.force = true;
    this.fs.writeJSON(
      this.destinationPath('config', 'default.json'),
      config
    );
  }

  writing() {
    const dependencies = [ 'feathers-authentication@pre', 'feathers-authentication-jwt' ];
    const context = Object.assign({
      kebabEntity: _.kebabCase(this.props.entity),
      camelEntity: _.camelCase(this.props.entity),
      oauthProviders: []
    }, this.props);

    // Set up strategies and add dependencies
    this.props.strategies.forEach(strategy => {
      const oauthProvider = OAUTH2_STRATEGY_MAPPINGS[strategy];

      if (oauthProvider) {
        dependencies.push('feathers-authentication-oauth2');
        dependencies.push(oauthProvider);
        context.oauthProviders.push({
          name: strategy,
          strategyName: `${_.upperFirst(strategy)}Strategy`,
          module: oauthProvider
        });
      } else {
        dependencies.push(`feathers-authentication-${strategy}`);
      }
    });

    // Create the users service
    this.composeWith(require.resolve('../service'), {
      props: {
        name: context.entity,
        path: `/${context.kebabEntity}`,
        authentication: context
      }
    });

    // If the file doesn't exist yet, add it to the app.js
    if (!this.fs.exists(this.destinationPath(this.libDirectory, 'authentication.js'))) {
      const appjs = this.destinationPath(this.libDirectory, 'app.js');

      this.conflicter.force = true;
      this.fs.write(appjs, this._transformCode(
        this.fs.read(appjs).toString()
      ));
    }

    this.fs.copyTpl(
      this.templatePath('authentication.js'),
      this.destinationPath(this.libDirectory, 'authentication.js'),
      context
    );

    this._writeConfiguration(context);
    this._packagerInstall(dependencies, {
      save: true
    });
  }
};
<commit_msg>Add profileFields for Facebook authentication (#155)<commit_after>'use strict';

const _ = require('lodash');
const j = require('../../lib/transform');
const randomstring = require('randomstring');

const Generator = require('../../lib/generator');
const OAUTH2_STRATEGY_MAPPINGS = {
  google: 'passport-google-oauth20',
  facebook: 'passport-facebook',
  github: 'passport-github'
};

module.exports = class AuthGenerator extends Generator {
  prompting() {
    const prompts = [{
      type: 'checkbox',
      name: 'strategies',
      message: 'What authentication providers do you want to use? Other PassportJS strategies not in this list can still be configured manually.',
      default: 'providers',
      choices: [{
        name: 'Username + Password (Local)',
        value: 'local'
      }, {
        name: 'Google',
        value: 'google'
      }, {
        name: 'Facebook',
        value: 'facebook'
      }, {
        name: 'GitHub',
        value: 'github'
      }]
    }, {
      name: 'entity',
      message: 'What is the name of the user (entity) service?',
      default: 'users'
    }];

    return this.prompt(prompts).then(props => {
      this.props = Object.assign(this.props, props);
    });
  }

  _transformCode(code) {
    const ast = j(code);
    const appDeclaration = ast.findDeclaration('app');
    const configureServices = ast.findConfigure('services');
    const requireCall = 'const authentication = require(\'./authentication\');';

    if (appDeclaration.length === 0) {
      throw new Error('Could not find \'app\' variable declaration in app.js to insert database configuration. Did you modify app.js?');
    }

    if (configureServices.length === 0) {
      throw new Error('Could not find .configure(services) call in app.js after which to insert database configuration. Did you modify app.js?');
    }

    appDeclaration.insertBefore(requireCall);
    configureServices.insertBefore('app.configure(authentication);');

    return ast.toSource();
  }

  _writeConfiguration(context) {
    const config = Object.assign({}, this.defaultConfig);

    config.authentication = {
      secret: randomstring.generate(64),
      strategies: [ 'jwt' ],
      path: '/authentication',
      service: context.kebabEntity
    };

    if (context.strategies.indexOf('local') !== -1) {
      config.authentication.strategies.push('local');
    }

    context.strategies.forEach(strategy => {
      if (OAUTH2_STRATEGY_MAPPINGS[strategy]) {
        const strategyConfig = {
          clientID: `your ${strategy} client id`,
          clientSecret: `your ${strategy} client secret`
        };

        if (strategy === 'facebook') {
          strategyConfig.scope = ['public_profile', 'email'];
          strategyConfig.profileFields = ['id', 'displayName', 'first_name', 'last_name', 'email', 'gender', 'profileUrl', 'birthday', 'picture', 'permissions'];
        }

        config.authentication[strategy] = strategyConfig;
      }
    });

    this.conflicter.force = true;
    this.fs.writeJSON(
      this.destinationPath('config', 'default.json'),
      config
    );
  }

  writing() {
    const dependencies = [ 'feathers-authentication@pre', 'feathers-authentication-jwt' ];
    const context = Object.assign({
      kebabEntity: _.kebabCase(this.props.entity),
      camelEntity: _.camelCase(this.props.entity),
      oauthProviders: []
    }, this.props);

    // Set up strategies and add dependencies
    this.props.strategies.forEach(strategy => {
      const oauthProvider = OAUTH2_STRATEGY_MAPPINGS[strategy];

      if (oauthProvider) {
        dependencies.push('feathers-authentication-oauth2');
        dependencies.push(oauthProvider);
        context.oauthProviders.push({
          name: strategy,
          strategyName: `${_.upperFirst(strategy)}Strategy`,
          module: oauthProvider
        });
      } else {
        dependencies.push(`feathers-authentication-${strategy}`);
      }
    });

    // Create the users service
    this.composeWith(require.resolve('../service'), {
      props: {
        name: context.entity,
        path: `/${context.kebabEntity}`,
        authentication: context
      }
    });

    // If the file doesn't exist yet, add it to the app.js
    if (!this.fs.exists(this.destinationPath(this.libDirectory, 'authentication.js'))) {
      const appjs = this.destinationPath(this.libDirectory, 'app.js');

      this.conflicter.force = true;
      this.fs.write(appjs, this._transformCode(
        this.fs.read(appjs).toString()
      ));
    }

    this.fs.copyTpl(
      this.templatePath('authentication.js'),
      this.destinationPath(this.libDirectory, 'authentication.js'),
      context
    );

    this._writeConfiguration(context);
    this._packagerInstall(dependencies, {
      save: true
    });
  }
};
<|endoftext|>


<commit_before>/**
 * @copyright 2015, Prometheus Research, LLC
 */

import React, {PropTypes}   from 'react';
import WithFormValue        from './WithFormValue';
import Value                from './Value';
import Input                from './Input';
import ErrorList            from './ErrorList';

function renderLabel(label, schema) {
  return label && {label};
}

function renderErrorList(formValue) {
  return <ErrorList formValue={formValue} />;
}

@WithFormValue
export default class Field extends React.Component {

  static propTypes = {
    label: PropTypes.string,
    children: PropTypes.element,
    formValue: PropTypes.instanceOf(Value),
    renderLabel: PropTypes.func,
    renderErrorList: PropTypes.func
  };

  static defaultProps = {
    children: <Input type="text" />,
    renderLabel,
    renderErrorList
  };

  constructor(props) {
    super(props);
    this.state = {dirty: false};
  }

  render() {
    let {children, renderLabel, renderErrorList, formValue} = this.props;
    let {dirty} = this.state;
    let {schema, value, errors, params} = this.props.formValue;
    let showErrors = dirty || params.forceShowErrors;
    children = React.cloneElement(
      React.Children.only(children),
      {value, onChange: this.onChange});
    let label = this.props.label || schema.label;
    return (

        {renderLabel(label, schema)}
        {children}
        {showErrors && renderErrorList(formValue)}

    );
  }

  onBlur = () => {
    this.setState({dirty: true});
  }

  onChange = (e) => {
    let value;
    if (e && e.target && e.target.value !== undefined) {
      e.stopPropagation();
      value = e.target.value;
      if (value === '') {
        value = undefined;
      }
    } else {
      value = e;
    }
    this.setState({dirty: true});
    this.props.formValue.set(value);
  }
}
<commit_msg><Field />: implementation uses <Component /> directly<commit_after>/**
 * @copyright 2015, Prometheus Research, LLC
 */

import React, {PropTypes}   from 'react';
import Value                from './Value';
import Input                from './Input';
import ErrorList            from './ErrorList';
import Component            from './Component';

function renderLabel(label, schema) {
  return label && {label};
}

function renderErrorList(formValue) {
  return <ErrorList formValue={formValue} />;
}

export default class Field extends Component {

  static propTypes = {
    ...Component.propTypes,
    label: PropTypes.string,
    children: PropTypes.element,
    renderLabel: PropTypes.func,
    renderErrorList: PropTypes.func
  };

  static defaultProps = {
    children: <Input type="text" />,
    renderLabel,
    renderErrorList
  };

  constructor(props) {
    super(props);
    this.state = {dirty: false};
  }

  render() {
    let {children, renderLabel, renderErrorList} = this.props;
    let {dirty} = this.state;
    let {schema, value, errors, params} = this.formValue;
    let showErrors = dirty || params.forceShowErrors;
    children = React.cloneElement(
      React.Children.only(children),
      {value, onChange: this.onChange});
    let label = this.props.label || schema.label;
    return (

        {renderLabel(label, schema)}
        {children}
        {showErrors && renderErrorList(this.formValue)}

    );
  }

  onBlur = () => {
    this.setState({dirty: true});
  }

  onChange = (e) => {
    let value;
    if (e && e.target && e.target.value !== undefined) {
      e.stopPropagation();
      value = e.target.value;
      if (value === '') {
        value = undefined;
      }
    } else {
      value = e;
    }
    this.setState({dirty: true});
    this.props.formValue.set(value);
  }
}
<|endoftext|>


<commit_before>var fs = require('fs')
var format = require('util').format
var https = require('https')
var path = require('path')

module.exports = function getVersions (options) {
  var distributionListingUri = options.baseUrl + 'index.json'

  https.get(distributionListingUri, function (res) {
    if (res.statusCode !== 200) return this.emit('error', res)

    var responseData = ''

    res
    .on('data', function (data) {
      responseData = responseData + data
    })
    .on('end', function () {
      JSON.parse(responseData)
        .map(function (build) {
          return Object.assign(Object.create(Build), {
            baseUrl: options.baseUrl,
            prefix: options.prefix || '',
            version: build.version
          })
        })
        .filter(function (build) {
          return !build.fileExists || options.overwrite
        })
        .forEach(function (build) {
          getShasum(build, writeFile)
        })
    })
    .on('error', this.emit.bind(this, 'error'))
  }).on('error', function (e) { console.error('Error with distribution listing', e.message) })
}

// private

var Build = {
  get basename () {
    return this.prefix + this.version.replace(/v/, '')
  },
  get filename () {
    return path.join(__dirname, '../share/node-build', this.basename)
  },
  get fileExists () {
    return fs.existsSync(this.filename)
  },
  get shasumFileUri () {
    return format('%s%s/SHASUMS256.txt', this.baseUrl, this.version)
  },
  get definition () {
    return format('install_package "%s" "%s"\n', this.name, this.downloadUri)
  },
  get downloadUri () {
    return format('%s%s/%s#%s', this.baseUrl, this.version, this.package, this.shasum)
  }
}

function getShasum (build, cb) {
  https.get(build.shasumFileUri, function (res) {
    if (res.statusCode !== 200) return this.emit('error', res)

    var shasumData = ''

    res
    .on('data', function (data) {
      shasumData = shasumData + data
    })
    .on('end', function () {
      var result = shasumData.match(/(\w{64}) {2}(?:\.\/)?(((?:node|iojs)-v\d+\.\d+\.\d+).tar.gz)/i)

      if (result) {
        build.shasum = result[1]
        build.package = result[2]
        build.name = result[3]

        cb(null, build)
      } else {
        cb(shasumData)
      }
    })
    .on('error', this.emit.bind(this, 'error'))
  }).on('error', function (e) { console.error('Error with ', build.version, e.message) })
}

function writeFile (err, build) {
  if (err) return console.error(err)

  fs.writeFile(build.filename, build.definition, function (err) {
    if (err) return console.error(err)

    console.log(build.name + ' written')
  })
}
<commit_msg>include binary distributions in definition file<commit_after>var fs = require('fs')
var format = require('util').format
var https = require('https')
var path = require('path')

module.exports = function getVersions (options) {
  var distributionListingUri = options.baseUrl + 'index.json'

  https.get(distributionListingUri, function (res) {
    if (res.statusCode !== 200) return this.emit('error', res)

    var responseData = ''

    res
    .on('data', function (data) {
      responseData = responseData + data
    })
    .on('end', function () {
      var self = this;
      JSON.parse(responseData)
        .map(function (build) {
          return Object.assign(Object.create(Build), {
            baseUrl: options.baseUrl,
            binaries: [],
            prefix: options.prefix || '',
            version: build.version
          })
        })
        .filter(function (build) {
          return !build.fileExists || options.overwrite
        })
        .forEach(function (build) {
          getChecksumsFile(build, function(err, shasumData) {
            extractShasums(build, shasumData, writeFile)
          })
        })
    })
    .on('error', this.emit.bind(this, 'error'))
  }).on('error', function (e) { console.error('Error with distribution listing', e.message) })
}

// private

var Build = {
  get basename () {
    return this.prefix + this.version.replace(/v/, '')
  },
  get filename () {
    return path.join(__dirname, '../share/node-build', this.basename)
  },
  get fileExists () {
    return fs.existsSync(this.filename)
  },
  get shasumFileUri () {
    return format('%s%s/SHASUMS256.txt', this.baseUrl, this.version)
  },
  get definition () {
    return format('%sinstall_package "%s" "%s"\n', this.distros, this.name, this.downloadUri)
  },
  get distros () {
    return this.binaries.map(function(binary){ return binary.definition }).join('') + (this.binaries.length ? '\n' : '')
  },
  get downloadUri () {
    return format('%s%s/%s#%s', this.baseUrl, this.version, this.package, this.shasum)
  }
}

var Binary = {
  get definition () {
    return format('distro %s "%s"\n', this.platform, this.downloadUri)
  },
  get downloadUri () {
    return format('%s%s/%s#%s', this.build.baseUrl, this.build.version, this.package, this.shasum)
  }
}

function getChecksumsFile (build, cb) {
  https.get(build.shasumFileUri, function (res) {
    if (res.statusCode !== 200) return this.emit('error', res)

    var shasumData = ''

    res
    .on('data', function (data) {
      shasumData = shasumData + data
    })
    .on('end', function () {
      cb(null, shasumData)
    })
    .on('error', this.emit.bind(this, 'error'))
  }).on('error', function (e) { console.error('Error with ', build.version, e.message) })
}

function extractShasums (build, shasumData, cb) {
  try {
    extractSourceChecksum(build, shasumData)
    extractBinaryChecksums(build, shasumData)
    cb(null, build)
  } catch (error) {
    cb(err)
  }
}

function extractSourceChecksum (build, shasumData) {
  var result = shasumData.match(/^(\w{64}) {2}(?:\.\/)?(((?:node|iojs)-v\d+\.\d+\.\d+).tar.gz)$/im)

  if (result) {
    build.shasum = result[1]
    build.package = result[2]
    build.name = result[3]
  } else {
    throw new Error("bad checksum data", shasumData)
  }
}

function extractBinaryChecksums (build, shasumData) {
  var result = shasumData.match(/^(\w{64}) {2}(?:\.\/)?((?:(?:node|iojs)-v\d+\.\d+\.\d+)-(.+).tar.gz)$/gim)
  if (!result) return

  result.forEach(function(distro) {
    var result = distro.match(/^(\w{64}) {2}(?:\.\/)?((?:(?:node|iojs)-v\d+\.\d+\.\d+)-(.+).tar.gz)$/i)
    if(!result) return
    build.binaries.push(
      Object.assign(Object.create(Binary), {
        build: build,
        shasum: result[1],
        package: result[2],
        platform: result[3]
      })
    )
  })
}

function writeFile (err, build) {
  if (err) return console.error(err)

  fs.writeFile(build.filename, build.definition, function (err) {
    if (err) return console.error(err)

    console.log(build.name + ' written')
  })
}
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';

window.React = React;

let data = {
  id: 1,
  commentaire: 'Un commentaire'
};

const leftButton = {
  getDefaultProps: () => {
    return (

        TOTO

    )

  }
};

class Button extends React.Component {
  constructor() {
    super();

    this.handleclick = this.handleclick.bind(this);
  }
  handleclick() {
    alert("Go to the next photo");
  }
  render() {
    console.log(this.props);
    return (

        Right button

    );
  }
}

React.reactMixin.onClass(Button, leftButton);

class Comment extends React.Component {
  render() {
    let commentaire = this.props.data.commentaire;
    return (

        { commentaire }

    );
  }
}

class Contenu extends React.Component {
  render() {
    return (

Hello!!!

        <Comment data= {this.props.data} />

    );
  }
}

render(

    <Contenu data= { data } />
    <NextButton />

,
  // React.createElement(Contenu, null),
  document.getElementById('content')
);
<commit_msg>feat(wip) : Some experiments<commit_after>import React from 'react';
import { render } from 'react-dom';

window.React = React;

let data = {
  id: 1,
  commentaire: 'Un commentaire'
};

const button = (Component, state) => class extends React.Component {
  constructor(props) {
    super(props);
    // this.state = state;
    // this.props.buttonSide = '';
    // this.Component = Component;
    // this.handleclick = this.handleclick.bind(this, 'Bonjour!');
  }
  handleclick(text, e) {
    // alert(this.props.buttonSide);
  }
  render() {
    return (
      //

      //   Right button
      //

      <Component {...this.props} />
    );
  }
}

class LeftButton extends React.Component {
  constructor(props){
    super(props);
    this.handleclick = this.handleclick.bind(this, 'Hello there!');
  }
  handleclick(text, e){
    // this.props.buttonSide = 'left';
    // alert(text);
  }
  render() {
    return (

        Left button

    );
  }
}

class Comment extends React.Component {
  render() {
    let commentaire = this.props.data.commentaire;
    return (

        { commentaire }

    );
  }
}

class Contenu extends React.Component {
  render() {
    return (

Hello!!!

        <Comment data= {this.props.data} />

    );
  }
}

const Wrapper = button(LeftButton);

render(

    <Contenu data= { data } />
    <Wrapper />

,
  // React.createElement(Contenu, null),
  document.getElementById('content')
);
<|endoftext|>