<commit_before>define(function (require, exports, module) {
    var marionette  = require('marionette');
    var RenderNode = require('famous/core/RenderNode');
    var ContainerSurface = require('famous/surfaces/ContainerSurface');
    var FamousItemView = require('./itemview').FamousItemView;
    var FamousView = require('./view').FamousView;
    var utils = require('rich/utils');
    var constraintWithJSON = require('rich/autolayout/constraints').constraintWithJSON;

    var obj = {};
    _.extend(obj, marionette.CollectionView.prototype, FamousView.prototype);

    var CollectionView = FamousItemView.extend(obj);

    CollectionView = CollectionView.extend({
        orientation: 'vertical',
        spacing: 8,

        constructor: function(options){
            options || (options = {});

            var collectionOptions = ['orientation', 'spacing', 'sizeForViewAtIndex'];
            _.extend(this, _.pick(options, collectionOptions));

            FamousView.prototype.constructor.apply(this, arguments);

            this._initialEvents();
            //this.initRenderBuffer();
        },

        // Configured the initial events that the collection view
        // binds to.
        _initialEvents: function() {

            // the only reason we are overriding this methods is to change
            // the behavior of the 'reset' handler.
            if (this.collection) {
                this.listenTo(this.collection, 'add', this._onCollectionAdd);
                this.listenTo(this.collection, 'remove', this._onCollectionRemove);
                this.listenTo(this.collection, 'reset', this._famousReset);

                if (this.sort) {
                    this.listenTo(this.collection, 'sort', this._sortViews);
                }
            }
        },

        _famousReset: function(){
            this.destroyEmptyView();
            this.destroyChildren();
            this.root = null;
            this.triggerRichInvalidate();
        },

        render: function(){
            if(!this.root || this.needsDisplay()){

                this._ensureViewIsIntact();
                this.triggerMethod('before:render', this);
                this._renderChildren();
                this.triggerMethod('render', this);
            }

            return this._spec;
        },

        // Internal method. Separated so that CompositeView can have
        // more control over events being triggered, around the rendering
        // process
        _renderChildren: function() {

            this.destroyEmptyView();

            if(!this.isEmpty(this.collection) && this.children.length > 0){
                this._render();
                return;
            }

            //this.destroyChildren();

            if (this.isEmpty(this.collection)) {
                this.showEmptyView();
            } else {
                this.triggerMethod('before:render:collection', this);
                // this.startBuffering();
                this.showCollection();
                // this.endBuffering();
                this.triggerMethod('render:collection', this);
            }

            this._render();
        },

        // Internal method to destroy an existing emptyView instance
        // if one exists. Called when a collection view has been
        // rendered empty, and then a child is added to the collection.
        destroyEmptyView: function() {
            if (this._showingEmptyView) {
                this.destroyChildren();
                delete this._showingEmptyView;
            }
        },

        // Render and show the emptyView. Similar to addChild method
        // but "child:added" events are not fired, and the event from
        // emptyView are not forwarded
        addEmptyView: function(child, EmptyView){

            // get the emptyViewOptions, falling back to childViewOptions
            var emptyViewOptions = this.getOption('emptyViewOptions') ||
                                   this.getOption('childViewOptions');

            if (_.isFunction(emptyViewOptions)){
                emptyViewOptions = emptyViewOptions.call(this);
            }

            // build the empty view
            var view = this.buildChildView(child, EmptyView, emptyViewOptions);

            // trigger the 'before:show' event on `view` if the collection view
            // has already been shown
            if (this._isShown){
                this.triggerMethod.call(view, 'before:show');
            }

            // Store the `emptyView` like a `childView` so we can properly
            // remove and/or close it later

            /**
             * RICH CHANGE: from this.children.add(view) to this.addSubview(view)
             * Effecitively does the same thing, but we need to register
             * our subviews for our rendering needs
             */

            if(this.sizeForEmptyView){
                size = this.sizeForEmptyView(view);
                view.properties.size = size;
            }

            this.addSubview(view);

            // call the 'show' method if the collection view
            // has already been shown
            if (this._isShown){
                this.triggerMethod.call(view, 'show');
            }
        },

        // Internal Method. Add the view to children and render it at
        // the given index.
        _addChildView: function(view, index) {

            // set up the child view event forwarding
            this.proxyChildEvents(view);

            this.triggerMethod('before:add:child', view);

            // Store the child view itself so we can properly
            // remove and/or destroy it later

            /**
             * RICH CHANGE: from this.children.add(view) to this.addSubview(view)
             * Effecitively does the same thing, but we need to register
             * our subviews for our rendering needs
             */

            // we don't want addSubview here, that will immediately
            // invalidate the view. addCOnstraints below will do that
            // job for us as well as invalidating the layout.
            this.prepareSubviewAdd(view);

            var constraints;

            if(this.orientation == 'vertical'){
                constraints = this.applyVerticalConstraints(view, index);
            } else {
                constraints = this.applyHorizontalConstraints(view, index);
            }

            view._initializeRelationships();
            this.addConstraints(constraints);

            if (true || this._isShown && !this.isBuffering){
                if (_.isFunction(view.triggerMethod)) {
                    view.triggerMethod('show');
                } else {
                    Marionette.triggerMethod.call(view, 'show');
                }
            }

            this.triggerMethod('add:child', view);
        },

        applyVerticalConstraints: function(view, index){
            var size = this.sizeForViewAtIndex(view, index);
            var constraints = [];

            constraints.push(constraintWithJSON({
                item: view,
                attribute: 'width',
                relatedBy: '==',
                toItem: this,
                toAttribute: 'width',
            }));

            constraints.push(constraintWithJSON({
                item: view,
                attribute: 'height',
                relatedBy: '==',
                constant: size[1],
            }));

            if(index === 0){
                constraints.push(constraintWithJSON({
                    item: view,
                    attribute: 'top',
                    relatedBy: '==',
                    toItem: this,
                    toAttribute: 'top',
                    constant: 0,
                    priority: 20,
                }));
            } else {
                constraints.push(constraintWithJSON({
                    item: view,
                    attribute: 'top',
                    relatedBy: '==',
                    toItem: this.children.findByIndex(index - 1),
                    toAttribute: 'bottom',
                    constant: this.spacing,
                    priority: 20,
                }));
            }

            return constraints;
        },

        applyHorizontalConstraints: function(view, index){
            var size = this.sizeForViewAtIndex(view, index);
            var constraints = [];

            constraints.push(constraintWithJSON({
                item: view,
                attribute: 'height',
                relatedBy: '==',
                toItem: this,
                toAttribute: 'height'
            }));

            constraints.push(constraintWithJSON({
                item: view,
                attribute: 'width',
                relatedBy: '==',
                constant: size[0]
            }));

            if(index === 0){
                constraints.push(constraintWithJSON({
                    item: view,
                    attribute: 'left',
                    relatedBy: '==',
                    toItem: this,
                    toAttribute: 'left',
                    constant: 0
                }));
            } else {
                constraints.push(constraintWithJSON({
                    item: view,
                    attribute: 'left',
                    relatedBy: '==',
                    toItem: this.children.findByIndex(index - 1),
                    toAttribute: 'right',
                    constant: this.spacing
                }));
            }

            return constraints;
        },

        sizeForViewAtIndex: function(view, index){
            return view.getSize();
        },

        // Remove the child view and destroy it.
        // This function also updates the indices of
        // later views in the collection in order to keep
        // the children in sync with the collection.
        removeChildView: function(view) {

            if (view) {
                this.triggerMethod('before:remove:child', view);
                // call 'destroy' or 'remove', depending on which is found
                if (view.destroy) { view.destroy(); }
                else if (view.remove) { view.remove(); }

                this.stopListening(view);
                //this.children.remove(view);
                this.prepareSubviewRemove(view);
                this.triggerMethod('remove:child', view);

                // decrement the index of views after this one
                this._updateIndices(view, false);

                var constraints = [];

                constraints = constraints.concat(this._processIntrinsicConstraints(
                    _.result(this, 'constraints')
                ));

                var action = this.orientation == 'vertical' ?
                    this.applyVerticalConstraints.bind(this) :
                    this.applyHorizntalConstraints.bind(this);

                this.children.each(function(view, index){
                    //view.invalidateLayout();
                    constraints = constraints.concat(action(view, index));
                }, this);

                this._constraints = constraints;
                this._constraintsInitialized = false;
                this.invalidateView();
            }

            return view;
        },

        startBuffering: function(){
            // noop for now
        },

        endBuffering: function(){
            // noop for now
        },
    });

    exports.CollectionView = CollectionView;
});
<commit_msg>buffered loading for collectionview<commit_after>define(function (require, exports, module) {
    var marionette  = require('marionette');
    var RenderNode = require('famous/core/RenderNode');
    var ContainerSurface = require('famous/surfaces/ContainerSurface');
    var FamousItemView = require('./itemview').FamousItemView;
    var FamousView = require('./view').FamousView;
    var utils = require('rich/utils');
    var constraintWithJSON = require('rich/autolayout/constraints').constraintWithJSON;

    var obj = {};
    _.extend(obj, marionette.CollectionView.prototype, FamousView.prototype);

    var CollectionView = FamousItemView.extend(obj);

    CollectionView = CollectionView.extend({
        orientation: 'vertical',
        spacing: 8,

        constructor: function(options){
            options || (options = {});

            var collectionOptions = ['orientation', 'spacing', 'sizeForViewAtIndex'];
            _.extend(this, _.pick(options, collectionOptions));

            FamousView.prototype.constructor.apply(this, arguments);

            this._initialEvents();
            this.initRenderBuffer();
        },

        // Instead of inserting elements one by one into the page,
        // it's much more performant to insert elements into a document
        // fragment and then insert that document fragment into the page
        initRenderBuffer: function() {
          //this.elBuffer = document.createDocumentFragment();
          //this._bufferedChildren = [];
          this._constraintBuffer = [];
        },

        startBuffering: function() {
            this.initRenderBuffer();
            this.isBuffering = true;

            var constraints = _.result(this, 'constraints');
            this._constraintBuffer = this._constraintBuffer.concat(
                this._processIntrinsicConstraints(constraints)
            );
        },

        endBuffering: function() {
            this.isBuffering = false;
            this._constraints = this._constraintBuffer;

            //this._triggerBeforeShowBufferedChildren();
            //this._triggerShowBufferedChildren();
            this.initRenderBuffer();
        },

        // Configured the initial events that the collection view
        // binds to.
        _initialEvents: function() {

            // the only reason we are overriding this methods is to change
            // the behavior of the 'reset' handler.
            if (this.collection) {
                this.listenTo(this.collection, 'add', this._onCollectionAdd);
                this.listenTo(this.collection, 'remove', this._onCollectionRemove);
                this.listenTo(this.collection, 'reset', this._famousReset);

                if (this.sort) {
                    this.listenTo(this.collection, 'sort', this._sortViews);
                }
            }
        },

        _famousReset: function(){
            this.destroyEmptyView();
            this.destroyChildren();
            this.root = null;
            this.triggerRichInvalidate();
        },

        render: function(){
            if(!this.root || this.needsDisplay()){

                this._ensureViewIsIntact();
                this.triggerMethod('before:render', this);
                this._renderChildren();
                this.triggerMethod('render', this);
            }

            return this._spec;
        },

        // Internal method. Separated so that CompositeView can have
        // more control over events being triggered, around the rendering
        // process
        _renderChildren: function() {

            this.destroyEmptyView();

            if(!this.isEmpty(this.collection) && this.children.length > 0){
                this._render();
                return;
            }

            //this.destroyChildren();

            if (this.isEmpty(this.collection)) {
                this.showEmptyView();
            } else {
                this.triggerMethod('before:render:collection', this);
                this.startBuffering();
                this.showCollection();
                this.endBuffering();
                this.triggerMethod('render:collection', this);
            }

            this._render();
        },

        // Internal method to destroy an existing emptyView instance
        // if one exists. Called when a collection view has been
        // rendered empty, and then a child is added to the collection.
        destroyEmptyView: function() {
            if (this._showingEmptyView) {
                this.destroyChildren();
                delete this._showingEmptyView;
            }
        },

        // Render and show the emptyView. Similar to addChild method
        // but "child:added" events are not fired, and the event from
        // emptyView are not forwarded
        addEmptyView: function(child, EmptyView){

            // get the emptyViewOptions, falling back to childViewOptions
            var emptyViewOptions = this.getOption('emptyViewOptions') ||
                                   this.getOption('childViewOptions');

            if (_.isFunction(emptyViewOptions)){
                emptyViewOptions = emptyViewOptions.call(this);
            }

            // build the empty view
            var view = this.buildChildView(child, EmptyView, emptyViewOptions);

            // trigger the 'before:show' event on `view` if the collection view
            // has already been shown
            if (this._isShown){
                this.triggerMethod.call(view, 'before:show');
            }

            // Store the `emptyView` like a `childView` so we can properly
            // remove and/or close it later

            /**
             * RICH CHANGE: from this.children.add(view) to this.addSubview(view)
             * Effecitively does the same thing, but we need to register
             * our subviews for our rendering needs
             */

            if(this.sizeForEmptyView){
                size = this.sizeForEmptyView(view);
                view.properties.size = size;
            }

            this.addSubview(view);

            // call the 'show' method if the collection view
            // has already been shown
            if (this._isShown){
                this.triggerMethod.call(view, 'show');
            }
        },

        // Internal Method. Add the view to children and render it at
        // the given index.
        _addChildView: function(view, index) {

            // set up the child view event forwarding
            this.proxyChildEvents(view);

            this.triggerMethod('before:add:child', view);

            // Store the child view itself so we can properly
            // remove and/or destroy it later

            /**
             * RICH CHANGE: from this.children.add(view) to this.addSubview(view)
             * Effecitively does the same thing, but we need to register
             * our subviews for our rendering needs
             */

            // we don't want addSubview here, that will immediately
            // invalidate the view. addCOnstraints below will do that
            // job for us as well as invalidating the layout.

            var constraints;

            if(this.orientation == 'vertical'){
                constraints = this.applyVerticalConstraints(view, index);
            } else {
                constraints = this.applyHorizontalConstraints(view, index);
            }

            this.prepareSubviewAdd(view);

            if(this.isBuffering){
                this._constraintBuffer = this._constraintBuffer.concat(constraints);
            } else {
                view._initializeRelationships();
                this.addConstraints(constraints);
            }

            if (true || this._isShown && !this.isBuffering){
                if (_.isFunction(view.triggerMethod)) {
                    view.triggerMethod('show');
                } else {
                    Marionette.triggerMethod.call(view, 'show');
                }
            }

            this.triggerMethod('add:child', view);
        },

        applyVerticalConstraints: function(view, index){
            var size = this.sizeForViewAtIndex(view, index);
            var constraints = [];

            constraints.push(constraintWithJSON({
                item: view,
                attribute: 'width',
                relatedBy: '==',
                toItem: this,
                toAttribute: 'width',
            }));

            constraints.push(constraintWithJSON({
                item: view,
                attribute: 'height',
                relatedBy: '==',
                constant: size[1],
            }));

            if(index === 0){
                constraints.push(constraintWithJSON({
                    item: view,
                    attribute: 'top',
                    relatedBy: '==',
                    toItem: this,
                    toAttribute: 'top',
                    constant: 0,
                }));
            } else {
                constraints.push(constraintWithJSON({
                    item: view,
                    attribute: 'top',
                    relatedBy: '==',
                    toItem: this.children.findByIndex(index - 1),
                    toAttribute: 'bottom',
                    constant: this.spacing
                }));
            }

            return constraints;
        },

        applyHorizontalConstraints: function(view, index){
            var size = this.sizeForViewAtIndex(view, index);
            var constraints = [];

            constraints.push(constraintWithJSON({
                item: view,
                attribute: 'height',
                relatedBy: '==',
                toItem: this,
                toAttribute: 'height'
            }));

            constraints.push(constraintWithJSON({
                item: view,
                attribute: 'width',
                relatedBy: '==',
                constant: size[0]
            }));

            if(index === 0){
                constraints.push(constraintWithJSON({
                    item: view,
                    attribute: 'left',
                    relatedBy: '==',
                    toItem: this,
                    toAttribute: 'left',
                    constant: 0
                }));
            } else {
                constraints.push(constraintWithJSON({
                    item: view,
                    attribute: 'left',
                    relatedBy: '==',
                    toItem: this.children.findByIndex(index - 1),
                    toAttribute: 'right',
                    constant: this.spacing
                }));
            }

            return constraints;
        },

        sizeForViewAtIndex: function(view, index){
            return view.getSize();
        },

        // Remove the child view and destroy it.
        // This function also updates the indices of
        // later views in the collection in order to keep
        // the children in sync with the collection.
        removeChildView: function(view) {

            if (view) {
                this.triggerMethod('before:remove:child', view);
                // call 'destroy' or 'remove', depending on which is found
                if (view.destroy) { view.destroy(); }
                else if (view.remove) { view.remove(); }

                this.stopListening(view);
                //this.children.remove(view);
                this.prepareSubviewRemove(view);
                this.triggerMethod('remove:child', view);

                // decrement the index of views after this one
                this._updateIndices(view, false);

                var constraints = [];

                constraints = constraints.concat(this._processIntrinsicConstraints(
                    _.result(this, 'constraints')
                ));

                var action = this.orientation == 'vertical' ?
                    this.applyVerticalConstraints.bind(this) :
                    this.applyHorizntalConstraints.bind(this);

                this.children.each(function(view, index){
                    //view.invalidateLayout();
                    constraints = constraints.concat(action(view, index));
                }, this);

                this._constraints = constraints;
                this._constraintsInitialized = false;
                this.invalidateView();
            }

            return view;
        },
    });

    exports.CollectionView = CollectionView;
});
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    rimraf = require('gulp-rimraf'),
    rename = require('gulp-rename'),
    gutil = require('gulp-util'),
    tap = require('gulp-tap'),
    buffer = require('gulp-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    browserify = require('browserify'),
    reactify = require('reactify'),
    mochify = require('mochify'),
    mocha = require('gulp-mocha'),
    SRC = './lib/SmartString.js',
    TEST_SRC = './test/SmartString.test.js',
    DEST = 'dist',
    SRC_COMPILED = 'SmartString.js',
    MIN_FILE = 'SmartString.min.js';

gulp.task('browserify', function() {

    return gulp.src(SRC, { read: false }) // no need of reading file because browserify does.

    // transform file objects using gulp-tap plugin
    .pipe(tap(function(file) {

        gutil.log('bundling ' + file.path);

        // replace file contents with browserify's bundle stream
        file.contents = browserify(file.path, { debug: true }).bundle();

    }))

    // transform streaming contents into buffer contents (because gulp-sourcemaps does not support streaming contents)
    .pipe(buffer())

    // load and init sourcemaps
    .pipe(sourcemaps.init({ loadMaps: true }))

    .pipe(uglify())

    // write sourcemaps
    .pipe(sourcemaps.write('./'))

    .pipe(gulp.dest('dist'));

});

/*
// gulp-browserify is deprecated
gulp.task('browserify', function() {
    return gulp.src(SRC)
        .pipe(browserify({
            detectGlobals: true,
            standalone: 'S'
        }))
        .pipe(gulp.dest(DEST));
});
*/
gulp.task('test', function() {
    return gulp.src(TEST_SRC, { read: false })
        .pipe(mocha({ reporter: 'spec', growl: 1 }));
});

gulp.task('clean', function() {
    return gulp.src(DEST)
        .pipe(rimraf());
});

gulp.task('build', ['test', 'clean', 'browserify'], function() {
    gulp.src(DEST + '/' + SRC_COMPILED)
        .pipe(uglify())
        .pipe(rename(MIN_FILE))
        .pipe(gulp.dest(DEST));
});

gulp.task('browserTest', function(done) {
    return mochify({ wd: true })
        .on('error', function(err) {
            if (err) done(err);
            else done();
        })
        .bundle();
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['clean', 'build']);<commit_msg>reformat gulp file<commit_after>var gulp = require('gulp'),
  uglify = require('gulp-uglify'),
  rimraf = require('gulp-rimraf'),
  rename = require('gulp-rename'),
  gutil = require('gulp-util'),
  tap = require('gulp-tap'),
  buffer = require('gulp-buffer'),
  sourcemaps = require('gulp-sourcemaps'),
  browserify = require('browserify'),
  reactify = require('reactify'),
  mochify = require('mochify'),
  mocha = require('gulp-mocha'),
  SRC = './lib/SmartString.js',
  TEST_SRC = './test/SmartString.test.js',
  DEST = 'dist',
  SRC_COMPILED = 'SmartString.js',
  MIN_FILE = 'SmartString.min.js'

gulp.task('browserify', function () {
  return gulp.src(SRC, { read: false }) // no need of reading file because browserify does.

    // transform file objects using gulp-tap plugin
    .pipe(tap(function (file) {
      gutil.log('bundling ' + file.path)

      // replace file contents with browserify's bundle stream
      file.contents = browserify(file.path, { debug: true }).bundle()
    }))

    // transform streaming contents into buffer contents (because gulp-sourcemaps does not support streaming contents)
    .pipe(buffer())

    // load and init sourcemaps
    .pipe(sourcemaps.init({ loadMaps: true }))

    .pipe(uglify())

    // write sourcemaps
    .pipe(sourcemaps.write('./'))

    .pipe(gulp.dest('dist'))
})

/*
// gulp-browserify is deprecated
gulp.task('browserify', function() {
    return gulp.src(SRC)
        .pipe(browserify({
            detectGlobals: true,
            standalone: 'S'
        }))
        .pipe(gulp.dest(DEST))
})
*/
gulp.task('test', function () {
  return gulp.src(TEST_SRC, { read: false })
    .pipe(mocha({ reporter: 'spec', growl: 1 }))
})

gulp.task('clean', function () {
  return gulp.src(DEST)
    .pipe(rimraf())
})

gulp.task('build', ['test', 'clean', 'browserify'], function () {
  gulp.src(DEST + '/' + SRC_COMPILED)
    .pipe(uglify())
    .pipe(rename(MIN_FILE))
    .pipe(gulp.dest(DEST))
})

gulp.task('browserTest', function (done) {
  return mochify({ wd: true })
    .on('error', function (err) {
      if (err) done(err)
      else done()
    })
    .bundle()
})

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['clean', 'build'])
<|endoftext|>


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

class InstrumentPageLoad {
    constructor() {
        this._inited = false;
        this._span = null;
    }

    name() {
        return 'instrument_page_load';
    }

    addOptions(tracerImp) {
        tracerImp.addOption('instrument_page_load', { type : 'bool', defaultValue : false });
    }

    start(tracerImp) {
        if (this._inited) {
            return;
        }
        this._inited = true;

        if (typeof window !== 'object' || typeof document !== 'object') {
            return;
        }

        const currentOptions = tracerImp.options();
        if (currentOptions.instrument_page_load) {
            this._ensureSpanStarted(tracerImp);
            document.addEventListener('readystatechange', this._handleReadyStateChange.bind(this));
        }
    }

    stop() {
    }

    _ensureSpanStarted(tracerImp) {
        if (!this._span) {
            this._span = tracerImp.startSpan('document/load');
            tracerImp.addActiveRootSpan(this._span);
        }
    }

    _handleReadyStateChange() {
        if (!this._span) {
            return;
        }

        let span = this._span;
        let state = document.readyState;
        let payload = undefined;
        if (state === 'complete') {
            payload = {};
            if (window.performance && performance.timing) {
                this._addTimingSpans(span, performance.timing);
                payload['window.performance.timing'] = performance.timing;
            }
        }

        span.logEvent(`document.readystatechange ${state}`, payload);

        if (state === 'complete') {
            if (span.tracer()) {
                span.tracer().removeActiveRootSpan(span.tracer());
            }
            span.finish();
        }
    }

    _copyNavigatorProperties(nav) {
        let dst = {};
        for (let key in nav) { // eslint-disable-line guard-for-in
            try {
                let value = nav[key];
                switch (key) {

                case 'plugins': {
                    let p = [];
                    for (let i = 0; i < value.length; i++) {
                        let item = value.item(i);
                        p.push({
                            name        : item.name,
                            description : item.description,
                        });
                    }
                    dst[key] = p;
                } break;

                case 'mimeTypes': {
                    let p = [];
                    for (let i = 0; i < value.length; i++) {
                        let item = value.item(i);
                        p.push({
                            type        : item.type,
                            description : item.description,
                            suffixes    : item.suffixes,
                        });
                    }
                    dst[key] = p;
                } break;

                default:
                    dst[key] = value;
                    break;
                }
            } catch (e) {
                // Skip, just in case
            }
        }
        return dst;
    }

    // Retroactively create the appropriate spans and logs
    _addTimingSpans(parentImp, timing) {
        // NOTE: this currently relies on LightStep-specific APIs
        if (!parentImp) {
            return;
        }

        parentImp.setTag('user_agent', navigator.userAgent);

        _each(timing, (value, key) => {
            // e.g. secureConnectionStart is not always set
            if (typeof value !== 'number' || value === 0) {
                return;
            }

            let payload = undefined;

            if (key === 'navigationStart' && typeof navigator === 'object') {
                payload = {
                    navigator : this._copyNavigatorProperties(navigator),
                };
            }
            parentImp.log({
                message : `document ${key}`,
                payload : payload,
            }, value);
        });

        if (window.chrome && window.chrome.loadTimes) {
            let chromeTimes = window.chrome.loadTimes();
            if (chromeTimes) {
                parentImp.log({
                    message : 'window.chrome.loadTimes()',
                    payload : chromeTimes,
                }, timing.domComplete);
            }
        }

        parentImp.setBeginMicros(timing.navigationStart * 1000.0);

        parentImp.tracer().startSpan('document/time_to_first_byte', { childOf : parentImp })
            .setBeginMicros(timing.requestStart * 1000.0)
            .setEndMicros(timing.responseStart * 1000.0)
            .finish();
        parentImp.tracer()
            .startSpan('document/response_transfer', { childOf : parentImp })
            .setBeginMicros(timing.responseStart * 1000.0)
            .setEndMicros(timing.responseEnd * 1000.0)
            .finish();
        parentImp.tracer().startSpan('document/dom_load', { childOf : parentImp })
            .setBeginMicros(timing.domLoading * 1000.0)
            .setEndMicros(timing.domInteractive * 1000.0)
            .finish();
    }
}

module.exports = new InstrumentPageLoad();
<commit_msg>Remove deprecated chrome.loadTimes() code (#157)<commit_after>import _each from '../_each';

class InstrumentPageLoad {
    constructor() {
        this._inited = false;
        this._span = null;
    }

    name() {
        return 'instrument_page_load';
    }

    addOptions(tracerImp) {
        tracerImp.addOption('instrument_page_load', { type : 'bool', defaultValue : false });
    }

    start(tracerImp) {
        if (this._inited) {
            return;
        }
        this._inited = true;

        if (typeof window !== 'object' || typeof document !== 'object') {
            return;
        }

        const currentOptions = tracerImp.options();
        if (currentOptions.instrument_page_load) {
            this._ensureSpanStarted(tracerImp);
            document.addEventListener('readystatechange', this._handleReadyStateChange.bind(this));
        }
    }

    stop() {
    }

    _ensureSpanStarted(tracerImp) {
        if (!this._span) {
            this._span = tracerImp.startSpan('document/load');
            tracerImp.addActiveRootSpan(this._span);
        }
    }

    _handleReadyStateChange() {
        if (!this._span) {
            return;
        }

        let span = this._span;
        let state = document.readyState;
        let payload = undefined;
        if (state === 'complete') {
            payload = {};
            if (window.performance && performance.timing) {
                this._addTimingSpans(span, performance.timing);
                payload['window.performance.timing'] = performance.timing;
            }
        }

        span.logEvent(`document.readystatechange ${state}`, payload);

        if (state === 'complete') {
            if (span.tracer()) {
                span.tracer().removeActiveRootSpan(span.tracer());
            }
            span.finish();
        }
    }

    _copyNavigatorProperties(nav) {
        let dst = {};
        for (let key in nav) { // eslint-disable-line guard-for-in
            try {
                let value = nav[key];
                switch (key) {

                case 'plugins': {
                    let p = [];
                    for (let i = 0; i < value.length; i++) {
                        let item = value.item(i);
                        p.push({
                            name        : item.name,
                            description : item.description,
                        });
                    }
                    dst[key] = p;
                } break;

                case 'mimeTypes': {
                    let p = [];
                    for (let i = 0; i < value.length; i++) {
                        let item = value.item(i);
                        p.push({
                            type        : item.type,
                            description : item.description,
                            suffixes    : item.suffixes,
                        });
                    }
                    dst[key] = p;
                } break;

                default:
                    dst[key] = value;
                    break;
                }
            } catch (e) {
                // Skip, just in case
            }
        }
        return dst;
    }

    // Retroactively create the appropriate spans and logs
    _addTimingSpans(parentImp, timing) {
        // NOTE: this currently relies on LightStep-specific APIs
        if (!parentImp) {
            return;
        }

        parentImp.setTag('user_agent', navigator.userAgent);

        _each(timing, (value, key) => {
            // e.g. secureConnectionStart is not always set
            if (typeof value !== 'number' || value === 0) {
                return;
            }

            let payload = undefined;

            if (key === 'navigationStart' && typeof navigator === 'object') {
                payload = {
                    navigator : this._copyNavigatorProperties(navigator),
                };
            }
            parentImp.log({
                message : `document ${key}`,
                payload : payload,
            }, value);
        });

        parentImp.setBeginMicros(timing.navigationStart * 1000.0);

        parentImp.tracer().startSpan('document/time_to_first_byte', { childOf : parentImp })
            .setBeginMicros(timing.requestStart * 1000.0)
            .setEndMicros(timing.responseStart * 1000.0)
            .finish();
        parentImp.tracer()
            .startSpan('document/response_transfer', { childOf : parentImp })
            .setBeginMicros(timing.responseStart * 1000.0)
            .setEndMicros(timing.responseEnd * 1000.0)
            .finish();
        parentImp.tracer().startSpan('document/dom_load', { childOf : parentImp })
            .setBeginMicros(timing.domLoading * 1000.0)
            .setEndMicros(timing.domInteractive * 1000.0)
            .finish();
    }
}

module.exports = new InstrumentPageLoad();
<|endoftext|>


<commit_before>/**
 * The Initial Developer of the Original Code is
 * Tarmo Alexander Sundström <ta@sundstrom.im>
 *
 * Portions created by the Initial Developer are
 * Copyright (C) 2014 Tarmo Alexander Sundström <ta@sundstrom.im>
 *
 * All Rights Reserved.
 *
 * Contributor(s):
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

var Article = {

    init: function()
    {
        jQuery('.confirm').click(function(e) {
            var message = jQuery(this).attr('data-message');
            if (confirm(message)) {
                return true;
            } else {
                return false;
            }
        });

        jQuery('#alias-toggle').on('click', function() {
            jQuery('#article-alias').toggle();
        });

        jQuery('a[href="#webvaloa-all-tabs"]').click(function(){
          jQuery('#groups-tab li').removeClass('active');
          jQuery(this).parent().addClass('active');
          jQuery('#'+jQuery(this).data('tabs') + ' .tab-pane').each(function(i,t){
            jQuery(this).addClass('active');
          });
        }).trigger('click');

        if(document.location.hash) {
          jQuery('.nav-tabs a[href='+document.location.hash+']').tab('show');
          jQuery('a[href="#webvaloa-all-tabs"]').parent().remove();
        }
        jQuery('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
          window.location.hash = e.target.hash;
        });
        jQuery(window).on('hashchange', function() {
          jQuery('.nav-tabs a[href='+document.location.hash+']').tab('show');
        });
    }
}

jQuery(document).ready(function() {

    Article.init();

});
<commit_msg>Hipsufy hash selector<commit_after>/**
 * The Initial Developer of the Original Code is
 * Tarmo Alexander Sundström <ta@sundstrom.im>
 *
 * Portions created by the Initial Developer are
 * Copyright (C) 2014 Tarmo Alexander Sundström <ta@sundstrom.im>
 *
 * All Rights Reserved.
 *
 * Contributor(s):
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

var Article = {

    init: function()
    {
        jQuery('.confirm').click(function(e) {
            var message = jQuery(this).attr('data-message');
            if (confirm(message)) {
                return true;
            } else {
                return false;
            }
        });

        jQuery('#alias-toggle').on('click', function() {
            jQuery('#article-alias').toggle();
        });

        jQuery('a[href="#webvaloa-all-tabs"]').click(function(){
          jQuery('#groups-tab li').removeClass('active');
          jQuery(this).parent().addClass('active');
          jQuery('#'+jQuery(this).data('tabs') + ' .tab-pane').each(function(i,t){
            jQuery(this).addClass('active');
          });
        }).trigger('click');

        if(document.location.hash) {
          jQuery('.nav-tabs a[href="'+document.location.hash+'"]').tab('show');
          jQuery('a[href="#webvaloa-all-tabs"]').parent().remove();
        }
        jQuery('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
          window.location.hash = e.target.hash;
        });
        jQuery(window).on('hashchange', function() {
          jQuery('.nav-tabs a[href="'+document.location.hash+'"]').tab('show');
        });
    }
}

jQuery(document).ready(function() {

    Article.init();

});
<|endoftext|>


<commit_before>"use strict";

//# aims to be similiar to this "official" word count example
//# https://github.com/apache/kafka/blob/0.10.0/streams/examples/src/main/java/org/apache/kafka/streams/examples/wordcount/WordCountDemo.java

/*
    the input topic could look like this:

    "fruit banana"
    "fruit cherry"
    "vegetable broccoli"
    "fruit strawberry"
    "vegetable lettuce"

    the output topic would then look like this:

    "fruit 3"
*/

const {KafkaStreams} = require("./../index.js");
const config = require("./../test/test-config.js");

const kafkaStreams = new KafkaStreams(config);
const stream = kafkaStreams.getKStream("my-input-topic");

stream
    .map(keyValueMapperEtl)
    .countByKey("key", "count")
    .filter(kv => kv.count >= 3)
    .map(kv => kv.key + " " + kv.count)
    .tap(kv => console.log(kv))
    .to("my-output-topic");

stream.start();

//consume & produce for 5 seconds
setTimeout(kafkaStreams.closeAll().bind(kafkaStreams), 5000);

function keyValueMapperEtl(message){
    const elements = message.toLowerCase().split(" ");
    return {
        key: elements[0],
        value: elements[1]
    };
}

//# alternatively checkout ../test/unit/WordCount.test.js for a working example without kafka broker<commit_msg>Fix bug in word count example<commit_after>"use strict";

//# aims to be similiar to this "official" word count example
//# https://github.com/apache/kafka/blob/0.10.0/streams/examples/src/main/java/org/apache/kafka/streams/examples/wordcount/WordCountDemo.java

/*
    the input topic could look like this:

    "fruit banana"
    "fruit cherry"
    "vegetable broccoli"
    "fruit strawberry"
    "vegetable lettuce"

    the output topic would then look like this:

    "fruit 3"
*/

const {KafkaStreams} = require("./../index.js");
const config = require("./../test/test-config.js");

const kafkaStreams = new KafkaStreams(config);
const stream = kafkaStreams.getKStream("my-input-topic");

stream
    .map(keyValueMapperEtl)
    .countByKey("key", "count")
    .filter(kv => kv.count >= 3)
    .map(kv => kv.key + " " + kv.count)
    .tap(kv => console.log(kv))
    .to("my-output-topic");

stream.start();

//consume & produce for 5 seconds
setTimeout(kafkaStreams.closeAll.bind(kafkaStreams), 5000);

function keyValueMapperEtl(message){
    const elements = message.toLowerCase().split(" ");
    return {
        key: elements[0],
        value: elements[1]
    };
}

//# alternatively checkout ../test/unit/WordCount.test.js for a working example without kafka broker
<|endoftext|>


<commit_before>/**
* A Observer Model on Top of the jQuery Javascript Library
*
* Copyright 2011, Thomas Appel, http://thomas-appel.com, mail(at)thomas-appel.com
*
* dual licensed under MIT and GPL license
*
* http://dev.thomas-appel.com/licenses/mit.txt
* http://dev.thomas-appel.com/licenses/gpl.txt
*
* see readme.md for further info
*
* =================================================================
*
* @name jquery.observer.js
* @version 0.1.1
* @author thomas appel <mail@thomas-appel.com
*/

(function (global, undefined) {

    'use strict';

    var slice = Array.prototype.slice,
    Subscriber, Observer, pubsCID = 0,
    subsCID = 0,
    exports,
    isObject = function (obj) {
        return obj && obj.toString().toLowerCase() === '[object object]';
    },
    $ = (typeof require !== undefined || (global.define && global.define.amd)) ? require('jquery') : global.jQuery;

    /**
     * @param {Mixed} options: String or Obejct
     * @param {Object} methods: optional
     */
    function Publisher(options, methods) {
        var that = this,
        i, sl, s;

        methods = methods || {};

        if (typeof options === 'string') {
            options = {
                name: options
            };
        }

        options = $.extend({},
        Publisher.defaults, options);
        this.subscribers = {};
        this.name = options.name;

        if (!this.cid) {
            this.cid = 'pub-' + pubsCID++;
        }
        if ($.isArray(options.subscribe)) {
            i = 0;
            sl = options.subscribe.length;

            for (; i < sl; i++) {
                s = options.subscribe[i];
                s.host.subscribe.apply(s.host, [that, s.event, s.fn, s.bind]);
            }
        }

        Publisher.prototype = $.extend(Publisher.prototype, methods);
    }

    Publisher.defaults = {
        name: 'publisher'
    };
    // conf obj Array
    // [{
    //  host: subscriber object,
    //  event: events,
    //  fn: callback handle
    //  bind: boolean – binds the host subscriber-object to the THIS keyword in
    //  the callback handle
    //  }]
    Publisher.prototype = {

        cancelSubscription: (function () {
            var removeSubscription = function (service, subscribers, subscriber) {
                var l = subscribers[service].length,
                i = 0;
                for (; i < l; i++) {
                    if (subscribers[service][i].subscriber === subscriber) {
                        subscribers[service].splice(i, 1);
                    }
                }
            };

            /**
            * @param {Object} subscriber: the subscriber object
            * @param {String} service: name of service to be canceled
            */
            return function (subscriber, service) {
                var subscribers = this.subscribers,
                keys = [],
                services = (function () {
                    var key;
                    for (key in subscribers) {
                        if (subscribers.hasOwnProperty(key)) {
                            keys.push(key);
                        }
                    }
                    return keys;
                } ()),
                _services = service ? service.split(' ') : services,
                l = _services.length,
                i = 0;

                for (; i < l; i++) {
                    if (services.indexOf(_services[i]) >= 0) {
                        removeSubscription(_services[i], subscribers, subscriber);
                    }
                }
                return this;
            };
        } ()),

        /**
        * @param {String} service: name of service to be published
        * you can pass additional arguments to the publish method.
        *
        */
        publish: function (service) {
            var args = slice.call(arguments, 1),
            subscribers = this.subscribers,
            subscription = subscribers[service],
            i,
            l;

            if (subscription) {
                i = 0;
                l = subscription.length;
                for (; i < l; i++) {
                    subscription[i].fn.apply(null, args);
                }
            }
            return this;
        },

        /**
         * @param {String} service: the service to subscribe to
         * @param {Function} fn: method called on publishing service
         * @param {Object} subscriber: the subscriber Obejct
         */
        setSubscriptions: function (service, fn, subscriber) {
            var subscribers = this.subscribers,
            services = service.split(' '),
            l = services.length,
            i = 0;

            for (; i < l; i++) {
                if (subscribers[services[i]]) {
                    subscribers[services[i]].push({
                        fn: fn,
                        subscriber: subscriber
                    });
                } else {
                    subscribers[services[i]] = [{
                        fn: fn,
                        subscriber: subscriber
                    }];
                }
            }
            return this;
        }
    };

    Subscriber = function (name) {
        this.name = typeof name === 'string' ? name: 'subscriber';
        this.cid = this.cid ? this.cid: 'sub-' + subsCID++;
    };

    Subscriber.prototype = {
        /**
        * @param {Object} publ: the Publisher to subscribe to
        * @param {String} service: the service to subscribe to
        * @param {Function} fn: the function to be called when service is published
        * @param {Boolean} bind: optional, defaults to true
        * set to false, if you don't want to pass in your Subscriber Object as
        * context
        */
        subscribe: function (publ, service, fn, bind) {
            var args = slice.call(arguments, 0),
            publisher = args.shift(),
            useProxy;

            if (typeof bind === 'boolean') {
                args.pop();
            }

            args.push(this);
            //args.unshift(args[1]);
            if (args.length < 2 || typeof args[0] !== 'string') {
                throw new Error('no subsriptions supplied');
            }
            if (publisher && publisher.setSubscriptions) {
                if (typeof args[1] === 'string' && typeof this[args[1]] === 'function') {
                    args[1] = $.proxy(this[args[1]], this);
                } else {
                    useProxy = typeof bind === 'boolean' ? bind: true;
                    args[1] = useProxy ? $.proxy(args[1], this) : args[1];
                }
                publisher.setSubscriptions.apply(publisher, args);
            } else {
                throw new Error('no publisher supplied for event "' + event + '" or publisher method ´setSubscriptions´ not found');
            }
            return this;
        },
        /**
        * @param {Object} publisher: the Publisher to unsubscribe from
        * @param {String} service: the service to unsubsubscribe from
        */
        unsubscribe: function (publisher, service) {
            publisher.cancelSubscription.call(publisher, this, service);
            return this;
        }
    };

    Observer = Publisher;
    Observer.prototype = $.extend({
        on: function (event, callback) {
            return this.subscribe(this, event, callback);
        }
    }, Publisher.prototype, Subscriber.prototype);

    exports = {
        Observer: function (options, methods) {
            return new Observer(options, methods);
        },
        Publisher: function (options, methods) {
            return new Publisher(options, methods);
        },
        Subscriber: function (options, methods) {
            return new Subscriber(options, methods);
        }
    };

    if (typeof global.define === 'function') {
        global.define('jqueryobserver', function () {
            return exports;
        });
    } else if (typeof module !== undefined) {
        module.exports = exports;
    } else {
        $.extend($, exports);
    }
}(this));
<commit_msg>fix amd loading<commit_after>/**
* A Observer Model on Top of the jQuery Javascript Library
*
* Copyright 2011, Thomas Appel, http://thomas-appel.com, mail(at)thomas-appel.com
*
* dual licensed under MIT and GPL license
*
* http://dev.thomas-appel.com/licenses/mit.txt
* http://dev.thomas-appel.com/licenses/gpl.txt
*
* see readme.md for further info
*
* =================================================================
*
* @name jquery.observer.js
* @version 0.1.1
* @author thomas appel <mail@thomas-appel.com
*/

(function (global, undefined) {

    'use strict';

    var slice = Array.prototype.slice,
    Subscriber, Observer, pubsCID = 0,
    subsCID = 0,
    exports,
    isObject = function (obj) {
        return obj && obj.toString().toLowerCase() === '[object object]';
    },
    $ = (typeof require !== 'undefined' || (global.define && global.define.amd)) ? require('jquery') : global.jQuery;

    /**
     * @param {Mixed} options: String or Obejct
     * @param {Object} methods: optional
     */
    function Publisher(options, methods) {
        var that = this,
        i, sl, s;

        methods = methods || {};

        if (typeof options === 'string') {
            options = {
                name: options
            };
        }

        options = $.extend({},
        Publisher.defaults, options);
        this.subscribers = {};
        this.name = options.name;

        if (!this.cid) {
            this.cid = 'pub-' + pubsCID++;
        }
        if ($.isArray(options.subscribe)) {
            i = 0;
            sl = options.subscribe.length;

            for (; i < sl; i++) {
                s = options.subscribe[i];
                s.host.subscribe.apply(s.host, [that, s.event, s.fn, s.bind]);
            }
        }

        Publisher.prototype = $.extend(Publisher.prototype, methods);
    }

    Publisher.defaults = {
        name: 'publisher'
    };
    // conf obj Array
    // [{
    //  host: subscriber object,
    //  event: events,
    //  fn: callback handle
    //  bind: boolean – binds the host subscriber-object to the THIS keyword in
    //  the callback handle
    //  }]
    Publisher.prototype = {

        cancelSubscription: (function () {
            var removeSubscription = function (service, subscribers, subscriber) {
                var l = subscribers[service].length,
                i = 0;
                for (; i < l; i++) {
                    if (subscribers[service][i].subscriber === subscriber) {
                        subscribers[service].splice(i, 1);
                    }
                }
            };

            /**
            * @param {Object} subscriber: the subscriber object
            * @param {String} service: name of service to be canceled
            */
            return function (subscriber, service) {
                var subscribers = this.subscribers,
                keys = [],
                services = (function () {
                    var key;
                    for (key in subscribers) {
                        if (subscribers.hasOwnProperty(key)) {
                            keys.push(key);
                        }
                    }
                    return keys;
                } ()),
                _services = service ? service.split(' ') : services,
                l = _services.length,
                i = 0;

                for (; i < l; i++) {
                    if (services.indexOf(_services[i]) >= 0) {
                        removeSubscription(_services[i], subscribers, subscriber);
                    }
                }
                return this;
            };
        } ()),

        /**
        * @param {String} service: name of service to be published
        * you can pass additional arguments to the publish method.
        *
        */
        publish: function (service) {
            var args = slice.call(arguments, 1),
            subscribers = this.subscribers,
            subscription = subscribers[service],
            i,
            l;

            if (subscription) {
                i = 0;
                l = subscription.length;
                for (; i < l; i++) {
                    subscription[i].fn.apply(null, args);
                }
            }
            return this;
        },

        /**
         * @param {String} service: the service to subscribe to
         * @param {Function} fn: method called on publishing service
         * @param {Object} subscriber: the subscriber Obejct
         */
        setSubscriptions: function (service, fn, subscriber) {
            var subscribers = this.subscribers,
            services = service.split(' '),
            l = services.length,
            i = 0;

            for (; i < l; i++) {
                if (subscribers[services[i]]) {
                    subscribers[services[i]].push({
                        fn: fn,
                        subscriber: subscriber
                    });
                } else {
                    subscribers[services[i]] = [{
                        fn: fn,
                        subscriber: subscriber
                    }];
                }
            }
            return this;
        }
    };

    Subscriber = function (name) {
        this.name = typeof name === 'string' ? name: 'subscriber';
        this.cid = this.cid ? this.cid: 'sub-' + subsCID++;
    };

    Subscriber.prototype = {
        /**
        * @param {Object} publ: the Publisher to subscribe to
        * @param {String} service: the service to subscribe to
        * @param {Function} fn: the function to be called when service is published
        * @param {Boolean} bind: optional, defaults to true
        * set to false, if you don't want to pass in your Subscriber Object as
        * context
        */
        subscribe: function (publ, service, fn, bind) {
            var args = slice.call(arguments, 0),
            publisher = args.shift(),
            useProxy;

            if (typeof bind === 'boolean') {
                args.pop();
            }

            args.push(this);
            //args.unshift(args[1]);
            if (args.length < 2 || typeof args[0] !== 'string') {
                throw new Error('no subsriptions supplied');
            }
            if (publisher && publisher.setSubscriptions) {
                if (typeof args[1] === 'string' && typeof this[args[1]] === 'function') {
                    args[1] = $.proxy(this[args[1]], this);
                } else {
                    useProxy = typeof bind === 'boolean' ? bind: true;
                    args[1] = useProxy ? $.proxy(args[1], this) : args[1];
                }
                publisher.setSubscriptions.apply(publisher, args);
            } else {
                throw new Error('no publisher supplied for event "' + event + '" or publisher method ´setSubscriptions´ not found');
            }
            return this;
        },
        /**
        * @param {Object} publisher: the Publisher to unsubscribe from
        * @param {String} service: the service to unsubsubscribe from
        */
        unsubscribe: function (publisher, service) {
            publisher.cancelSubscription.call(publisher, this, service);
            return this;
        }
    };

    Observer = Publisher;
    Observer.prototype = $.extend({
        on: function (event, callback) {
            return this.subscribe(this, event, callback);
        }
    }, Publisher.prototype, Subscriber.prototype);

    exports = {
        Observer: function (options, methods) {
            return new Observer(options, methods);
        },
        Publisher: function (options, methods) {
            return new Publisher(options, methods);
        },
        Subscriber: function (options, methods) {
            return new Subscriber(options, methods);
        }
    };

    if (typeof global.define === 'function') {
        global.define('jqueryobserver', function () {
            return exports;
        });
    } else if (typeof module !== undefined) {
        module.exports = exports;
    } else {
        $.extend($, exports);
    }
}(this));
<|endoftext|>


<commit_before><commit_msg>Updated documentation.<commit_after>var
	src = './src/',
	dist = './dist/',
	ex = './example/';

var
	gulp 		= require('gulp'),
	livereload	= require('gulp-livereload'),
	notify		= require('gulp-notify'),
	install		= require('gulp-install'),
	connect		= require('gulp-connect'),
	concat		= require('gulp-concat'),
	uglify		= require('gulp-uglify');

// Install Bower components
gulp.task('install', function() {
	// Locate the source file then run the install function
	gulp.src(['./bower.json'])
		.pipe(install());
});

gulp.task('scripts', function() {
	// Locate all js files in the src folder
	gulp.src(src + '*.js')
		// Concatenate all files to a single one,
		// then move the concatenated file to the dist/ folder
		.pipe(concat('angular-flash.js'))
		.pipe(gulp.dest(dist))
		// Minify
		// .pipe(uglify())
		.pipe(livereload())
		.pipe(notify({ message: 'Scripts tasks completed!'} ) );
});

gulp.task('watch', function() {
	// Run the install task which installs Bower components
	gulp.run('install');

	// Run the scripts task
	gulp.run('scripts');

	// Watch for file changes
	gulp.watch(src + '*.js', ['scripts'];
	gulp.watch(ex + 'index.html')
		.on('change', function(file) {
			file.change()
		});
});<|endoftext|>


<commit_before>'use strict'
require('vigour-scratch/index.less')
require('./style.less')

var Element = require('vigour-element')
var Observable = require('vigour-js/lib/observable')
var contentdata = new Observable(require('./data.json'))

Element.prototype.inject(require('vigour-element/lib/property/text'))
// Element.prototype.inject(require('vigour-element/lib/events'))
Observable.prototype.inject(require('vigour-js/lib/operator/subscribe'))

var TextItem = new Element({
  titlefield:{
    text:{
      $:'title'
    }
  },
  info:{
    text:{
      $:'description'
    }
  }
}).Constructor

var Input = new Element({
  node: 'input',
  $: 'title',
  on: {
    data () {
      var node = this.node
      var value = this.val
      if (node.value !== value) {
        node.value = value
      }
    },
    keyup () {
      this.$subscribe.origin.val = this.node.value
    }
  }
}).Constructor

var app = new Element({
  val:contentdata,
  node:document.body,
  topbar:{
    text:'TOPBAR!'
  },
  inputlist:{
    ChildConstructor:Input,
    $:'shows'
  },
  container:{
    ChildConstructor:TextItem,
    $:'shows'
  },
})

// var InputTitle = new Element({
//   node: 'input',
//   $: 'title',
//   on: {
//     data () {
//       var node = this.node
//       var value = this.val
//       if (node.value !== value) {
//         node.value = value
//       }
//     },
//     keyup () {
//       this.$subscribe.origin.val = this.node.value
//     }
//   }
// }).Constructor

// var InputId = new InputTitle({
//   $: 'id'
// }).Constructor

// var app = new Element({
//   val: contentdata,
//   node: document.body,
//   topbar: {
//     node: 'header',
//     text: 'this is a topbar'
//   },
//   container: {
//     ChildConstructor: new Element({
//       titlefield: new InputTitle(),
//       secondTitle: new InputId(),
//       info: {
//         text: {
//           $: 'description'
//         }
//       }
//     }).Constructor,
//     $: 'shows'
//   }
// })
<commit_msg>example collection<commit_after>'use strict'
// require('vigour-scratch/index.less')
require('./style.less')

var Element = require('vigour-element')
var Observable = require('vigour-js/lib/observable')
var contentdata = new Observable(require('./data.json'))

Element.prototype.inject(require('vigour-element/lib/property/text'))
Observable.prototype.inject(require('vigour-js/lib/operator/subscribe'))

var TextElement = new Element({
  titlefield: {
    text: {
      $: 'title'
    }
  },
  info: {
    nested: {
      text: {
        $: 'description'
      }
    }
  }
}).Constructor

var Input = new Element({
  node: 'input',
  $: 'title',
  on: {
    data() {
        var node = this.node
        var value = this.val
        if (node.value !== value) {
          node.value = value
        }
      },
      keyup() {
        this.$subscribe.origin.val = this.node.value
      }
  }
}).Constructor

var app = new Element({
  val: contentdata,
  node: document.body,
  topbar: {
    text: 'topbar?!'
  },
  inputlist: {
    ChildConstructor: Input,
    $: 'shows'
  },
  container: {
    ChildConstructor: TextElement,
    $: 'shows'
  }
})
<|endoftext|>


<commit_before>const mergeDirs = require('merge-dirs').default;
const helpers = require('../../lib/helpers');
const path = require('path');
const shell = require('shelljs');
const latestVersion = require('latest-version');

module.exports = latestVersion('@storybook/react-native').then(version => {
  // copy all files from the template directory to project directory
  mergeDirs(path.resolve(__dirname, 'template/'), '.', 'overwrite');

  // set correct project name on entry files if possible
  const dirname = shell.ls('-d', 'ios/*.xcodeproj').stdout;
  const projectName =
    dirname && dirname.slice('ios/'.length, dirname.length - '.xcodeproj'.length - 1);
  if (projectName) {
    shell.sed('-i', '%APP_NAME%', projectName, 'storybook/index.ios.js');
    shell.sed('-i', '%APP_NAME%', projectName, 'storybook/index.android.js');
  }

  const packageJson = helpers.getPackageJson();

  packageJson.devDependencies = packageJson.devDependencies || {};
  packageJson.devDependencies['@storybook/react-native'] = `^${version}`;

  packageJson.scripts = packageJson.scripts || {};
  packageJson.scripts['storybook'] = 'storybook start -p 7007';

  helpers.writePackageJson(packageJson);
});
<commit_msg>Add react-dom to the devDependency list for React Native projects<commit_after>const mergeDirs = require('merge-dirs').default;
const helpers = require('../../lib/helpers');
const path = require('path');
const shell = require('shelljs');
const latestVersion = require('latest-version');

module.exports = latestVersion('@storybook/react-native').then(version => {
  // copy all files from the template directory to project directory
  mergeDirs(path.resolve(__dirname, 'template/'), '.', 'overwrite');

  // set correct project name on entry files if possible
  const dirname = shell.ls('-d', 'ios/*.xcodeproj').stdout;
  const projectName =
    dirname && dirname.slice('ios/'.length, dirname.length - '.xcodeproj'.length - 1);
  if (projectName) {
    shell.sed('-i', '%APP_NAME%', projectName, 'storybook/index.ios.js');
    shell.sed('-i', '%APP_NAME%', projectName, 'storybook/index.android.js');
  }

  const packageJson = helpers.getPackageJson();

  packageJson.dependencies = packageJson.dependencies || {};
  packageJson.devDependencies = packageJson.devDependencies || {};

  packageJson.devDependencies['@storybook/react-native'] = `^${version}`;

  if (!packageJson.dependencies['react-dom'] && !packageJson.devDependencies['react-dom']) {
    packageJson.devDependencies['react-dom'] = '^15.5.4';
  }

  packageJson.scripts = packageJson.scripts || {};
  packageJson.scripts['storybook'] = 'storybook start -p 7007';

  helpers.writePackageJson(packageJson);
});
<|endoftext|>


<commit_before>var g_registerWidget = null;

function emptySectionRegister() {
	if (g_sectionRegister == null) return;
	setDimensions(g_sectionRegister, "100%", 0);
}

function initSectionRegister() {
	if (g_sectionRegister == null) return;
	setDimensions(g_sectionRegister, "100%", "auto");
}

function clearHome() {
	$("#pager-filters").empty();
	$("#pager-screen-activities").empty();
	$("#pager-bar-activities").empty();
	emptySectionRegister();
}

function requestHome() {
	clearProfile();
	clearDetail();
	window.location.hash = "";

	initSectionRegister();
	g_sectionUser = $("#section-user");
	g_sectionRegister = $("#section-register");
	g_registerWidget = generateRegisterWidget($("#section-register"),
			function(data) {
				alert("Registered successfully!");
				listActivitiesAndRefresh();
			},
			function(err) {

			});

	var selector = createSelector($("#pager-filters"), ["時間倒序", "時間順序"], [g_orderDescend, g_orderAscend], null, null, null, null);
	var filter = new PagerFilter(g_keyOrientation, selector);
	var filters = [filter];

	var pagerCache = new PagerCache(5);

	// initialize pager widgets
	g_pager = new Pager($("#pager-screen-activities"), $("#pager-bar-activities"), g_numItemsPerPage, "/activity/list", generateActivitiesListParams, pagerCache, filters, onListActivitiesSuccess, onListActivitiesError);

	var onLoginSuccess = function(data) {
		emptySectionRegister();
		g_registerWidget.hide();
		listActivitiesAndRefresh();
	};

	var onLoginError = function(err) {
		initSectionRegister();
		g_registerWidget.show();
		g_pager.screen.show();
		listActivitiesAndRefresh();
	};

	var onLogoutSuccess = function(data) {
		initSectionRegister();
		g_registerWidget.show();
		g_pager.screen.show();
		listActivitiesAndRefresh();
	};

	var onLogoutError = null;

	g_preLoginForm = generatePreLoginForm(g_sectionLogin, onLoginSuccess, onLoginError, onLogoutSuccess, onLogoutError);
	g_onActivitySaveSuccess = null;
	checkLoginStatus();
}

function routeByHash() {
	var hash = window.location.hash;
	if (hash == null || hash == "") {
		requestHome();
		return;
	}
	var parts = hash.split("=");
	if (parts[0] == ("#" + g_keyVieweeId)) requestProfile(parseInt(parts[1]));
	else requestActivityDetail(parseInt(parts[1]));
}

$(document).ready(function(){

	initTopbar($("#topbar"));
	initActivityEditor($("#wrap"), listActivitiesAndRefresh);

	$(window).on("hashchange", function(evt) {
		routeByHash();
	});
	routeByHash();
});
<commit_msg>Fixed UI bug of registration section.<commit_after>var g_registerWidget = null;

function emptySectionRegister() {
	if (g_sectionRegister == null) return;
	setDimensions(g_sectionRegister, "100%", 0);
}

function initSectionRegister() {
	if (g_sectionRegister == null) return;
	setDimensions(g_sectionRegister, "100%", "auto");
}

function clearHome() {
	$("#pager-filters").empty();
	$("#pager-screen-activities").empty();
	$("#pager-bar-activities").empty();
	emptySectionRegister();
	if (g_sectionRegister == null) return;
	g_sectionRegister.empty();
}

function requestHome() {
	clearProfile();
	clearDetail();
	window.location.hash = "";

	initSectionRegister();
	g_sectionUser = $("#section-user");
	g_sectionRegister = $("#section-register");
	g_registerWidget = generateRegisterWidget($("#section-register"),
			function(data) {
				alert("Registered successfully!");
				listActivitiesAndRefresh();
			},
			function(err) {

			});

	var selector = createSelector($("#pager-filters"), ["時間倒序", "時間順序"], [g_orderDescend, g_orderAscend], null, null, null, null);
	var filter = new PagerFilter(g_keyOrientation, selector);
	var filters = [filter];

	var pagerCache = new PagerCache(5);

	// initialize pager widgets
	g_pager = new Pager($("#pager-screen-activities"), $("#pager-bar-activities"), g_numItemsPerPage, "/activity/list", generateActivitiesListParams, pagerCache, filters, onListActivitiesSuccess, onListActivitiesError);

	var onLoginSuccess = function(data) {
		emptySectionRegister();
		g_registerWidget.hide();
		listActivitiesAndRefresh();
	};

	var onLoginError = function(err) {
		initSectionRegister();
		g_registerWidget.show();
		g_pager.screen.show();
		listActivitiesAndRefresh();
	};

	var onLogoutSuccess = function(data) {
		initSectionRegister();
		g_registerWidget.show();
		g_pager.screen.show();
		listActivitiesAndRefresh();
	};

	var onLogoutError = null;

	g_preLoginForm = generatePreLoginForm(g_sectionLogin, onLoginSuccess, onLoginError, onLogoutSuccess, onLogoutError);
	g_onActivitySaveSuccess = null;
	checkLoginStatus();
}

function routeByHash() {
	var hash = window.location.hash;
	if (hash == null || hash == "") {
		requestHome();
		return;
	}
	var parts = hash.split("=");
	if (parts[0] == ("#" + g_keyVieweeId)) requestProfile(parseInt(parts[1]));
	else requestActivityDetail(parseInt(parts[1]));
}

$(document).ready(function(){

	initTopbar($("#topbar"));
	initActivityEditor($("#wrap"), listActivitiesAndRefresh);

	$(window).on("hashchange", function(evt) {
		routeByHash();
	});
	routeByHash();
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var runSequence = require('run-sequence');
var del = require('del');
var vinylPaths = require('vinyl-paths');
var to5 = require('gulp-6to5');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var yuidoc = require("gulp-yuidoc");
var changelog = require('conventional-changelog');
var assign = Object.assign || require('object.assign');
var fs = require('fs');
var bump = require('gulp-bump');
var browserSync = require('browser-sync');
var changed = require('gulp-changed');
var plumber = require('gulp-plumber');
var tools = require('aurelia-tools');

var path = {
  source:'src/**/*.js',
  html:'src/**/*.html',
  output:'dist/',
  doc:'./doc'
};

var compilerOptions = {
  filename: '',
  filenameRelative: '',
  blacklist: [],
  whitelist: [],
  modules: '',
  sourceMap: true,
  sourceMapName: '',
  sourceFileName: '',
  sourceRoot: '',
  moduleRoot: '',
  moduleIds: false,
  runtime: false,
  experimental: false,
  format: {
    comments: false,
    compact: false,
    indent: {
      parentheses: true,
      adjustMultilineComment: true,
      style: "  ",
      base: 0
    }
  }
};

var jshintConfig = {esnext:true};

gulp.task('clean', function() {
 return gulp.src([path.output])
    .pipe(vinylPaths(del));
});

gulp.task('build-system', function () {
  return gulp.src(path.source)
    .pipe(plumber())
    .pipe(changed(path.output, {extension: '.js'}))
    .pipe(to5(assign({}, compilerOptions, {modules:'system'})))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('build-html', function () {
  return gulp.src(path.html)
    .pipe(changed(path.output, {extension: '.html'}))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('lint', function() {
  return gulp.src(path.source)
    .pipe(jshint(jshintConfig))
    .pipe(jshint.reporter(stylish));
});

gulp.task('doc-generate', function(){
  return gulp.src(path.source)
    .pipe(yuidoc.parser(null, 'api.json'))
    .pipe(gulp.dest(path.doc));
});

gulp.task('doc', ['doc-generate'], function(){
  tools.transformAPIModel(path.doc);
});

gulp.task('bump-version', function(){
  return gulp.src(['./package.json'])
    .pipe(bump({type:'patch'})) //major|minor|patch|prerelease
    .pipe(gulp.dest('./'));
});

gulp.task('changelog', function(callback) {
  var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));

  return changelog({
    repository: pkg.repository.url,
    version: pkg.version,
    file: path.doc + '/CHANGELOG.md'
  }, function(err, log) {
    fs.writeFileSync(path.doc + '/CHANGELOG.md', log);
  });
});

gulp.task('build', function(callback) {
  return runSequence(
    'clean',
    ['build-system', 'build-html'],
    callback
  );
});

gulp.task('update-own-deps', function(){
  tools.updateOwnDependenciesFromLocalRepositories();
});

gulp.task('serve', ['build'], function(done) {
  browserSync({
    open: false,
    port: 9000,
    server: {
      baseDir: ['.'],
      middleware: function (req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        next();
      }
    }
  }, done);
});

gulp.task('watch', ['serve'], function() {
  var watcher = gulp.watch([path.source, path.html], ['build']);
  watcher.on('change', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
  });
});

gulp.task('prepare-release', function(callback){
  return runSequence(
    'build',
    'lint',
    'bump-version',
    'doc',
    'changelog',
    callback
  );
});<commit_msg>feat(build): update watch task to include style files<commit_after>var gulp = require('gulp');
var runSequence = require('run-sequence');
var del = require('del');
var vinylPaths = require('vinyl-paths');
var to5 = require('gulp-6to5');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var yuidoc = require("gulp-yuidoc");
var changelog = require('conventional-changelog');
var assign = Object.assign || require('object.assign');
var fs = require('fs');
var bump = require('gulp-bump');
var browserSync = require('browser-sync');
var changed = require('gulp-changed');
var plumber = require('gulp-plumber');
var tools = require('aurelia-tools');

var path = {
  source:'src/**/*.js',
  html:'src/**/*.html',
  style:'styles/**/*.css',
  output:'dist/',
  doc:'./doc'
};

var compilerOptions = {
  filename: '',
  filenameRelative: '',
  blacklist: [],
  whitelist: [],
  modules: '',
  sourceMap: true,
  sourceMapName: '',
  sourceFileName: '',
  sourceRoot: '',
  moduleRoot: '',
  moduleIds: false,
  runtime: false,
  experimental: false,
  format: {
    comments: false,
    compact: false,
    indent: {
      parentheses: true,
      adjustMultilineComment: true,
      style: "  ",
      base: 0
    }
  }
};

var jshintConfig = {esnext:true};

gulp.task('clean', function() {
 return gulp.src([path.output])
    .pipe(vinylPaths(del));
});

gulp.task('build-system', function () {
  return gulp.src(path.source)
    .pipe(plumber())
    .pipe(changed(path.output, {extension: '.js'}))
    .pipe(to5(assign({}, compilerOptions, {modules:'system'})))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('build-html', function () {
  return gulp.src(path.html)
    .pipe(changed(path.output, {extension: '.html'}))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('lint', function() {
  return gulp.src(path.source)
    .pipe(jshint(jshintConfig))
    .pipe(jshint.reporter(stylish));
});

gulp.task('doc-generate', function(){
  return gulp.src(path.source)
    .pipe(yuidoc.parser(null, 'api.json'))
    .pipe(gulp.dest(path.doc));
});

gulp.task('doc', ['doc-generate'], function(){
  tools.transformAPIModel(path.doc);
});

gulp.task('bump-version', function(){
  return gulp.src(['./package.json'])
    .pipe(bump({type:'patch'})) //major|minor|patch|prerelease
    .pipe(gulp.dest('./'));
});

gulp.task('changelog', function(callback) {
  var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));

  return changelog({
    repository: pkg.repository.url,
    version: pkg.version,
    file: path.doc + '/CHANGELOG.md'
  }, function(err, log) {
    fs.writeFileSync(path.doc + '/CHANGELOG.md', log);
  });
});

gulp.task('build', function(callback) {
  return runSequence(
    'clean',
    ['build-system', 'build-html'],
    callback
  );
});

gulp.task('update-own-deps', function(){
  tools.updateOwnDependenciesFromLocalRepositories();
});

gulp.task('serve', ['build'], function(done) {
  browserSync({
    open: false,
    port: 9000,
    server: {
      baseDir: ['.'],
      middleware: function (req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        next();
      }
    }
  }, done);
});

gulp.task('watch', ['serve'], function() {
  var watcher = gulp.watch([path.source, path.html, path.style], ['build']);
  watcher.on('change', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
  });
});

gulp.task('prepare-release', function(callback){
  return runSequence(
    'build',
    'lint',
    'bump-version',
    'doc',
    'changelog',
    callback
  );
});<|endoftext|>