<commit_before>/*global imagesLoaded */

/******************************************
 * jQuery FitFrame
 *
 * A lightweight, easy-to-use jQuery plugin for responsive slide layout.
 *
 * Author          @jenkins118 (https://fabrik.io)
 * Copyright       Copyright (c) 2015 Phil Jenkins.
 * License         MIT
 * Version         0.0.0.1
 *
 ******************************************/

(function ($, window, undefined) {

  var PLUGIN_NAME = "fabrikStrip",
      INSTANCE_KEY = "plugin_" + PLUGIN_NAME;

  function FabrikStrip(element, options, defaults) {
    this.element = $(element);
    this.options = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._init();
  }

  FabrikStrip.prototype = {

    goTo: function (index) {
      // Go to specific blade

      var self = this,
          bladesCount = $(self.options.bladesSelector).length;

      if (index > bladesCount - 1) {
        return;
      }

      $('button', self.options.pagerSelector).show();

      if (index <= 0) {
        self.goToFirst();
      }
      else if (index >= bladesCount - 1) {
        self.goToLast();
      }
      else {
        var beforeWidth = 0;

        $(self.options.bladesSelector).each(function () {
          var $blade = $(this);

          if ($blade.index() < index) {
            beforeWidth += $blade.width();
          }
        });

        var viewableWidth = $(self.element[0]).width(),
            halfView = (viewableWidth - $(self.options.bladesSelector).eq(index).width()) / 2,
            pull = beforeWidth - halfView;

        this._setActive(index);
        this._setPull(-pull);

        this.options.afterChange(index);
        return index;
      }
    },

    goToFirst: function () {
      // Go to first blade
      $('.left', self.options.pagerSelector).hide();
      this._setActive(0);
      this._setPull(0);

      this.options.afterChange(0);
      return 0;
    },

    goToLast: function () {
      // Go to last blade
      $('.right', self.options.pagerSelector).hide();
      var pull = $(this.options.innerStripSelector).width() - $(this.element[0]).width(),
          index = $(this.options.bladesSelector).length - 1;

      this._setActive(index);
      this._setPull(-pull);

      this.options.afterChange(index);
      return index;
    },

    _init: function () {
      $('html').addClass('fabrik-strip');
      this._bind();
      this._setSizes();
      this._setActive(this.options.startIndex);
    },

    _setSizes: function () {

      var self = this,
          windowHeight = $(window).height(),
          windowWidth = $(window).width();

      if ($(self.options.headerSelector).length) {
        windowHeight -= $(self.options.headerSelector).height();
      }

      $(self.element[0]).height(windowHeight);
      $(self.options.bladesSelector).removeAttr('style');

      // after images are loaded get the widths of the blades so we can set parent container

      if (imagesLoaded !== undefined) {
        imagesLoaded(self.element[0], function () {
          var width = 0;

          $(self.options.bladesSelector).each(function () {

            var $blade = $(this),
                bladewidth = $(this).width(),
                $img = $('img', $blade);

            if ($img.length) {
              bladewidth = $img.width();
            }

            $blade.width(bladewidth);
            width += bladewidth;
          });

          $(self.options.innerStripSelector).width(width).addClass('blades-loaded');
        });
      }
      else {
        console.info("You need to add images Loaded plugin http://imagesloaded.desandro.com/");
      }

      var pagerWidth = $('.left').outerWidth(true),
          infoWidth = windowWidth - pagerWidth;

      if (windowWidth >= 1200) {
        infoWidth = $(self.element[0]).width() / 2;
      }

      $('.project-info-blade').width(infoWidth);

    },

    _setPull: function (int) {
      $(this.options.innerStripSelector).css({
        "-webkit-transform": "translate3d(" + int + "px, 0px, 0px)",
        "-moz-transform": "translate3d(" + int + "px, 0px, 0px)",
        "-ms-transform": "translate3d(" + int + "px, 0px, 0px)",
        "-o-transform": "translate3d(" + int + "px, 0px, 0px)",
        "transform": "translate3d(" + int + "px, 0px, 0px)"
      });
    },

    _setActive: function (index) {
      $(this.options.bladesSelector).removeClass('active');
      // Get the new active blade
      var $blade = $(this.options.bladesSelector).eq(index);
      $blade.addClass('active');

      $(this.element[0]).data('activeIndex', index);
    },

    _goToOnResize: function (index) {
      var self = this;

      setTimeout(function () {
        self.goTo(index);
      }, 200);
    },

    _bind: function () {
      // debounced resizing
      var self = this, t;

      $('button', self.options.pagerSelector).on('click', function (e) {
        e.preventDefault();

        var activeIndex = $(self.element[0]).data('activeIndex'),
            index = activeIndex + 1;

        if ($(this).hasClass('left')) {
          index = activeIndex - 1;
        }

        self.options.beforeChange(activeIndex);

        self.goTo(index);
      });

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

        if (!$(this).hasClass('active')) {
          e.preventDefault();
          var activeIndex = $(self.element[0]).data('activeIndex');
          self.options.beforeChange(activeIndex);
          self.goTo($(this).index());
        }
      });

      $(window).on('resize.' + PLUGIN_NAME, function () {
        clearTimeout(t);
        t = setTimeout(function () {
          // On resize set the sizes
          self._setSizes();
          self._goToOnResize($(self.element[0]).data('activeIndex'));
        }, 100);
      });

      $(document.documentElement).keyup(function (event) {

        // handle cursor keys
        if (event.keyCode == 37) {
          // go left
          var activeIndex = $(self.element[0]).data('activeIndex'),
              index = activeIndex - 1;

          self.options.beforeChange(activeIndex);
          self.goTo(index);
        } else if (event.keyCode == 39) {
          // go right
          var activeIndex = $(self.element[0]).data('activeIndex'),
              index = activeIndex + 1;

          self.options.beforeChange(activeIndex);
          self.goTo(index);
        }
      });

    }

  };

  $.fn[PLUGIN_NAME] = function (options) {

    var args = arguments,
      returns;

    this.each(function () {

      var instance = $.data(this, INSTANCE_KEY);

      if (instance) {
        // check if invoking public methods
        if (typeof (options) === 'string' && options[0] !== '_') {
          var method = instance[options];
          if (typeof (method) === 'function') {
            returns = method.apply(instance, Array.prototype.slice.call(args, 1));
          } else {
            // method missing
            $.error('Public method \'' + options + '\' does not exist on jQuery.' + PLUGIN_NAME);
          }
        }

      } else {
        $.data(this, INSTANCE_KEY, new FabrikStrip(this, options, $.fn[PLUGIN_NAME].defaults));
      }
    });

    // if the earlier cached method has a value return it, otherwise return this to preserve chainability
    return returns !== undefined ? returns : this;
  };

  $.fn[PLUGIN_NAME].defaults = {
    bladesSelector: '.blade',
    innerStripSelector: '.strip',
    headerSelector: null,
    pagerSelector: '.strip-pagers',
    startIndex: 0,
    afterChange: function () { },
    beforeChange: function () { },
  };

})(jQuery, window);<commit_msg>Fixed the issue with pagerselector<commit_after>/*global imagesLoaded */

/******************************************
 * jQuery FitFrame
 *
 * A lightweight, easy-to-use jQuery plugin for responsive slide layout.
 *
 * Author          @jenkins118 (https://fabrik.io)
 * Copyright       Copyright (c) 2015 Phil Jenkins.
 * License         MIT
 * Version         0.0.0.1
 *
 ******************************************/

(function ($, window, undefined) {

  var PLUGIN_NAME = "fabrikStrip",
      INSTANCE_KEY = "plugin_" + PLUGIN_NAME;

  function FabrikStrip(element, options, defaults) {
    this.element = $(element);
    this.options = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._init();
  }

  FabrikStrip.prototype = {

    goTo: function (index) {
      // Go to specific blade

      var self = this,
          bladesCount = $(self.options.bladesSelector).length;

      if (index > bladesCount - 1) {
        return;
      }

      $('button', $(self.options.pagerSelector)).show();

      if (index <= 0) {
        self.goToFirst();
      }
      else if (index >= bladesCount - 1) {
        self.goToLast();
      }
      else {
        var beforeWidth = 0;

        $(self.options.bladesSelector).each(function () {
          var $blade = $(this);

          if ($blade.index() < index) {
            beforeWidth += $blade.width();
          }
        });

        var viewableWidth = $(self.element[0]).width(),
            halfView = (viewableWidth - $(self.options.bladesSelector).eq(index).width()) / 2,
            pull = beforeWidth - halfView;

        this._setActive(index);
        this._setPull(-pull);

        this.options.afterChange(index);
        return index;
      }
    },

    goToFirst: function () {
      // Go to first blade
      $('.left', $(self.options.pagerSelector)).hide();
      this._setActive(0);
      this._setPull(0);

      this.options.afterChange(0);
      return 0;
    },

    goToLast: function () {
      // Go to last blade
      $('.right', $(self.options.pagerSelector)).hide();
      var pull = $(this.options.innerStripSelector).width() - $(this.element[0]).width(),
          index = $(this.options.bladesSelector).length - 1;

      this._setActive(index);
      this._setPull(-pull);

      this.options.afterChange(index);
      return index;
    },

    _init: function () {
      $('html').addClass('fabrik-strip');
      this._bind();
      this._setSizes();
      this._setActive(this.options.startIndex);
    },

    _setSizes: function () {

      var self = this,
          windowHeight = $(window).height(),
          windowWidth = $(window).width();

      if ($(self.options.headerSelector).length) {
        windowHeight -= $(self.options.headerSelector).height();
      }

      $(self.element[0]).height(windowHeight);
      $(self.options.bladesSelector).removeAttr('style');

      // after images are loaded get the widths of the blades so we can set parent container

      if (imagesLoaded !== undefined) {
        imagesLoaded(self.element[0], function () {
          var width = 0;

          $(self.options.bladesSelector).each(function () {

            var $blade = $(this),
                bladewidth = $(this).width(),
                $img = $('img', $blade);

            if ($img.length) {
              bladewidth = $img.width();
            }

            $blade.width(bladewidth);
            width += bladewidth;
          });

          $(self.options.innerStripSelector).width(width).addClass('blades-loaded');
        });
      }
      else {
        console.info("You need to add images Loaded plugin http://imagesloaded.desandro.com/");
      }

      var pagerWidth = $('.left').outerWidth(true),
          infoWidth = windowWidth - pagerWidth;

      if (windowWidth >= 1200) {
        infoWidth = $(self.element[0]).width() / 2;
      }

      $('.project-info-blade').width(infoWidth);

    },

    _setPull: function (int) {
      $(this.options.innerStripSelector).css({
        "-webkit-transform": "translate3d(" + int + "px, 0px, 0px)",
        "-moz-transform": "translate3d(" + int + "px, 0px, 0px)",
        "-ms-transform": "translate3d(" + int + "px, 0px, 0px)",
        "-o-transform": "translate3d(" + int + "px, 0px, 0px)",
        "transform": "translate3d(" + int + "px, 0px, 0px)"
      });
    },

    _setActive: function (index) {
      $(this.options.bladesSelector).removeClass('active');
      // Get the new active blade
      var $blade = $(this.options.bladesSelector).eq(index);
      $blade.addClass('active');

      $(this.element[0]).data('activeIndex', index);
    },

    _goToOnResize: function (index) {
      var self = this;

      setTimeout(function () {
        self.goTo(index);
      }, 200);
    },

    _bind: function () {
      // debounced resizing
      var self = this, t;

      $('button', $(self.options.pagerSelector)).on('click', function (e) {
        e.preventDefault();

        var activeIndex = $(self.element[0]).data('activeIndex'),
            index = activeIndex + 1;

        if ($(this).hasClass('left')) {
          index = activeIndex - 1;
        }

        self.options.beforeChange(activeIndex);

        self.goTo(index);
      });

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

        if (!$(this).hasClass('active')) {
          e.preventDefault();
          var activeIndex = $(self.element[0]).data('activeIndex');
          self.options.beforeChange(activeIndex);
          self.goTo($(this).index());
        }
      });

      $(window).on('resize.' + PLUGIN_NAME, function () {
        clearTimeout(t);
        t = setTimeout(function () {
          // On resize set the sizes
          self._setSizes();
          self._goToOnResize($(self.element[0]).data('activeIndex'));
        }, 100);
      });

      $(document.documentElement).keyup(function (event) {

        // handle cursor keys
        if (event.keyCode == 37) {
          // go left
          var activeIndex = $(self.element[0]).data('activeIndex'),
              index = activeIndex - 1;

          self.options.beforeChange(activeIndex);
          self.goTo(index);
        } else if (event.keyCode == 39) {
          // go right
          var activeIndex = $(self.element[0]).data('activeIndex'),
              index = activeIndex + 1;

          self.options.beforeChange(activeIndex);
          self.goTo(index);
        }
      });

    }

  };

  $.fn[PLUGIN_NAME] = function (options) {

    var args = arguments,
      returns;

    this.each(function () {

      var instance = $.data(this, INSTANCE_KEY);

      if (instance) {
        // check if invoking public methods
        if (typeof (options) === 'string' && options[0] !== '_') {
          var method = instance[options];
          if (typeof (method) === 'function') {
            returns = method.apply(instance, Array.prototype.slice.call(args, 1));
          } else {
            // method missing
            $.error('Public method \'' + options + '\' does not exist on jQuery.' + PLUGIN_NAME);
          }
        }

      } else {
        $.data(this, INSTANCE_KEY, new FabrikStrip(this, options, $.fn[PLUGIN_NAME].defaults));
      }
    });

    // if the earlier cached method has a value return it, otherwise return this to preserve chainability
    return returns !== undefined ? returns : this;
  };

  $.fn[PLUGIN_NAME].defaults = {
    bladesSelector: '.blade',
    innerStripSelector: '.strip',
    headerSelector: null,
    pagerSelector: '.strip-pagers',
    startIndex: 0,
    afterChange: function () { },
    beforeChange: function () { },
  };

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


<commit_before>// app/components/EditSetHeader.js

import React, {Component} from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput }  from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

class EditSetHeader extends Component {

    constructor(props) {
		super(props);

		this.state = {};
	}

    setNumber() {
        if (this.state.setNumber === null || this.state.setNumber === undefined) {
            return '#1';
        }
        return '#' + this.state.setNumber;
    }

    render() {
        return (
            <View style={{flex: 1, flexDirection: 'column'}}>
                <View style={styles.upperShadow} />
                    <View style={[styles.shadow, {flex: 1, flexDirection: 'column', padding: 5}]}>
                        <View style={styles.field}>
                            <View>
                                <TextInput
                                    style={styles.fieldText}
                                    underlineColorAndroid={'transparent'}
                                    editable = {true}
                                    maxLength = {40}
                                    value = {this.state.exercise}
                                    placeholder="Enter Exercise"
                                    onChangeText={(exercise) => this.setState({exercise: exercise}) }
                                />
                            </View>
                            <View style={styles.fieldDetails} pointerEvents='none'>
                                <Text style={styles.detailText}>{this.setNumber()}</Text>
                            </View>
                        </View>
                        <View style={{flex: 1, flexDirection: 'row'}}>
                            <View style={[styles.field, {flex: 1, marginRight: 5}]}>
                                <TextInput
                                    style={styles.fieldText}
                                    keyboardType={'numeric'}
                                    underlineColorAndroid={'transparent'}
                                    editable = {true}
                                    maxLength = {40}
                                    placeholder="Enter Weight"
                                    onChangeText={(weight) => this.setState({weight: weight}) }
                                />
                                <View style={styles.fieldDetails}>
                                    <TouchableOpacity>
                                        <View style={{flexDirection: 'row', alignItems: 'center', }}>
                                            <Text style={styles.detailText}>LB </Text>
                                            <Icon name="refresh" size={10} color="gray" />
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>

                            <View style={[styles.field, {flex: 1}]}>
                                <TextInput
                                    style={styles.fieldText}
                                    keyboardType={'numeric'}
                                    underlineColorAndroid={'transparent'}
                                    editable = {true}
                                    maxLength = {40}
                                    placeholder="Enter RPE"
                                    value = {this.state.rpe}
                                    onChangeText={(rpe) => this.setState({rpe: rpe}) }
                                />
                                <View style={styles.fieldDetails} pointerEvents='none'>
                                    <Text style={styles.detailText}>RPE</Text>
                                </View>
                            </View>
                        </View>

                        <View style={[styles.field, {flex: 1}]}>
                            <View style={{height: 30, justifyContent: 'center'}}>
                                <Text>Tags</Text>
                            </View>
                        </View>
                    </View>
            </View>
        );
    }

}

const styles = StyleSheet.create({
    field: {
        backgroundColor: 'rgba(239, 239, 239, 1)',
        borderColor: 'rgba(239, 239, 239, 1)',
        borderWidth: 3,
        borderRadius: 3,
        marginBottom: 5,
    },
    fieldDetails: {
        position: 'absolute',
        right: 5,
        top: 0,
        bottom: 0,
        justifyContent: 'center',
    },
    fieldText: {
        height: 30,
        fontSize: 15
    },
    detailText: {
        color: 'gray'
    },
    upperShadow: {
		shadowColor: "#000000",
        shadowRadius: 2,
        shadowOpacity: 1,
        shadowOffset: {
            height: 1,
            weight: 0
        },
        height: 1,
        backgroundColor: 'white'
    },
	shadow: {
		shadowColor: "#000000",
		shadowOpacity: 0.2,
		shadowRadius: 2,
		shadowOffset: {
			height: 4,
			width: 0
		},
	}
});

export default EditSetHeader;
<commit_msg>removed max length<commit_after>// app/components/EditSetHeader.js

import React, {Component} from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput }  from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

class EditSetHeader extends Component {

    constructor(props) {
		super(props);

		this.state = {};
	}

    setNumber() {
        if (this.state.setNumber === null || this.state.setNumber === undefined) {
            return '#1';
        }
        return '#' + this.state.setNumber;
    }

    render() {
        return (
            <View style={{flex: 1, flexDirection: 'column'}}>
                <View style={styles.upperShadow} />
                    <View style={[styles.shadow, {flex: 1, flexDirection: 'column', padding: 5}]}>
                        <View style={styles.field}>
                            <View>
                                <TextInput
                                    style={styles.fieldText}
                                    underlineColorAndroid={'transparent'}
                                    editable = {true}
                                    value = {this.state.exercise}
                                    placeholder="Enter Exercise"
                                    onChangeText={(exercise) => this.setState({exercise: exercise}) }
                                />
                            </View>
                            <View style={styles.fieldDetails} pointerEvents='none'>
                                <Text style={styles.detailText}>{this.setNumber()}</Text>
                            </View>
                        </View>
                        <View style={{flex: 1, flexDirection: 'row'}}>
                            <View style={[styles.field, {flex: 1, marginRight: 5}]}>
                                <TextInput
                                    style={styles.fieldText}
                                    keyboardType={'numeric'}
                                    underlineColorAndroid={'transparent'}
                                    editable = {true}
                                    placeholder="Enter Weight"
                                    onChangeText={(weight) => this.setState({weight: weight}) }
                                />
                                <View style={styles.fieldDetails}>
                                    <TouchableOpacity>
                                        <View style={{flexDirection: 'row', alignItems: 'center', }}>
                                            <Text style={styles.detailText}>LB </Text>
                                            <Icon name="refresh" size={10} color="gray" />
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>

                            <View style={[styles.field, {flex: 1}]}>
                                <TextInput
                                    style={styles.fieldText}
                                    keyboardType={'numeric'}
                                    underlineColorAndroid={'transparent'}
                                    editable = {true}
                                    placeholder="Enter RPE"
                                    value = {this.state.rpe}
                                    onChangeText={(rpe) => this.setState({rpe: rpe}) }
                                />
                                <View style={styles.fieldDetails} pointerEvents='none'>
                                    <Text style={styles.detailText}>RPE</Text>
                                </View>
                            </View>
                        </View>

                        <View style={[styles.field, {flex: 1}]}>
                            <View style={{height: 30, justifyContent: 'center'}}>
                                <Text>Tags</Text>
                            </View>
                        </View>
                    </View>
            </View>
        );
    }

}

const styles = StyleSheet.create({
    field: {
        backgroundColor: 'rgba(239, 239, 239, 1)',
        borderColor: 'rgba(239, 239, 239, 1)',
        borderWidth: 3,
        borderRadius: 3,
        marginBottom: 5,
    },
    fieldDetails: {
        position: 'absolute',
        right: 5,
        top: 0,
        bottom: 0,
        justifyContent: 'center',
    },
    fieldText: {
        height: 30,
        fontSize: 15
    },
    detailText: {
        color: 'gray'
    },
    upperShadow: {
		shadowColor: "#000000",
        shadowRadius: 2,
        shadowOpacity: 1,
        shadowOffset: {
            height: 1,
            weight: 0
        },
        height: 1,
        backgroundColor: 'white'
    },
	shadow: {
		shadowColor: "#000000",
		shadowOpacity: 0.2,
		shadowRadius: 2,
		shadowOffset: {
			height: 4,
			width: 0
		},
	}
});

export default EditSetHeader;
<|endoftext|>


<commit_before>// Load modules

var Chai = require('chai');
var Querystring = require('querystring');
var Hapi = require('../helpers');
var Validation = process.env.TEST_COV ? require('../../lib-cov/validation') : require('../../lib/validation');

// Declare internals

var internals = {};

// Test shortcuts

var expect = Chai.expect;

var S = Hapi.types.String,
    N = Hapi.types.Number,
    O = Hapi.types.Object,
    B = Hapi.types.Boolean;

describe('Validation', function () {

    var testHandler = function (hapi, reply) {

        reply('ohai');
    };

    var createRequestObject = function (query, route, payload) {

        var qstr = Querystring.stringify(query);
        var routeClone = Hapi.utils.clone(route);

        return {
            url: {
                search: '?' + qstr,
                query: query,
                pathname: routeClone.path,
                path: routeClone.path + '?' + qstr,//'/config?choices=1&choices=2',
                href: routeClone.path + '?' + qstr //'/config?choices=1&choices=2'
            },
            query: query,
            payload: payload,
            path: routeClone.path,
            method: routeClone.method,
            _route: { config: routeClone.config },
            response: { result: {} }
        };
    };

    var createRequestObjectFromPath = function (path, params, route) {

        var routeClone = Hapi.utils.clone(route);

        return {
            url: {
                pathname: path,
                path: path,
                href: path
            },
            params: params,
            method: routeClone.method,
            _route: { config: routeClone.config },
            response: { result: {} }
        };
    };

    describe('#response', function () {

        var route = { method: 'GET', path: '/', config: { handler: testHandler, response: { schema: { username: S().required() } } } };

        it('should not raise an error when responding with valid param', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);

            request._response = Hapi.Response.generate({ username: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with invalid param', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });

        it('should not raise an error when responding with invalid param and sample is 0', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.sample = 0;
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with invalid param and sample is 100', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.sample = 100;
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });

        it('should report an error when sample is 50 and making 50 invalid requests', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.onInvalid = 'report';
            request._route.config.response.sample = 50;
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            request.log = function (tags, data) {

                expect(data).to.contain('not allowed to be undefined');
                done();

                request.log = function () { };
            };

            var validationResponse = function () {};

            for (var i = 50; i > 0; i--) {
                Validation.response(request, validationResponse);
            }
        });

        it('should report an error when sample is 100 and making 25 invalid requests', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.onInvalid = 'report';
            request._route.config.response.sample = 25;
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            request.log = function (tags, data) {

                expect(data).to.contain('not allowed to be undefined');
                done();

                request.log = function () { };
            };

            var validationResponse = function () {};

            for (var i = 100; i > 0; i--) {
                Validation.response(request, validationResponse);
            }
        });

        it('should not return an error when sample is 1 and making 1 invalid requests', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.sample = 1;
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should report an error when responding with invalid response param and onInvalid is report', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.onInvalid = 'report';
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            request.log = function (tags, data) {

                expect(data).to.contain('not allowed to be undefined');
                done();
            };

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
            });
        });

        it('should raise an error when validating a non-object response', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._response = Hapi.Response.generate('test');

            Validation.response(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });

        it('doesn\'t perform validation when response is true', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, response: true } };

            var query = null;
            var request = createRequestObject(query, route);

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });
    });

    describe('#path', function () {

        var route = { method: 'GET', path: '/{id}', config: { handler: testHandler, validate: { path: { id: N().required() } } } };

        it('should not raise an error when responding with valid param in the path', function (done) {

            var request = createRequestObjectFromPath('/21', { id: 21 }, route);

            Validation.path(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with an invalid path param', function (done) {

            var request = createRequestObjectFromPath('/test', { id: 'test' }, route);

            Validation.path(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });

        it('doesn\'t perform validation when path is true', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { path: true } } };

            var query = null;
            var request = createRequestObject(query, route);

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });
    });

    describe('#query', function () {

        it('doesn\'t perform validation when query is true', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { query: true } } };

            var query = null;
            var request = createRequestObject(query, route);

            Validation.query(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should not raise an error when responding with valid param in the querystring', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { query: { username: S().min(7)  } } } };
            var query = { username: 'username' };
            var request = createRequestObject(query, route);

            Validation.query(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with an invalid querystring param', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { query: { username: S().min(7) } } } };
            var query = { username: '1' };
            var request = createRequestObject(query, route);

            Validation.query(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });
    });

    describe('#payload', function () {

        it('doesn\'t perform validation when schema is true', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { schema: true } } };

            var payload = null;
            var request = createRequestObject(null, route, payload);

            Validation.payload(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should not raise an error when responding with valid param in the payload', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { schema: { username: S().min(7)  } } } };
            var payload = { username: 'username' };
            var request = createRequestObject(null, route, payload);

            Validation.payload(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with an invalid payload param', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { schema: { username: S().required() } } } };
            var payload = { username: '' };
            var request = createRequestObject(null, route, payload);

            Validation.payload(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });
    });
});<commit_msg>Fixing response validation tests<commit_after>// Load modules

var Chai = require('chai');
var Querystring = require('querystring');
var Hapi = require('../helpers');
var Validation = process.env.TEST_COV ? require('../../lib-cov/validation') : require('../../lib/validation');

// Declare internals

var internals = {};

// Test shortcuts

var expect = Chai.expect;

var S = Hapi.types.String,
    N = Hapi.types.Number,
    O = Hapi.types.Object,
    B = Hapi.types.Boolean;

describe('Validation', function () {

    var testHandler = function (hapi, reply) {

        reply('ohai');
    };

    var createRequestObject = function (query, route, payload) {

        var qstr = Querystring.stringify(query);
        var routeClone = Hapi.utils.clone(route);

        return {
            url: {
                search: '?' + qstr,
                query: query,
                pathname: routeClone.path,
                path: routeClone.path + '?' + qstr,//'/config?choices=1&choices=2',
                href: routeClone.path + '?' + qstr //'/config?choices=1&choices=2'
            },
            query: query,
            payload: payload,
            path: routeClone.path,
            method: routeClone.method,
            _route: { config: routeClone.config },
            response: { result: {} }
        };
    };

    var createRequestObjectFromPath = function (path, params, route) {

        var routeClone = Hapi.utils.clone(route);

        return {
            url: {
                pathname: path,
                path: path,
                href: path
            },
            params: params,
            method: routeClone.method,
            _route: { config: routeClone.config },
            response: { result: {} }
        };
    };

    describe('#response', function () {

        var route = { method: 'GET', path: '/', config: { handler: testHandler, response: { schema: { username: S().required() } } } };

        it('should not raise an error when responding with valid param', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);

            request._response = Hapi.Response.generate({ username: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with invalid param', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });

        it('should not raise an error when responding with invalid param and sample is 0', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.sample = 0;
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with invalid param and sample is 100', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.sample = 100;
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            Validation.response(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });

        internals.calculateFailAverage = function (size, sample) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.onInvalid = 'report';
            request._route.config.response.sample = sample;
            request._response = Hapi.Response.generate({ wrongParam: 'test' });
            var failureCount = 0;

            request.log = function () {

                failureCount++;
            };

            var validationResponse = function () {};

            for (var i = size; i > 0; i--) {
                Validation.response(request, validationResponse);
            }

            return (failureCount / size) * 100;
        };

        it('sample percentage results in correct fail rate', function (done) {

            var rates = [];

            for (var i = 50; i > 0; i--) {                                  // Try 50 times and take the max and min
                rates.push(internals.calculateFailAverage(100, 25));
            }

            rates = rates.sort(function (a, b) {

                return a - b;
            });

            expect(rates[0]).to.be.greaterThan(9);                          // accept a 15 point margin
            expect(rates[49]).to.be.lessThan(41);

            done();
        });

        it('should report an error when responding with invalid response param and onInvalid is report', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._route.config.response.onInvalid = 'report';
            request._response = Hapi.Response.generate({ wrongParam: 'test' });

            request.log = function (tags, data) {

                expect(data).to.contain('not allowed to be undefined');
                done();
            };

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
            });
        });

        it('should raise an error when validating a non-object response', function (done) {

            var query = { username: 'walmart' };
            var request = createRequestObject(query, route);
            request._response = Hapi.Response.generate('test');

            Validation.response(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });

        it('doesn\'t perform validation when response is true', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, response: true } };

            var query = null;
            var request = createRequestObject(query, route);

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });
    });

    describe('#path', function () {

        var route = { method: 'GET', path: '/{id}', config: { handler: testHandler, validate: { path: { id: N().required() } } } };

        it('should not raise an error when responding with valid param in the path', function (done) {

            var request = createRequestObjectFromPath('/21', { id: 21 }, route);

            Validation.path(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with an invalid path param', function (done) {

            var request = createRequestObjectFromPath('/test', { id: 'test' }, route);

            Validation.path(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });

        it('doesn\'t perform validation when path is true', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { path: true } } };

            var query = null;
            var request = createRequestObject(query, route);

            Validation.response(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });
    });

    describe('#query', function () {

        it('doesn\'t perform validation when query is true', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { query: true } } };

            var query = null;
            var request = createRequestObject(query, route);

            Validation.query(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should not raise an error when responding with valid param in the querystring', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { query: { username: S().min(7)  } } } };
            var query = { username: 'username' };
            var request = createRequestObject(query, route);

            Validation.query(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with an invalid querystring param', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { query: { username: S().min(7) } } } };
            var query = { username: '1' };
            var request = createRequestObject(query, route);

            Validation.query(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });
    });

    describe('#payload', function () {

        it('doesn\'t perform validation when schema is true', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { schema: true } } };

            var payload = null;
            var request = createRequestObject(null, route, payload);

            Validation.payload(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should not raise an error when responding with valid param in the payload', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { schema: { username: S().min(7)  } } } };
            var payload = { username: 'username' };
            var request = createRequestObject(null, route, payload);

            Validation.payload(request, function (err) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('should raise an error when responding with an invalid payload param', function (done) {

            var route = { method: 'GET', path: '/', config: { handler: testHandler, validate: { schema: { username: S().required() } } } };
            var payload = { username: '' };
            var request = createRequestObject(null, route, payload);

            Validation.payload(request, function (err) {

                expect(err).to.exist;
                done();
            });
        });
    });
});<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import LoginStatus from './LoginStatus'
import {parseWebviewCookiesByDomain, whoAmI} from '../../electron/ipc_render'
import * as DataUtils from '../helpers/client_data'
import {getCookieByName} from '../helpers/utils'
import {ZHIHU_XSRF_TOKEN_NAME} from '../helpers/const'
import styles from './Settings.css'

const HOME_PAGE_URL = 'https://www.zhihu.com/'
const LOGIN_URL = 'https://www.zhihu.com/signin'
const LOGOUT_URL = 'https://www.zhihu.com/logout'

export default React.createClass({
  propTypes: {
    states: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired
  },

  getInitialState() {
    return {
      isLoggingOut: null
    }
  },

  componentDidUpdate(nextProps, nextState) {
    let isLogin = this.props.states.status.zhihu
    let isLoggingOut = this.state.isLoggingOut
    // 注销时绑定事件
    if (!isLogin && isLoggingOut === false) {
      this.onWebviewMounted()
    }
  },

  componentDidMount() {
    this.onWebviewMounted()
  },

  onWebviewMounted() {
    let webview = this.refs.webview
    if (!webview) {
      console.warn('webview is not mounted.')
      return
    }

    webview.addEventListener('will-navigate', (e) => {
      if (e.url === LOGIN_URL || e.url === HOME_PAGE_URL) {
        let session = webview.getWebContents().session
        parseWebviewCookiesByDomain(session, 'zhihu.com').then(function(cookie) {
          DataUtils.setCookiesByPlatform('zhihu', cookie)
          return whoAmI({cookie, token: getCookieByName(cookie, ZHIHU_XSRF_TOKEN_NAME)})
        }).then(json => {
          this.props.actions.accountUpdate({
            platform: 'zhihu',
            value: {
              username: json.email,
              password: ''
            }
          })
          DataUtils.updateAccount('zhihu', json.email, '')
          this.props.actions.statusUpdate({
            platform: 'zhihu',
            value: true
          })
        }).catch(err => {
          App.alert(err.message)
        })
      }
    })
  },

  handleZhihuLogout() {
    DataUtils.setCookiesByPlatform('zhihu', null)
    this.setState({
      isLoggingOut: true
    }, () => {
      let webview = this.refs.webview
      webview.addEventListener('did-get-response-details', (e) => {
        this.props.actions.statusUpdate({
          platform: 'zhihu',
          value: false
        })
        this.setState({
          isLoggingOut: false
        })
      })
    })
  },

  renderZhihu() {
    let accountMap = this.props.states.account
    let status = this.props.states.status
    if (status.zhihu) {
      return (

          <LoginStatus
            username={accountMap.zhihu.username}
            onLogout={this.handleZhihuLogout}
          />
          {
            this.state.isLoggingOut && (
              <webview
                className={styles.hide}
                ref="webview"
                src={LOGOUT_URL}
                disablewebsecurity
                partition="persist:zhihu"
              />
            )
          }

      )
    }

    return (

        <webview
          className={styles.normal}
          ref="webview"
          src={LOGIN_URL}
          disablewebsecurity
          partition="persist:zhihu"
        />

    )
  },

  render() {
    return (

        {this.renderZhihu()}

    )
  }
})
<commit_msg>login url detect removed<commit_after>import React, {PropTypes} from 'react'
import LoginStatus from './LoginStatus'
import {parseWebviewCookiesByDomain, whoAmI} from '../../electron/ipc_render'
import * as DataUtils from '../helpers/client_data'
import {getCookieByName} from '../helpers/utils'
import {ZHIHU_XSRF_TOKEN_NAME} from '../helpers/const'
import styles from './Settings.css'

const HOME_PAGE_URL = 'https://www.zhihu.com/'
const LOGIN_URL = 'https://www.zhihu.com/signin'
const LOGOUT_URL = 'https://www.zhihu.com/logout'

export default React.createClass({
  propTypes: {
    states: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired
  },

  getInitialState() {
    return {
      isLoggingOut: null
    }
  },

  componentDidUpdate(nextProps, nextState) {
    let isLogin = this.props.states.status.zhihu
    let isLoggingOut = this.state.isLoggingOut
    // 注销时绑定事件
    if (!isLogin && isLoggingOut === false) {
      this.onWebviewMounted()
    }
  },

  componentDidMount() {
    this.onWebviewMounted()
  },

  onWebviewMounted() {
    let webview = this.refs.webview
    if (!webview) {
      console.warn('webview is not mounted.')
      return
    }

    webview.addEventListener('will-navigate', (e) => {
      // TODO 暂时忽略点击其它连接的跳转
      let session = webview.getWebContents().session
      parseWebviewCookiesByDomain(session, 'zhihu.com').then(function(cookie) {
        DataUtils.setCookiesByPlatform('zhihu', cookie)
        return whoAmI({cookie, token: getCookieByName(cookie, ZHIHU_XSRF_TOKEN_NAME)})
      }).then(json => {
        this.props.actions.accountUpdate({
          platform: 'zhihu',
          value: {
            username: json.email,
            password: ''
          }
        })
        DataUtils.updateAccount('zhihu', json.email, '')
        this.props.actions.statusUpdate({
          platform: 'zhihu',
          value: true
        })
      }).catch(err => {
        App.alert(err.message)
      })
    })
  },

  handleZhihuLogout() {
    DataUtils.setCookiesByPlatform('zhihu', null)
    this.setState({
      isLoggingOut: true
    }, () => {
      let webview = this.refs.webview
      webview.addEventListener('did-get-response-details', (e) => {
        this.props.actions.statusUpdate({
          platform: 'zhihu',
          value: false
        })
        this.setState({
          isLoggingOut: false
        })
      })
    })
  },

  renderZhihu() {
    let accountMap = this.props.states.account
    let status = this.props.states.status
    if (status.zhihu) {
      return (

          <LoginStatus
            username={accountMap.zhihu.username}
            onLogout={this.handleZhihuLogout}
          />
          {
            this.state.isLoggingOut && (
              <webview
                className={styles.hide}
                ref="webview"
                src={LOGOUT_URL}
                disablewebsecurity
                partition="persist:zhihu"
              />
            )
          }

      )
    }

    return (

        <webview
          className={styles.normal}
          ref="webview"
          src={LOGIN_URL}
          disablewebsecurity
          partition="persist:zhihu"
        />

    )
  },

  render() {
    return (

        {this.renderZhihu()}

    )
  }
})
<|endoftext|>


<commit_before>var util = require('../util.test');

module.exports = function() {
	var body = 'test__';
	util.request({
		url: 'http://test.whistlejs.com/',
		body: body
	}, function(res, data) {
		data.body.should.be.equal(body);
	});

	util.request({
		url: 'http://rule4.test.whistlejs.com/abc?abc=1',
		body: body
	}, function(res, data) {
		data.body.should.be.equal(body);
	});

	util.request('http://rule.test.whistlejs.com/', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
	});

	util.request('http://rule1.test.whistlejs.com/?abc=123#cdb', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/?test1abc=123');
	});

	util.request('http://rule2.test.whistlejs.com/?abc=1', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/?test2');
	});

	util.request('http://rule2.test.whistlejs.com/?abc=', function(res, data) {
		data.should.not.have.property('type');
		data.headers.host.should.equal('rule2.test.whistlejs.com');
	});

	util.request('http://rule3.test.whistlejs.com/abcd', function(res, data) {
		data.should.not.have.property('type');
		data.headers.host.should.not.equal('host.test.whistlejs.com');
	});

	util.request('http://rule3.test.whistlejs.com/abc', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/?test2');
	});

	util.request('http://rule4.test.whistlejs.com/abc', function(res, data) {
		data.should.not.have.property('type');
		data.headers.host.should.not.equal('host.test.whistlejs.com');
	});

	util.request('http://rule4.test.whistlejs.com/abc?abc=1', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/?test2');
	});

	util.request('http://testrule5.test.whistlejs.com/abc?abc=1#aaaa', function(res, data) {
		data.should.not.have.property('type');
		data.headers.host.should.not.equal('host.test.whistlejs.com');
	});

	util.request('http://testrule5.test.whistlejs.com/abc?test=1#aaaa', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/abc?test=1');
	});

	util.request('http://testrule5.abc.test.whistlejs.com/?test=1#aaaa', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.abc.test.whistlejs.com');
		data.url.should.endWith('/?test=1');
	});
};<commit_msg>test: rule<commit_after>var util = require('../util.test');

module.exports = function() {
	var body = 'test__';
	util.request({
		url: 'http://test.whistlejs.com/',
		body: body
	}, function(res, data) {
		data.body.should.be.equal(body);
	});

	util.request({
		url: 'http://rule4.test.whistlejs.com/abc?abc=1',
		body: body
	}, function(res, data) {
		data.body.should.be.equal(body);
	});

	util.request('http://rule.test.whistlejs.com/', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
	});

	util.request('http://rule1.test.whistlejs.com/?abc=123#cdb', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/?test1abc=123');
	});

	util.request('http://rule2.test.whistlejs.com/?abc=1', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/?test2');
	});

	util.request('http://rule2.test.whistlejs.com/?abc=', function(res, data) {
		data.should.not.have.property('type');
		data.headers.host.should.equal('rule2.test.whistlejs.com');
	});

	util.request('http://rule3.test.whistlejs.com/abcd', function(res, data) {
		data.should.not.have.property('type');
		data.headers.host.should.not.equal('host.test.whistlejs.com');
	});

	util.request('http://rule3.test.whistlejs.com/abc', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/?test2');
	});

	util.request('http://rule4.test.whistlejs.com/abc', function(res, data) {
		data.should.not.have.property('type');
		data.headers.host.should.not.equal('host.test.whistlejs.com');
	});

	util.request('http://rule4.test.whistlejs.com/abc?abc=1', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/?test2');
	});

	util.request('http://testrule5.test.whistlejs.com/abc?abc=1#aaaa', function(res, data) {
		data.should.not.have.property('type');
		data.headers.host.should.not.equal('host.test.whistlejs.com');
	});

	var test = '9999999999';

	util.request('http://testrule5.test.whistlejs.com/abc?test=' + test + '#aaaa', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.test.whistlejs.com');
		data.url.should.endWith('/abc?test=' + test + '');
	});

	util.request('http://testrule5.abc.test.whistlejs.com/?test=' + test + '#aaaa', function(res, data) {
		data.type.should.equal('server');
		data.headers.host.should.equal('host.abc.test.whistlejs.com');
		data.url.should.endWith('/?test=' + test + '');
	});
};<|endoftext|>


<commit_before>import motFeed from './mot-feed.html';

//import filters from '../../filters';

export default function(angularModule) {

    /**
   * Controller: displays feed for main page
   */

    angularModule.directive('feed', function() {
        return {
            replace: true,
            restrict: 'E',
            template: motFeed,
            controller: [ '$scope', 'FeedService',
                function( $scope, FeedService ){
                    function compare(A, B) {
                        if (A.time > B.time) {
                            return -1;
                        }
                        else if (A.time < B.time) {
                            return 1;
                        }
                        return 0;
                    };
                    FeedService.query( res => {
                        $scope.projects = res;
                        $scope.projects.sort(compare);
                    });
                    $scope.projectView = function(project){
                        $scope.singleProjectView = project;
                        FeedService.query({'id':project._id}, res => {
                                  $scope.comments = res;
                                  $scope.comments.sort(compare);
                                  console.log($scope.comments);
                                 });
                        $scope.singleProjectView.time = project.time.substring(0,10);
                        //For milestone progress bar:
                        $scope.max = $scope.singleProjectView.progress.length;
                        $scope.value = 0;
                        $scope.singleProjectView.progress.forEach(progress => {
                            if (progress.done === true) {
                                $scope.value += 1;
                            }
                        });

                    };

                    $scope.remaining = function(time, completion){
                        console.log(Date.parse(time), Date.parse(completion) );
                        var remains = Math.floor((1+ Date.parse(completion) - Date.now()  )/86400000);
                        console.log(remains, ' is remains');
                        return remains;
                    };

                    $scope.percentTimeUsed = function(time, completion){
                        // percent is  remaining / total
                        var time = Date.parse(time);  //start time
                        var completion = Date.parse(completion);  //completion time
                        //total project days
                        var total =  1 + Math.floor(( completion - time )/86400000);
                        //remaining days from now
                        var remaining = Math.floor((completion - Date.now()  )/86400000);
                        var percentTime = 100 - Math.trunc ( ( (remaining / total) * 100 ) );
                         return percentTime;
                    }

                }
            ]
        };
    });
}
<commit_msg>remove console<commit_after>import motFeed from './mot-feed.html';

//import filters from '../../filters';

export default function(angularModule) {

    /**
   * Controller: displays feed for main page
   */

    angularModule.directive('feed', function() {
        return {
            replace: true,
            restrict: 'E',
            template: motFeed,
            controller: [ '$scope', 'FeedService',
                function( $scope, FeedService ){
                    function compare(A, B) {
                        if (A.time > B.time) {
                            return -1;
                        }
                        else if (A.time < B.time) {
                            return 1;
                        }
                        return 0;
                    };
                    FeedService.query( res => {
                        $scope.projects = res;
                        $scope.projects.sort(compare);
                    });
                    $scope.projectView = function(project){
                        $scope.singleProjectView = project;
                        FeedService.query({'id':project._id}, res => {
                                  $scope.comments = res;
                                  $scope.comments.sort(compare);
                                 });
                        $scope.singleProjectView.time = project.time.substring(0,10);
                        //For milestone progress bar:
                        $scope.max = $scope.singleProjectView.progress.length;
                        $scope.value = 0;
                        $scope.singleProjectView.progress.forEach(progress => {
                            if (progress.done === true) {
                                $scope.value += 1;
                            }
                        });

                    };

                    $scope.remaining = function(time, completion){
                        var remains = Math.floor((1+ Date.parse(completion) - Date.now()  )/86400000);
                        return remains;
                    };

                    $scope.percentTimeUsed = function(time, completion){
                        // percent is  remaining / total
                        var time = Date.parse(time);  //start time
                        var completion = Date.parse(completion);  //completion time
                        //total project days
                        var total =  1 + Math.floor(( completion - time )/86400000);
                        //remaining days from now
                        var remaining = Math.floor((completion - Date.now()  )/86400000);
                        var percentTime = 100 - Math.trunc ( ( (remaining / total) * 100 ) );
                         return percentTime;
                    }

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


<commit_before>const fs = require('fs');
const path = require('path');

const markdownRegex = /\.md$/;

// Returns the markdowns of the documentation in a flat array.
// {
//   pathname: String,
//   filename: String,
// }
function findPagesMarkdown(
  directory = path.resolve(__dirname, '../../../src/pages'),
  pagesMarkdown = [],
) {
  const items = fs.readdirSync(directory);

  items.forEach(item => {
    const itemPath = path.resolve(directory, item);

    if (fs.statSync(itemPath).isDirectory()) {
      findPagesMarkdown(itemPath, pagesMarkdown);
      return;
    }

    if (!markdownRegex.test(item)) {
      return;
    }

    let pathname = itemPath
      .replace(new RegExp(`\\${path.sep}`, 'g'), '/')
      .replace(/^.*\/pages/, '')
      .replace('.md', '');

    // Remove the last pathname segment.
    pathname = pathname
      .split('/')
      .slice(0, 3)
      .join('/');

    pagesMarkdown.push({
      // Relative location in the path (URL) system.
      pathname,
      // Relative location in the file system.
      filename: itemPath,
    });
  });

  return pagesMarkdown;
}

const componentRegex = /^([A-Z][a-z]+)+\.js/;

// Returns the component source in a flat array.
function findComponents(directory, components = []) {
  const items = fs.readdirSync(directory);

  items.forEach(item => {
    const itemPath = path.resolve(directory, item);

    if (fs.statSync(itemPath).isDirectory()) {
      findComponents(itemPath, components);
      return;
    }

    if (!componentRegex.test(item)) {
      return;
    }

    components.push({
      filename: itemPath,
    });
  });

  return components;
}

const jsRegex = /\.js$/;
const blackList = ['/.eslintrc', '/_document'];

// Returns the next.js pages available in a nested format.
function findPages(
  options = {},
  directory = path.resolve(__dirname, '../../../../pages'),
  pages = [],
) {
  fs.readdirSync(directory).forEach(item => {
    const itemPath = path.resolve(directory, item);
    const pathname = itemPath
      .replace(new RegExp(`\\${path.sep}`, 'g'), '/')
      .replace(/^.*\/pages/, '')
      .replace('.js', '');

    if (
      options.front &&
      pathname.indexOf('/demos') === -1 &&
      pathname.indexOf('/api') === -1 &&
      pathname.indexOf('/lab') === -1
    ) {
      return;
    }

    if (fs.statSync(itemPath).isDirectory()) {
      const children = [];
      pages.push({
        pathname,
        children,
      });
      findPages(options, itemPath, children);
      return;
    }

    if (!jsRegex.test(item) || blackList.includes(pathname)) {
      return;
    }

    pages.push({
      pathname,
    });
  });

  return pages;
}

module.exports = {
  findPages,
  findPagesMarkdown,
  findComponents,
};
<commit_msg>[docs] Sort the pages by path and ignore dashes (#10396)<commit_after>const fs = require('fs');
const path = require('path');

const markdownRegex = /\.md$/;

// Returns the markdowns of the documentation in a flat array.
// {
//   pathname: String,
//   filename: String,
// }
function findPagesMarkdown(
  directory = path.resolve(__dirname, '../../../src/pages'),
  pagesMarkdown = [],
) {
  const items = fs.readdirSync(directory);

  items.forEach(item => {
    const itemPath = path.resolve(directory, item);

    if (fs.statSync(itemPath).isDirectory()) {
      findPagesMarkdown(itemPath, pagesMarkdown);
      return;
    }

    if (!markdownRegex.test(item)) {
      return;
    }

    let pathname = itemPath
      .replace(new RegExp(`\\${path.sep}`, 'g'), '/')
      .replace(/^.*\/pages/, '')
      .replace('.md', '');

    // Remove the last pathname segment.
    pathname = pathname
      .split('/')
      .slice(0, 3)
      .join('/');

    pagesMarkdown.push({
      // Relative location in the path (URL) system.
      pathname,
      // Relative location in the file system.
      filename: itemPath,
    });
  });

  return pagesMarkdown;
}

const componentRegex = /^([A-Z][a-z]+)+\.js/;

// Returns the component source in a flat array.
function findComponents(directory, components = []) {
  const items = fs.readdirSync(directory);

  items.forEach(item => {
    const itemPath = path.resolve(directory, item);

    if (fs.statSync(itemPath).isDirectory()) {
      findComponents(itemPath, components);
      return;
    }

    if (!componentRegex.test(item)) {
      return;
    }

    components.push({
      filename: itemPath,
    });
  });

  return components;
}

const jsRegex = /\.js$/;
const blackList = ['/.eslintrc', '/_document'];

// Returns the next.js pages available in a nested format.
function findPages(
  options = {},
  directory = path.resolve(__dirname, '../../../../pages'),
  pages = [],
) {
  fs.readdirSync(directory).forEach(item => {
    const itemPath = path.resolve(directory, item);
    const pathname = itemPath
      .replace(new RegExp(`\\${path.sep}`, 'g'), '/')
      .replace(/^.*\/pages/, '')
      .replace('.js', '');

    if (
      options.front &&
      pathname.indexOf('/demos') === -1 &&
      pathname.indexOf('/api') === -1 &&
      pathname.indexOf('/lab') === -1
    ) {
      return;
    }

    if (fs.statSync(itemPath).isDirectory()) {
      const children = [];
      pages.push({
        pathname,
        children,
      });
      findPages(options, itemPath, children);
      return;
    }

    if (!jsRegex.test(item) || blackList.includes(pathname)) {
      return;
    }

    pages.push({
      pathname,
    });
  });

  // sort by pathnames without '-' so that e.g. card comes before card-action
  pages.sort((a, b) => {
    const pathnameA = a.pathname.replace(/-/g, '');
    const pathnameB = b.pathname.replace(/-/g, '');
    if (pathnameA < pathnameB) return -1;
    if (pathnameA > pathnameB) return 1;
    return 0;
  });

  return pages;
}

module.exports = {
  findPages,
  findPagesMarkdown,
  findComponents,
};
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {next, previous, movieDetail} from '../../redux/playlist';
import {Row, Col, Button, Glyphicon} from 'react-bootstrap';
import Youtube from '../youtube';

import playercss from './player.local.css';

class Player extends Component {
  constructor(props) {
    super(props);

    this.onPreviousClick = this.onPreviousClick.bind(this);
    this.onNextClick = this.onNextClick.bind(this);
  }

  onPreviousClick() {
    let {index, results} = this.props;
    index -= 1;
    if (results.length > 0 && results.length > index){
      let {id} = results[index];
      this.props.previous();
      this.props.movieDetail(id);
    }
  }

  onNextClick() {
    let {index, results} = this.props;
    index += 1;
    if (results.length > 0 && results.length > index){
      let {id} = results[index];
      this.props.next();
      this.props.movieDetail(id);
    }
  }

  render() {
    let {currentMovie} = this.props;

    let player;
    if(currentMovie){
      console.log(currentMovie);
      if(currentMovie.videos.results.length > 0) player = <Youtube id={currentMovie.videos.results[0].key}/>;
      else player =
NO VIDEO FOUND
;
    } else {
      player =
NO VIDEO FOUND

    }

    return (

        <Row>
          <Col xs={6}>
            <Button className={playercss.navbtnprev} onClick={this.onPreviousClick}><Glyphicon
              glyph="chevron-left"/> Previous</Button>
          </Col>
          <Col xs={6}>
            <Button className={playercss.navbtnnext} onClick={this.onNextClick}>Next <Glyphicon
              glyph="chevron-right"/></Button>
          </Col>
        </Row>
        <Row>
          <Col xs={12} className={playercss.frame}>

{player}

          </Col>
        </Row>

    );
  }
}

const mapStateToProps = (state) => ({
  ...state.playlist
});

const mapDispatchToProps = dispatch => {
  return bindActionCreators({previous, next, movieDetail}, dispatch)
};

export default connect(mapStateToProps, mapDispatchToProps)(Player);
<commit_msg>small fix<commit_after>import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {next, previous, movieDetail} from '../../redux/playlist';
import {Row, Col, Button, Glyphicon} from 'react-bootstrap';
import Youtube from '../youtube';

import playercss from './player.local.css';

class Player extends Component {
  constructor(props) {
    super(props);

    this.onPreviousClick = this.onPreviousClick.bind(this);
    this.onNextClick = this.onNextClick.bind(this);
  }

  onPreviousClick() {
    let {index, results} = this.props;
    index -= 1;
    if (results.length > 0 && results.length > index && index >= 0){
      let {id} = results[index];
      this.props.previous();
      this.props.movieDetail(id);
    }
  }

  onNextClick() {
    let {index, results} = this.props;
    index += 1;
    if (results.length > 0 && results.length > index){
      let {id} = results[index];
      this.props.next();
      this.props.movieDetail(id);
    }
  }

  render() {
    let {currentMovie} = this.props;

    let player;
    if(currentMovie){
      console.log(currentMovie);
      if(currentMovie.videos.results.length > 0) player = <Youtube id={currentMovie.videos.results[0].key}/>;
      else player =
NO VIDEO FOUND
;
    } else {
      player =
NO VIDEO FOUND

    }

    return (

        <Row>
          <Col xs={6}>
            <Button className={playercss.navbtnprev} onClick={this.onPreviousClick}><Glyphicon
              glyph="chevron-left"/> Previous</Button>
          </Col>
          <Col xs={6}>
            <Button className={playercss.navbtnnext} onClick={this.onNextClick}>Next <Glyphicon
              glyph="chevron-right"/></Button>
          </Col>
        </Row>
        <Row>
          <Col xs={12} className={playercss.frame}>

{player}

          </Col>
        </Row>

    );
  }
}

const mapStateToProps = (state) => ({
  ...state.playlist
});

const mapDispatchToProps = dispatch => {
  return bindActionCreators({previous, next, movieDetail}, dispatch)
};

export default connect(mapStateToProps, mapDispatchToProps)(Player);
<|endoftext|>


<commit_before>var tape = require('tape'),
    dataflow = require('../../');

tape('field create a field accessor', function(test) {
  var f = dataflow.field('x');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x');
  test.deepEqual(f.fields, ['x']);
  test.equal(f({x:'foo'}), 'foo');
  test.equal(f({x:0}), 0);

  f = dataflow.field('[1].x');
  test.equal(typeof f, 'function');
  test.equal(f.fname, '[1].x');
  test.deepEqual(f.fields, ['[1].x']);
  test.equal(f([{x:'foo'},{x:'bar'}]), 'bar');
  test.equal(f([{x:1},{x:0}]), 0);

  f = dataflow.field('x["y"].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x["y"].z');
  test.deepEqual(f.fields, ['x["y"].z']);
  test.equal(f({x:{y:{z:'bar'}}}), 'bar');
  test.equal(f({x:{y:{z:0}}}), 0);

  f = dataflow.field('x[y].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x[y].z');
  test.deepEqual(f.fields, ['x[y].z']);
  test.equal(f({x:{y:{z:'bar'}}}), 'bar');
  test.equal(f({x:{y:{z:0}}}), 0);

  f = dataflow.field('x["a.b"].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x["a.b"].z');
  test.deepEqual(f.fields, ['x["a.b"].z']);
  test.equal(f({x:{'a.b':{z:'bar'}}}), 'bar');
  test.equal(f({x:{'a.b':{z:0}}}), 0);

  f = dataflow.field('x[a.b].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x[a.b].z');
  test.deepEqual(f.fields, ['x[a.b].z']);
  test.equal(f({x:{'a.b':{z:'bar'}}}), 'bar');
  test.equal(f({x:{'a.b':{z:0}}}), 0);

  f = dataflow.field('x[a b].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x[a b].z');
  test.deepEqual(f.fields, ['x[a b].z']);
  test.equal(f({x:{'a b':{z:'bar'}}}), 'bar');
  test.equal(f({x:{'a b':{z:0}}}), 0);

  f = dataflow.field('x.a b.z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x.a b.z');
  test.deepEqual(f.fields, ['x.a b.z']);
  test.equal(f({x:{'a b':{z:'bar'}}}), 'bar');
  test.equal(f({x:{'a b':{z:0}}}), 0);
  test.end();
});
<commit_msg>Fix typo in field tests.<commit_after>var tape = require('tape'),
    dataflow = require('../../');

tape('field creates a field accessor', function(test) {
  var f = dataflow.field('x');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x');
  test.deepEqual(f.fields, ['x']);
  test.equal(f({x:'foo'}), 'foo');
  test.equal(f({x:0}), 0);

  f = dataflow.field('[1].x');
  test.equal(typeof f, 'function');
  test.equal(f.fname, '[1].x');
  test.deepEqual(f.fields, ['[1].x']);
  test.equal(f([{x:'foo'},{x:'bar'}]), 'bar');
  test.equal(f([{x:1},{x:0}]), 0);

  f = dataflow.field('x["y"].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x["y"].z');
  test.deepEqual(f.fields, ['x["y"].z']);
  test.equal(f({x:{y:{z:'bar'}}}), 'bar');
  test.equal(f({x:{y:{z:0}}}), 0);

  f = dataflow.field('x[y].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x[y].z');
  test.deepEqual(f.fields, ['x[y].z']);
  test.equal(f({x:{y:{z:'bar'}}}), 'bar');
  test.equal(f({x:{y:{z:0}}}), 0);

  f = dataflow.field('x["a.b"].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x["a.b"].z');
  test.deepEqual(f.fields, ['x["a.b"].z']);
  test.equal(f({x:{'a.b':{z:'bar'}}}), 'bar');
  test.equal(f({x:{'a.b':{z:0}}}), 0);

  f = dataflow.field('x[a.b].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x[a.b].z');
  test.deepEqual(f.fields, ['x[a.b].z']);
  test.equal(f({x:{'a.b':{z:'bar'}}}), 'bar');
  test.equal(f({x:{'a.b':{z:0}}}), 0);

  f = dataflow.field('x[a b].z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x[a b].z');
  test.deepEqual(f.fields, ['x[a b].z']);
  test.equal(f({x:{'a b':{z:'bar'}}}), 'bar');
  test.equal(f({x:{'a b':{z:0}}}), 0);

  f = dataflow.field('x.a b.z');
  test.equal(typeof f, 'function');
  test.equal(f.fname, 'x.a b.z');
  test.deepEqual(f.fields, ['x.a b.z']);
  test.equal(f({x:{'a b':{z:'bar'}}}), 'bar');
  test.equal(f({x:{'a b':{z:0}}}), 0);
  test.end();
});
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
    providerUrlRegex: {
        //'bioRxiv': '', doesnt currently have urls
        'Cognitive Sciences ePrint Archive': 'cogprints',
        OSF: 'osf',
        PeerJ: 'peerj',
        arXiv: 'arxiv'
    },

    numMaxChars: 300,
    showBody: false,
    footerIcon: Ember.computed('showBody', function() {
        return this.get('showBody') ? 'caret-up' : 'caret-down';
    }),
    result: null,

    shortDescription: Ember.computed('result', function() {
        let result = this.get('result');
        if (result.description && result.description.length > this.numMaxChars) {
            return result.description.substring(0, this.numMaxChars) + '...';
        }
        return result.description;
    }),

    osfID: function() {
        let re = /osf.io\/(\w+)\/$/;
        if (this.get('result.providers').indexOf('OSF') !== -1)
            for (let i = 0; i < this.get('result.lists.links.length'); i++)
                if (re.test(this.get('result.lists.links')[i].url))
                    return re.exec(this.get('result.lists.links')[i].url)[1];
        return false;
    }.property('result'),

    hyperlink: function() {
        var rule = this.get('providerUrlRegex')[this.get('result.providers.0.name')];
        var matches = [];
        if (rule) {
            matches = this.get('result.lists.links').slice().filter(each => each.url.indexOf(rule) !== -1);
        }
        return matches.length ? matches[0].url : this.get('result.lists.links.0.url');
    }.property('result'),

    actions: {
        toggleShowBody() {
            this.set('showBody', !this.showBody);
        },
        select(item) {
            this.attrs.select(item);
        }
    }

});
<commit_msg>Update hyperlink picker<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
    providerUrlRegex: {
        //'bioRxiv': '', doesnt currently have urls
        Cogprints: /cogprints/,
        OSF: /\/\/(?!api\.)osf.io/,  // Doesn't match api.osf urls
        PeerJ: /peerj/,
        arXiv: /arxivj/
    },

    numMaxChars: 300,
    showBody: false,
    footerIcon: Ember.computed('showBody', function() {
        return this.get('showBody') ? 'caret-up' : 'caret-down';
    }),
    result: null,

    shortDescription: Ember.computed('result', function() {
        let result = this.get('result');
        if (result.description && result.description.length > this.numMaxChars) {
            return result.description.substring(0, this.numMaxChars) + '...';
        }
        return result.description;
    }),

    osfID: function() {
        let re = /osf.io\/(\w+)\/$/;
        if (this.get('result.providers').indexOf('OSF') !== -1)
            for (let i = 0; i < this.get('result.lists.links.length'); i++)
                if (re.test(this.get('result.lists.links')[i].url))
                    return re.exec(this.get('result.lists.links')[i].url)[1];
        return false;
    }.property('result'),

    hyperlink: function() {
        var re = null;
        for (let i = 0; i < this.get('result.providers.length'); i++)
            re = this.providerUrlRegex[this.get('result.providers')[i].name] || null;

        if (!re) return this.get('result.lists.links.0.url');

        for (let j = 0; j < this.get('result.lists.links.length') j++);
            if (re.test(this.get('result.lists.links')[j].url))
                return this.get('result.lists.links')[j].url;
    }.property('result'),

    actions: {
        toggleShowBody() {
            this.set('showBody', !this.showBody);
        },
        select(item) {
            this.attrs.select(item);
        }
    }

});
<|endoftext|>


<commit_before>/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * IMA SDK integration plugin for Video.js. For more information see
 * https://www.github.com/googleads/videojs-ima
 */

var browsers = require('./content/capabilities');

browsers.browsers.forEach(function(browser) {

    describe('Basic Tests ' + browser.name, function() {

    this.timeout(0);
    this.slow(15000);

    var webdriver = require('selenium-webdriver'),
        until = webdriver.until;
        By = webdriver.By;

    var driver;

    before(async function() {
      driver = await new webdriver.Builder()
            .forBrowser(browser.capabilities.browserName)
            .usingServer(browser.server)
            .withCapabilities(browser.capabilities)
            .build();
      return driver;
    });

    after(async function() {
      await driver.quit();
    });

    it( 'Displays ad UI ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=linear');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), 60000);
      await driver.wait(until.elementIsVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), 60000);
    });

    it( 'Hides controls when ad ends ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=linear');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), 60000);
      await driver.wait(until.elementIsNotVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), 60000);
      await driver.sleep();
    });

    it( 'Plays content when ad ends ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=linear');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), 60000);
      await driver.wait(until.elementIsNotVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), 60000);
      await driver.wait(until.elementTextContains(log, 'playing'), 60000);
      await driver.sleep();
    });

    it( 'Displays skip ad button ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=skippable');
      await driver.findElement(By.id('content_video')).click();
      let log = driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), 60000);
      await driver.switchTo().frame(driver.findElement(
        By.css('#content_video_ima-ad-container > div:nth-child(1) > iframe')));
      let skipButton = await driver.findElement(
        By.css('div.videoAdUi button.videoAdUiSkipButton'));
      await driver.wait(until.elementIsVisible(skipButton), 60000);
      await driver.sleep();
    });

     it( 'VMAP: Preroll ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=vmap_preroll');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), 60000);
      await driver.wait(until.elementIsVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), 60000);
      await driver.sleep();
    });

    it( 'VMAP: Midroll ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=vmap_midroll');
      await driver.findElement(By.id('content_video')).click();
      await driver.wait(until.elementIsVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), 60000);
      await driver.sleep();
    });

    it( 'Nonlinear ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=nonlinear');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), 60000);
      await driver.switchTo().frame(driver.findElement(
        By.css('#content_video_ima-ad-container > div:nth-child(1) > iframe')));
      await driver.wait(until.elementIsVisible(driver.findElement(
        By.css('div.nonLinearContainer div.overlayContainer'))), 60000);
      await driver.sleep();
    });

    it( 'Handles ad error 303: wrappers ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=error_303');
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, '303'), 60000);
      await driver.sleep();
    });
  });
});
<commit_msg>revert changes part 2<commit_after>/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * IMA SDK integration plugin for Video.js. For more information see
 * https://www.github.com/googleads/videojs-ima
 */

var browsers = require('./content/capabilities');

browsers.browsers.forEach(function(browser) {

    describe('Basic Tests ' + browser.name, function() {

    this.timeout(0);
    this.slow(15000);

    var webdriver = require('selenium-webdriver'),
        until = webdriver.until;
        By = webdriver.By;

    var driver;

    var timeoutTime = 60000; //ms

    beforeEach(async function() {
      driver = await new webdriver.Builder()
            .forBrowser(browser.capabilities.browserName)
            .usingServer(browser.server)
            .withCapabilities(browser.capabilities)
            .build();
      return driver;
    });

    afterEach(async function() {
      await driver.quit();
    });

    it( 'Displays ad UI ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=linear');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), timeoutTime);
      await driver.wait(until.elementIsVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), timeoutTime);
    });

    it( 'Hides controls when ad ends ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=linear');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), timeoutTime);
      await driver.wait(until.elementIsNotVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), timeoutTime);
      await driver.sleep();
    });

    it( 'Plays content when ad ends ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=linear');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), timeoutTime);
      await driver.wait(until.elementIsNotVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), timeoutTime);
      await driver.wait(until.elementTextContains(log, 'playing'), timeoutTime);
      await driver.sleep();
    });

    it( 'Displays skip ad button ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=skippable');
      await driver.findElement(By.id('content_video')).click();
      let log = driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), timeoutTime);
      await driver.switchTo().frame(driver.findElement(
        By.css('#content_video_ima-ad-container > div:nth-child(1) > iframe')));
      let skipButton = await driver.findElement(
        By.css('div.videoAdUi button.videoAdUiSkipButton'));
      await driver.wait(until.elementIsVisible(skipButton), timeoutTime);
      await driver.sleep();
    });

     it( 'VMAP: Preroll ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=vmap_preroll');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), timeoutTime);
      await driver.wait(until.elementIsVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), timeoutTime);
      await driver.sleep();
    });

    it( 'VMAP: Midroll ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=vmap_midroll');
      await driver.findElement(By.id('content_video')).click();
      await driver.wait(until.elementIsVisible(driver.findElement(
        By.id('content_video_ima-controls-div'))), timeoutTime);
      await driver.sleep();
    });

    it( 'Nonlinear ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=nonlinear');
      await driver.findElement(By.id('content_video')).click();
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, 'start'), timeoutTime);
      await driver.switchTo().frame(driver.findElement(
        By.css('#content_video_ima-ad-container > div:nth-child(1) > iframe')));
      await driver.wait(until.elementIsVisible(driver.findElement(
        By.css('div.nonLinearContainer div.overlayContainer'))), timeoutTime);
      await driver.sleep();
    });

    it( 'Handles ad error 303: wrappers ' + browser.name, async function(){
      await driver.get('http://localhost:8000/test/webdriver/index.html?ad=error_303');
      let log = await driver.findElement(By.id('log'));
      await driver.wait(until.elementTextContains(log, '303'), timeoutTime);
      await driver.sleep();
    });
  });
});
<|endoftext|>