<commit_before>(function(angular) {
  var indexOf = [].indexOf || function(item) {
    for (var i = 0, l = this.length; i < l; i++) {
      if (i in this && this[i] === item) return i;
    }
    return -1;
  };

  angular.module('pickadate.utils', [])
    .factory('pickadateUtils', ['dateFilter',
      function(dateFilter) {
        return {
          isDate: function(obj) {
            return Object.prototype.toString.call(obj) === '[object Date]';
          },

          stringToDate: function(dateString) {
            if (this.isDate(dateString)) return new Date(dateString);
            var dateParts = dateString.split('-'),
              year = dateParts[0],
              month = dateParts[1],
              day = dateParts[2];

            // set hour to 3am to easily avoid DST change
            return new Date(year, month - 1, day, 3);
          },

          dateRange: function(first, last, initial, format) {
            var date, i, _i, dates = [];

            if (!format) format = 'yyyy-MM-dd';

            for (i = _i = first; first <= last ? _i < last : _i > last; i = first <= last ? ++_i : --_i) {
              date = this.stringToDate(initial);
              date.setDate(date.getDate() + i);
              dates.push(dateFilter(date, format));
            }
            return dates;
          }
        };
      }
  ]);

  angular.module('pickadate', ['pickadate.utils'])

  .factory('offset', function() {

    return function(element, parentWin) {
      if (parentWin === window || parentWin === document) {
        parentWin = document.body;
      }
      parentWin.style.position = 'relative';

      var offsetTop = element.offsetTop;
      var offsetLeft = element.offsetLeft;

      var offset = {
        top: offsetTop,
        left: offsetLeft
      };
      while (element.offsetParent && element.offsetParent !== parentWin) {
        offset.top += element.offsetParent.offsetTop;
        offset.left += element.offsetParent.offsetLeft;
      }

      return offset;

    }

  })

  .directive('input', ['$compile', 'offset', function($compile, offset){
    return {
      scope: {
        ngModel: '=',
        min: '=',
        max: '=',
        disabledDates: '='
      },
      restrict: 'E',
      link: function($scope, $elements, $attrs, controller) {
        if($attrs.type !== 'date'){
          return;
        }
        else{
          if($elements[0].type == 'date')return;
        }

        var pickdateTemp = '

';

        var $div = angular.element(pickdateTemp);

        angular.element(document.body).append($div);

        $compile($div)($scope);

        $div.css({display: 'none'});

        $elements.on('click', function(ev){

          ev.stopPropagation();

          $div.css({display: 'block'});

        })/*.on('blur', function(){
          setTimeout(function(){
            $div.css({display: 'none'});
          }, 200);
        });*/

        angular.element(document).on('click', function(){
          $div.css({display: 'none'});
        });

        angular.element(window).on('resize', setPosition);

        setPosition();

        function setPosition() {
            var offsetPos = offset($elements[0], window);
            var top = (offsetPos.top + $elements[0].offsetHeight + 2) + 'px';
            var left = offsetPos.left + 'px';

            $div.css({
              left: left,
              top: top
            });
        }
      }
    };
  }])
  .directive('pickadate', ['$locale', 'pickadateUtils', 'dateFilter', '$compile',
    function($locale, dateUtils, dateFilter, $compile) {

      return {
        require: 'ngModel',
        scope: {
          date: '=ngModel',
          minDate: '=',
          maxDate: '=',
          disabledDates: '='
        },
        template: '
' +
          '
' +
          '
' +
          '上月' +
          '下月' +
          '
' +
          '
' +
          '{{currentDate | date:"MM yyyy"}}' +
          '
' +
          '
' +
          '
' +
          '
' +
          '
' +
          '
' +
          '{{dayName}}' +
          '
' +
          '
' +
          '
' +
          '
' +
          '{{d.date | date:"d"}}' +
          '
' +
          '
' +
          '
' +
          '
' +
          '
',

        link: function(scope, element, attrs, ngModel) {
          var minDate = scope.minDate && dateUtils.stringToDate(scope.minDate),
            maxDate = scope.maxDate && dateUtils.stringToDate(scope.maxDate),
            disabledDates = scope.disabledDates || [],
            currentDate = new Date();

          // scope.dayNames = $locale.DATETIME_FORMATS['SHORTDAY'];
          scope.dayNames = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
          scope.currentDate = currentDate;

          scope.render = function(initialDate) {

            initialDate = new Date(initialDate.getFullYear(), initialDate.getMonth(), 1, 3);

            var currentMonth = initialDate.getMonth() + 1;
            var dayCount = new Date(initialDate.getFullYear(), initialDate.getMonth() + 1, 0, 3).getDate();

            var prevDates = dateUtils.dateRange(-initialDate.getDay(), 0, initialDate);
            var currentMonthDates = dateUtils.dateRange(0, dayCount, initialDate);

            var lastDate = dateUtils.stringToDate(currentMonthDates[currentMonthDates.length - 1]);
            var nextMonthDates = dateUtils.dateRange(1, 7 - lastDate.getDay(), lastDate);
            var allDates = prevDates.concat(currentMonthDates, nextMonthDates);
            var dates = [];
            var today = dateFilter(new Date(), 'yyyy-MM-dd');

            // Add an extra row if needed to make the calendar to have 6 rows
            if (allDates.length / 7 < 6) {
              allDates = allDates.concat(dateUtils.dateRange(1, 8, allDates[allDates.length - 1]));
            }

            var nextMonthInitialDate = new Date(initialDate);
            nextMonthInitialDate.setMonth(currentMonth);

            scope.allowPrevMonth = !minDate || initialDate > minDate;
            scope.allowNextMonth = !maxDate || nextMonthInitialDate < maxDate;

            for (var i = 0; i < allDates.length; i++) {
              var className = "",
                date = allDates[i];

              if (date < scope.minDate || date > scope.maxDate || dateFilter(date, 'M') !== currentMonth.toString()) {
                className = 'pickadate-disabled';
              } else if (indexOf.call(disabledDates, date) >= 0) {
                className = 'pickadate-disabled pickadate-unavailable';
              } else {
                className = 'pickadate-enabled';
              }

              if (date === today) {
                className += ' pickadate-today';
              }

              dates.push({
                date: date,
                className: className
              });
            }

            scope.dates = dates;
          };

          scope.setDate = function(dateObj) {

            if (isDateDisabled(dateObj)) return;
            ngModel.$setViewValue(dateObj.date);
          };

          ngModel.$render = function() {
            // console.log(ngModel)
            if ((date = ngModel.$modelValue) && (indexOf.call(disabledDates, date) === -1)) {
              scope.currentDate = currentDate = dateUtils.stringToDate(date);
            } else if (date) {
              // if the initial date set by the user is in the disabled dates list, unset it
              scope.setDate({});
            }
            scope.render(currentDate);
          };

          scope.changeMonth = function(offset) {
            // If the current date is January 31th, setting the month to date.getMonth() + 1
            // sets the date to March the 3rd, since the date object adds 30 days to the current
            // date. Settings the date to the 2nd day of the month is a workaround to prevent this
            // behaviour
            currentDate.setDate(1);
            currentDate.setMonth(currentDate.getMonth() + offset);
            scope.render(currentDate);
          };

          function isDateDisabled(dateObj) {
            return (/pickadate-disabled/.test(dateObj.className));
          }
        }
      };
    }
  ]);
})(window.angular);<commit_msg>first<commit_after>(function(angular) {
  var indexOf = [].indexOf || function(item) {
    for (var i = 0, l = this.length; i < l; i++) {
      if (i in this && this[i] === item) return i;
    }
    return -1;
  };

  angular.module('pickadate.utils', [])
    .factory('pickadateUtils', ['dateFilter',
      function(dateFilter) {
        return {
          isDate: function(obj) {
            return Object.prototype.toString.call(obj) === '[object Date]';
          },

          stringToDate: function(dateString) {
            if (this.isDate(dateString)) return new Date(dateString);
            var dateParts = dateString.split('-'),
              year = dateParts[0],
              month = dateParts[1],
              day = dateParts[2];

            // set hour to 3am to easily avoid DST change
            return new Date(year, month - 1, day, 3);
          },

          dateRange: function(first, last, initial, format) {
            var date, i, _i, dates = [];

            if (!format) format = 'yyyy-MM-dd';

            for (i = _i = first; first <= last ? _i < last : _i > last; i = first <= last ? ++_i : --_i) {
              date = this.stringToDate(initial);
              date.setDate(date.getDate() + i);
              dates.push(dateFilter(date, format));
            }
            return dates;
          }
        };
      }
  ]);

  angular.module('pickadate', ['pickadate.utils'])

  .factory('offset', function() {

    return function(element, parentWin) {
      if (parentWin === window || parentWin === document) {
        parentWin = document.body;
      }
      parentWin.style.position = 'relative';

      var offsetTop = element.offsetTop;
      var offsetLeft = element.offsetLeft;

      var offset = {
        top: offsetTop,
        left: offsetLeft
      };
      while (element.offsetParent && element.offsetParent !== parentWin) {
        offset.top += element.offsetParent.offsetTop;
        offset.left += element.offsetParent.offsetLeft;
      }

      return offset;

    }

  })

  .directive('input', ['$compile', 'offset', function($compile, offset){
    return {
      scope: {
        ngModel: '=',
        min: '=',
        max: '=',
        disabledDates: '='
      },
      restrict: 'E',
      link: function($scope, $elements, $attrs, controller) {
        if($attrs.type !== 'date'){
          return;
        }
        else{
          if($elements[0].type == 'date')return;
        }

        var pickdateTemp = '

';

        var $div = angular.element(pickdateTemp);

        angular.element(document.body).append($div);

        $compile($div)($scope);

        $div.css({display: 'none'});

        $elements.on('click', function(ev){

          ev.stopPropagation();

          $div.css({display: 'block'});

        });

        angular.element(document).on('click', function(){
          $div.css({display: 'none'});
        });

        angular.element(window).on('resize', setPosition);

        setPosition();

        function setPosition() {
            var offsetPos = offset($elements[0], window);
            var top = (offsetPos.top + $elements[0].offsetHeight + 2) + 'px';
            var left = offsetPos.left + 'px';

            $div.css({
              left: left,
              top: top
            });
        }
      }
    };
  }])
  .directive('pickadate', ['$locale', 'pickadateUtils', 'dateFilter', '$compile',
    function($locale, dateUtils, dateFilter, $compile) {

      return {
        require: 'ngModel',
        scope: {
          date: '=ngModel',
          minDate: '=',
          maxDate: '=',
          disabledDates: '='
        },
        template: '
' +
          '
' +
          '
' +
          '上月' +
          '下月' +
          '
' +
          '
' +
          '{{currentDate | date:"MM yyyy"}}' +
          '
' +
          '
' +
          '
' +
          '
' +
          '
' +
          '
' +
          '{{dayName}}' +
          '
' +
          '
' +
          '
' +
          '
' +
          '{{d.date | date:"d"}}' +
          '
' +
          '
' +
          '
' +
          '
' +
          '
',

        link: function(scope, element, attrs, ngModel) {
          var minDate = scope.minDate && dateUtils.stringToDate(scope.minDate),
            maxDate = scope.maxDate && dateUtils.stringToDate(scope.maxDate),
            disabledDates = scope.disabledDates || [],
            currentDate = new Date();

          // scope.dayNames = $locale.DATETIME_FORMATS['SHORTDAY'];
          scope.dayNames = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
          scope.currentDate = currentDate;

          scope.render = function(initialDate) {

            initialDate = new Date(initialDate.getFullYear(), initialDate.getMonth(), 1, 3);

            var currentMonth = initialDate.getMonth() + 1;
            var dayCount = new Date(initialDate.getFullYear(), initialDate.getMonth() + 1, 0, 3).getDate();

            var prevDates = dateUtils.dateRange(-initialDate.getDay(), 0, initialDate);
            var currentMonthDates = dateUtils.dateRange(0, dayCount, initialDate);

            var lastDate = dateUtils.stringToDate(currentMonthDates[currentMonthDates.length - 1]);
            var nextMonthDates = dateUtils.dateRange(1, 7 - lastDate.getDay(), lastDate);
            var allDates = prevDates.concat(currentMonthDates, nextMonthDates);
            var dates = [];
            var today = dateFilter(new Date(), 'yyyy-MM-dd');

            // Add an extra row if needed to make the calendar to have 6 rows
            if (allDates.length / 7 < 6) {
              allDates = allDates.concat(dateUtils.dateRange(1, 8, allDates[allDates.length - 1]));
            }

            var nextMonthInitialDate = new Date(initialDate);
            nextMonthInitialDate.setMonth(currentMonth);

            scope.allowPrevMonth = !minDate || initialDate > minDate;
            scope.allowNextMonth = !maxDate || nextMonthInitialDate < maxDate;

            for (var i = 0; i < allDates.length; i++) {
              var className = "",
                date = allDates[i];

              if (date < scope.minDate || date > scope.maxDate || dateFilter(date, 'M') !== currentMonth.toString()) {
                className = 'pickadate-disabled';
              } else if (indexOf.call(disabledDates, date) >= 0) {
                className = 'pickadate-disabled pickadate-unavailable';
              } else {
                className = 'pickadate-enabled';
              }

              if (date === today) {
                className += ' pickadate-today';
              }

              dates.push({
                date: date,
                className: className
              });
            }

            scope.dates = dates;
          };

          scope.setDate = function(dateObj) {

            if (isDateDisabled(dateObj)) return;
            ngModel.$setViewValue(dateObj.date);
          };

          ngModel.$render = function() {
            // console.log(ngModel)
            if ((date = ngModel.$modelValue) && (indexOf.call(disabledDates, date) === -1)) {
              scope.currentDate = currentDate = dateUtils.stringToDate(date);
            } else if (date) {
              // if the initial date set by the user is in the disabled dates list, unset it
              scope.setDate({});
            }
            scope.render(currentDate);
          };

          scope.changeMonth = function(offset) {
            // If the current date is January 31th, setting the month to date.getMonth() + 1
            // sets the date to March the 3rd, since the date object adds 30 days to the current
            // date. Settings the date to the 2nd day of the month is a workaround to prevent this
            // behaviour
            currentDate.setDate(1);
            currentDate.setMonth(currentDate.getMonth() + offset);
            scope.render(currentDate);
          };

          function isDateDisabled(dateObj) {
            return (/pickadate-disabled/.test(dateObj.className));
          }
        }
      };
    }
  ]);
})(window.angular);<|endoftext|>


<commit_before>// this will have all of a copy of the normal fs methods as well
const fs = require('fs.extra');
const path = require('path');
const argv = require('yargs').argv;
const MANIFEST = 'package.json';
const exec = require('child_process').exec;
const through = require('through2');
const _ = require('lodash');
const gutil = require('gulp-util');

const MODULE_PATH = './modules';
const BUILD_PATH = './build/dist';
const DEV_PATH = './build/dev';

// get only subdirectories that contain package.json with 'main' property
function isModuleDirectory(filePath) {
  try {
    const manifestPath = path.join(filePath, MANIFEST);
    if (fs.statSync(manifestPath).isFile()) {
      const module = require(manifestPath);
      return module && module.main;
    }
  }
  catch (error) {}
}

module.exports = {
  parseBrowserArgs: function (argv) {
    return (argv.browsers) ? argv.browsers.split(',') : [];
  },

  toCapitalCase: function (str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  },

  jsonifyHTML: function (str) {
    console.log(arguments);
    return str.replace(/\n/g, '')
        .replace(/<\//g, '<\\/')
        .replace(/\/>/g, '\\/>');
  },
  getArgModules() {
    var modules = (argv.modules || '').split(',').filter(module => !!module);

    try {
      if (modules.length === 1 && path.extname(modules[0]).toLowerCase() === '.json') {
        var moduleFile = modules[0];

        modules = JSON.parse(
          fs.readFileSync(moduleFile, 'utf8')
        );
      }
    } catch(e) {
      throw new gutil.PluginError({
        plugin: 'modules',
        message: 'failed reading: ' + argv.modules
      });
    }

    return modules;
  },
  getModules: _.memoize(function(externalModules) {
    externalModules = externalModules || [];
    var internalModules;
    try {
      internalModules = fs.readdirSync(MODULE_PATH)
        .filter(file => !(/(^|\/)\.[^\/\.]/g).test(file))
        .reduce((memo, file) => {
          var moduleName = file.split(new RegExp('[.' + path.sep + ']'))[0];
          var filePath = path.join(MODULE_PATH, file);
          var modulePath = path.join(__dirname, filePath)
          if (fs.lstatSync(filePath).isDirectory()) {
            modulePath = path.join(__dirname, filePath, "index.js")
          }
          memo[modulePath] = moduleName;
          return memo;
        }, {});
    } catch(err) {
      internalModules = {};
    }
    return Object.assign(externalModules.reduce((memo, module) => {
      try {
        var modulePath = require.resolve(module);
        memo[modulePath] = module;
      } catch(err) {
        // do something
      }
      return memo;
    }, internalModules));
  }),

  getBuiltModules: function(dev, externalModules) {
    var modules = this.getModuleNames(externalModules);
    if(Array.isArray(externalModules)) {
      modules = _.intersection(modules, externalModules);
    }
    return modules.map(name => path.join(__dirname, dev ? DEV_PATH : BUILD_PATH, name + '.js'));
  },

  getBuiltPrebidCoreFile: function(dev) {
    return path.join(__dirname, dev ? DEV_PATH : BUILD_PATH, 'prebid-core' + '.js');
  },

  getModulePaths: function(externalModules) {
    var modules = this.getModules(externalModules);
    return Object.keys(modules);
  },

  getModuleNames: function(externalModules) {
    return _.values(this.getModules(externalModules));
  },

  nameModules: function(externalModules) {
    var modules = this.getModules(externalModules);
    return through.obj(function(file, enc, done) {
      file.named = modules[file.path] ? modules[file.path] : 'prebid';
      this.push(file);
      done();
    })
  },

  /*
   * Get source files for analytics subdirectories in top-level `analytics`
   * directory adjacent to Prebid.js.
   * Invoke with gulp <task> --analytics
   * Returns an array of source files for inclusion in build process
   */
  getAnalyticsSources: function(directory) {
    if (!argv.analytics) {return [];} // empty arrays won't affect a standard build

    const directoryContents = fs.readdirSync(directory);
    return directoryContents
      .filter(file => isModuleDirectory(path.join(directory, file)))
      .map(moduleDirectory => {
        const module = require(path.join(directory, moduleDirectory, MANIFEST));
        return path.join(directory, moduleDirectory, module.main);
      });
  },

  createEnd2EndTestReport : function(targetDestinationDir) {
    var browsers = require('./browsers.json');
    var env = [];
    var input = 'bs';
    for(var key in browsers) {
      if(key.substring(0, input.length) === input && browsers[key].browser !== 'iphone') {
        env.push(key);
      }
    }

    //create new directory structure
    fs.rmrfSync(targetDestinationDir);
    env.forEach(item => {
      fs.mkdirpSync(targetDestinationDir + '/' + item);
    });

    //move xml files to newly created directory
    var walker = fs.walk('./build/coverage/e2e/reports');
    walker.on("file", function (root, stat, next) {
      env.forEach(item => {
        if(stat.name.search(item) !== -1) {
          var src = root + '/' + stat.name;
          var dest = targetDestinationDir + '/' + item + '/' + stat.name;
          fs.copy(src, dest, {replace: true}, function(err) {
            if(err) {
              throw err;
            }
          });
        }
      });
      next();
    });

    //run junit-viewer to read xml and create html
    env.forEach(item => {
      //junit-viewer --results="./custom-reports/chrome51" --save="./chrome.html"
      var cmd = 'junit-viewer --results="' + targetDestinationDir + '/' + item + '" --save="' + targetDestinationDir + '/' + item +'.html"';
      exec(cmd);
    });

    //create e2e-results.html
    var html = '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>End to End Testing Result</title><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
Note: Refresh in 2-3 seconds if it says "Cannot get ....."

';
    var li = '';
    var tabs = '';
    env.forEach(function(item,i) {
      i++;
      li = li + '
'+item+'
';
      tabs = tabs + '

';
    });
    html = html + '
' + li + '
' + tabs;
    html = html + '
';

    var filepath = targetDestinationDir + '/results.html';
    fs.openSync(filepath, 'w+');
    fs.writeFileSync(filepath, html);
  }
};
<commit_msg>fixes #1331 module bundling on windows (#1332)<commit_after>// this will have all of a copy of the normal fs methods as well
const fs = require('fs.extra');
const path = require('path');
const argv = require('yargs').argv;
const MANIFEST = 'package.json';
const exec = require('child_process').exec;
const through = require('through2');
const _ = require('lodash');
const gutil = require('gulp-util');

const MODULE_PATH = './modules';
const BUILD_PATH = './build/dist';
const DEV_PATH = './build/dev';

// get only subdirectories that contain package.json with 'main' property
function isModuleDirectory(filePath) {
  try {
    const manifestPath = path.join(filePath, MANIFEST);
    if (fs.statSync(manifestPath).isFile()) {
      const module = require(manifestPath);
      return module && module.main;
    }
  }
  catch (error) {}
}

module.exports = {
  parseBrowserArgs: function (argv) {
    return (argv.browsers) ? argv.browsers.split(',') : [];
  },

  toCapitalCase: function (str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  },

  jsonifyHTML: function (str) {
    console.log(arguments);
    return str.replace(/\n/g, '')
        .replace(/<\//g, '<\\/')
        .replace(/\/>/g, '\\/>');
  },
  getArgModules() {
    var modules = (argv.modules || '').split(',').filter(module => !!module);

    try {
      if (modules.length === 1 && path.extname(modules[0]).toLowerCase() === '.json') {
        var moduleFile = modules[0];

        modules = JSON.parse(
          fs.readFileSync(moduleFile, 'utf8')
        );
      }
    } catch(e) {
      throw new gutil.PluginError({
        plugin: 'modules',
        message: 'failed reading: ' + argv.modules
      });
    }

    return modules;
  },
  getModules: _.memoize(function(externalModules) {
    externalModules = externalModules || [];
    var internalModules;
    try {
      internalModules = fs.readdirSync(MODULE_PATH)
        .filter(file => !(/(^|\/)\.[^\/\.]/g).test(file))
        .reduce((memo, file) => {
          var moduleName = file.split(new RegExp('[.\\' + path.sep + ']'))[0];
          var filePath = path.join(MODULE_PATH, file);
          var modulePath = path.join(__dirname, filePath)
          if (fs.lstatSync(filePath).isDirectory()) {
            modulePath = path.join(__dirname, filePath, "index.js")
          }
          memo[modulePath] = moduleName;
          return memo;
        }, {});
    } catch(err) {
      internalModules = {};
    }
    return Object.assign(externalModules.reduce((memo, module) => {
      try {
        var modulePath = require.resolve(module);
        memo[modulePath] = module;
      } catch(err) {
        // do something
      }
      return memo;
    }, internalModules));
  }),

  getBuiltModules: function(dev, externalModules) {
    var modules = this.getModuleNames(externalModules);
    if(Array.isArray(externalModules)) {
      modules = _.intersection(modules, externalModules);
    }
    return modules.map(name => path.join(__dirname, dev ? DEV_PATH : BUILD_PATH, name + '.js'));
  },

  getBuiltPrebidCoreFile: function(dev) {
    return path.join(__dirname, dev ? DEV_PATH : BUILD_PATH, 'prebid-core' + '.js');
  },

  getModulePaths: function(externalModules) {
    var modules = this.getModules(externalModules);
    return Object.keys(modules);
  },

  getModuleNames: function(externalModules) {
    return _.values(this.getModules(externalModules));
  },

  nameModules: function(externalModules) {
    var modules = this.getModules(externalModules);
    return through.obj(function(file, enc, done) {
      file.named = modules[file.path] ? modules[file.path] : 'prebid';
      this.push(file);
      done();
    })
  },

  /*
   * Get source files for analytics subdirectories in top-level `analytics`
   * directory adjacent to Prebid.js.
   * Invoke with gulp <task> --analytics
   * Returns an array of source files for inclusion in build process
   */
  getAnalyticsSources: function(directory) {
    if (!argv.analytics) {return [];} // empty arrays won't affect a standard build

    const directoryContents = fs.readdirSync(directory);
    return directoryContents
      .filter(file => isModuleDirectory(path.join(directory, file)))
      .map(moduleDirectory => {
        const module = require(path.join(directory, moduleDirectory, MANIFEST));
        return path.join(directory, moduleDirectory, module.main);
      });
  },

  createEnd2EndTestReport : function(targetDestinationDir) {
    var browsers = require('./browsers.json');
    var env = [];
    var input = 'bs';
    for(var key in browsers) {
      if(key.substring(0, input.length) === input && browsers[key].browser !== 'iphone') {
        env.push(key);
      }
    }

    //create new directory structure
    fs.rmrfSync(targetDestinationDir);
    env.forEach(item => {
      fs.mkdirpSync(targetDestinationDir + '/' + item);
    });

    //move xml files to newly created directory
    var walker = fs.walk('./build/coverage/e2e/reports');
    walker.on("file", function (root, stat, next) {
      env.forEach(item => {
        if(stat.name.search(item) !== -1) {
          var src = root + '/' + stat.name;
          var dest = targetDestinationDir + '/' + item + '/' + stat.name;
          fs.copy(src, dest, {replace: true}, function(err) {
            if(err) {
              throw err;
            }
          });
        }
      });
      next();
    });

    //run junit-viewer to read xml and create html
    env.forEach(item => {
      //junit-viewer --results="./custom-reports/chrome51" --save="./chrome.html"
      var cmd = 'junit-viewer --results="' + targetDestinationDir + '/' + item + '" --save="' + targetDestinationDir + '/' + item +'.html"';
      exec(cmd);
    });

    //create e2e-results.html
    var html = '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>End to End Testing Result</title><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
Note: Refresh in 2-3 seconds if it says "Cannot get ....."

';
    var li = '';
    var tabs = '';
    env.forEach(function(item,i) {
      i++;
      li = li + '
'+item+'
';
      tabs = tabs + '

';
    });
    html = html + '
' + li + '
' + tabs;
    html = html + '
';

    var filepath = targetDestinationDir + '/results.html';
    fs.openSync(filepath, 'w+');
    fs.writeFileSync(filepath, html);
  }
};
<|endoftext|>


<commit_before>define(["pat/checklist"], function(pattern) {

    describe("checklist-pattern", function() {

        beforeEach(function() {
            $("
", {id: "lab"}).appendTo(document.body);
        });

        afterEach(function() {
            $("#lab").remove();
        });

        describe("jQuery plugin usage", function() {

            describe("Initialise via jQuery", function() {
                it("Specify options via API", function() {
                    $("#lab").html("

");
                    $("#lab div").patternChecklist({select: ".one", deselect: ".two"});
                    var $trigger = $("#lab div");
                    expect($trigger.data("patternChecklist")).toEqual({select: ".one", deselect: ".two"});
                });

                it("Parse options from DOM", function() {
                    $("#lab").html("

");
                    $("#lab div").patternChecklist();
                    var $trigger = $("#lab div");
                    expect($trigger.data("patternChecklist")).toEqual({select: ".one", deselect: ".two"});
                });
            });
        });
    });

});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Fix lint.<commit_after>define([], function() {

    describe("checklist-pattern", function() {

        beforeEach(function() {
            $("
", {id: "lab"}).appendTo(document.body);
        });

        afterEach(function() {
            $("#lab").remove();
        });

        describe("jQuery plugin usage", function() {

            describe("Initialise via jQuery", function() {
                it("Specify options via API", function() {
                    $("#lab").html("

");
                    $("#lab div").patternChecklist({select: ".one", deselect: ".two"});
                    var $trigger = $("#lab div");
                    expect($trigger.data("patternChecklist")).toEqual({select: ".one", deselect: ".two"});
                });

                it("Parse options from DOM", function() {
                    $("#lab").html("

");
                    $("#lab div").patternChecklist();
                    var $trigger = $("#lab div");
                    expect($trigger.data("patternChecklist")).toEqual({select: ".one", deselect: ".two"});
                });
            });
        });
    });

});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>// (function () {
//   'use strict';

//   angular
//     .module('core')
//     .controller('HomeController', HomeController);

//   function HomeController() {
//     var vm = this;
//     vm.authentication = Authentication;
//   }
// }());
<commit_msg>Update home.client.controller.js<commit_after> function () {
   'use strict';

   angular
     .module('core')
     .controller('HomeController', HomeController);

   function HomeController() {
     var vm = this;
     vm.authentication = Authentication;
   }
 };
<|endoftext|>


<commit_before>"use strict;"

var dateFromInput = document.getElementById("dateFromInput");
var dateToInput = document.getElementById("dateToInput");
var placeholderDiv = document.getElementById("placeholder1");
var tooltip = "tooltip1";
var tooltipDiv = "#" + tooltip;
var legendDiv = document.getElementById("legend");
var graphDiv = document.getElementById("graph1");
var sampleSelector = document.getElementById("sampleSelector");
var metricSelector = document.getElementById("metricSelector");
var encoderSelector = document.getElementById("encoderSelector");
var executeButton = document.getElementById("fetch");

var thousand = 1000;

var legendTitleClass = "legendTitle";
var legendInfoClass = "legendInfo";

/**
 * Handling link between Encoder and Git Revision
 */
// Specify your encoder with the git revision base link
var mapEncoder = new Object();
mapEncoder["https://github.com/videolan/x265"] = "x265";
mapEncoder["https://www.google.ch/#q="] = "xTOTO";

function gitUrlToEncoder(gitUrl) {
    return mapEncoder[gitUrl];
}

// Combine a git revision with his base link
function mapEncoGitToLink(encoder, git_commit) {
    return encoder + '/commit/' + git_commit;
}

// Date format displayed
function formatDate(date) {
    return '{0} {1}'.format(
        date.toLocaleDateString(),
        date.toLocaleTimeString()
    );
}

/* source:
* http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery */
String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

/**
 * Activate the chosen selector (Sample and Encoders)
 */
$(".my_select_box").chosen({
    no_results_text: "Oops, nothing found!",
    search_contains: true,
    width: "100%"
});

/**
 * Configure the DateTime input adding a new system to chose the minutes and seconds
 * and activate it (dateInputFrom and dateInputTo)
 * From the example : http://trentrichardson.com/examples/timepicker/
 */
var myControl = {
    create: function (tp_inst, obj, unit, val, min, max, step) {
        $('<input class="ui-timepicker-input" value="' + val + '" style="width:50%">')
            .appendTo(obj)
            .spinner({
                min: min,
                max: max,
                step: step,
                change: function (e, ui) { // key events
                    // don't call if api was used and not key press
                    if (e.originalEvent !== undefined)
                        tp_inst._onTimeChange();
                    tp_inst._onSelectHandler();
                },
                spin: function (e, ui) { // spin events
                    tp_inst.control.value(tp_inst, obj, unit, ui.value);
                    tp_inst._onTimeChange();
                    tp_inst._onSelectHandler();
                }
            });
        return obj;
    },
    options: function (tp_inst, obj, unit, opts, val) {
        if (typeof (opts) == 'string' && val !== undefined)
            return obj.find('.ui-timepicker-input').spinner(opts, val);
        return obj.find('.ui-timepicker-input').spinner(opts);
    },
    value: function (tp_inst, obj, unit, val) {
        if (val !== undefined)
            return obj.find('.ui-timepicker-input').spinner('value', val);
        return obj.find('.ui-timepicker-input').spinner('value');
    }
};

$(dateFromInput).datetimepicker({
    controlType: myControl,
    timeFormat: 'HH:mm:ss',
});
$(dateFromInput).datetimepicker('setDate', (new Date()));

$(dateToInput).datetimepicker({
    controlType: myControl,
    timeFormat: 'HH:mm:ss'
});
$(dateToInput).datetimepicker('setDate', (new Date()));

/**
 * Generate the graph in function of the data
 */
function generateGraph(data) {
    //http://stackoverflow.com/questions/9150964/identifying-hovered-point-with-flot
    //Create a table of tuple (x,y) for each encoder metric

    var xyEncoder = new Object();
    var encoderLabel = new Object();

    for (var i = 0; i < data.length; i++) {

        var entry = data[i];
        var date = new Date(entry.date*thousand); //Unix format To standard one;
        // Each key creates a new line in the graph
        var key = [entry.git_url, entry.git_commit, entry.source];

        // Create a corresponding label for this graph line
        if (!(key in xyEncoder)) {
            xyEncoder[key] = [];

            // How the label is displayed
            hTitle = $('', {'class': legendTitleClass})
                .text('{0}: '.format(entry.source));
            hGitA = $('', {
                'href': mapEncoGitToLink(entry.git_url, entry.git_commit),
                'title': entry.git_commit,
            }).text(gitUrlToEncoder(entry.git_url));
            hInfo = $('', {'class': legendInfoClass})
                .append(hGitA)
                .append(' ({0})'.format(formatDate(date)))
            encoderLabel[key] = hTitle[0].outerHTML + hInfo[0].outerHTML;
        }

        // Each point is bitrate-value pair
        xyEncoder[key].push([entry.bitrate, entry.value]);
    }

    // Create the dataset for the plot
    var dataset = [];
    for (key in xyEncoder) {
        var entry = xyEncoder[key];
        dataset.push({
            "label": encoderLabel[key],
            "data": entry.sort(),
        });
    }

    var precisionAxis = 3;
    //https://github.com/flot/flot/blob/master/API.md
    //Plot
    var plot = $.plot(placeholderDiv, dataset, {
        series: {
            lines: {
                show: true
            },
            points: {
                show: true
            }
        },
        grid: {
            hoverable: true,
        },
        xaxis: {
            tickFormatter: function (v) {
                return v.toFixed(precisionAxis) + " kb/s";
            }
        },
        yaxis: {
            tickFormatter: function (v) {
                return v.toFixed(precisionAxis) + " dB";
            }
        },
        legend: {
            container: legendDiv
        }
    });

    //Design of the tooltip
    $("

").css({
        position: "absolute",
        display: "none",
        border: "4px solid #fdd",
        padding: "2px",
        color: "#fff",
        "background-color": "#000",
        opacity: 0.80
    }).appendTo("body");

    //Event when the mouse go over a point
    var mouseover = false;
    var timeout;

    $(placeholderDiv).bind("plothover", function (event, pos, item) {
        //Show information
        if (item) {
            clearTimeout(timeout);
            var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(2);
            $(tooltipDiv).html("
" + item.series.label + "

" + x + "kb/s" + " at " + y + "dB
")
                .css({
                    top: item.pageY + 5,
                    left: item.pageX + 5,
                    "border-color": item.series.color
                })
                .fadeIn(200);
        } else {
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                $(tooltipDiv).fadeOut(200);
            }, 750);
        }
    });

    $(tooltipDiv).bind("mouseenter", function (event) {
        clearTimeout(timeout);
    });

    // Modify position of the legend
    $(legendDiv).css("position", "relative");
    $(legendDiv).css("top", -$(placeholderDiv).height());
    $(legendDiv).css("right", -$(placeholderDiv).width() * 1.03);
    $(legendDiv).css("background-color", "rgb(255, 255, 255, 0.85)");

    $(graphDiv).hide();
    $(graphDiv).toggle("explode");
    //$( "#toggle" ).toggle( "explode" );
    //$('#placeholder1 > div.legend > div, #placeholder1 > div.legend > table').css("right", -parseInt($('#placeholder1 > div.legend > div').css("width")));
    //$('#placeholder1 > div.legend > table').css("background-image", "url(getPhoto.jpg)").css("background-size", "contain");
};

/**
 * Fill the inputs fron the variable input
 */

// Source : http://stackoverflow.com/questions/3149072/determine-if-html-select-contains-a-value-in-any-of-its-child-options
function optionExists(select, val) {
    return $(select).find("option").filter(function () {
        return this.value === val;
    }).length !== 0;
}

function fill_encoders(data) {
    $.each(data, function (i, v) {
        if(!optionExists(encoderSelector, v)) {
            $(encoderSelector).append("<option>" + v + "</option>");
            $(encoderSelector).trigger('chosen:updated');
        }
    })
}

function fill_samplers(data) {
    $.each(data, function (i, v) {
        if(!optionExists(sampleSelector, v)) {
            $(sampleSelector).append("<option>" + v + "</option>");
            $(sampleSelector).trigger('chosen:updated');
        }
    })
}

function fill_metrics(data) {
    $.each(data, function (i, v) {
        if(!optionExists(metricSelector, v)) {
            $(metricSelector).append("<option>" + v + "</option>");
        }
    });
}

/**
 * Ajax Query for Execute ! button (MAIN)
 *
 * Reyssor: crochets, c'est dictionnaire et brackets listes je crois
 */
$(executeButton).click(function () {

    //Create options and fill it with the different field
    var options = {
        "date_from": "",
        "date_to": "",
        "source": [],
        "metric": "",
        "git_url": []
    };

    //Convertion to UNIX date time
    options.date_from = $(dateFromInput).datetimepicker("getDate").getTime()/thousand;
    options.date_to = $(dateToInput).datetimepicker("getDate").getTime()/thousand;

    $(sampleSelector).find("option:selected").each(function (i, selected) {
        options.source.push(selected.label);
    });

    options.metric = metricSelector.options[metricSelector.selectedIndex].text;

    $(encoderSelector).find("option:selected").each(function (i, selected) {
        options.git_url.push(selected.label);
    });

    jQuery.ajax({
        type: "GET",
        dataType: "json",
        url: "http://duckyduck.gnugen.ch/webui/json",
        data: options,
        success: function (data, textStatus, jqXHR) {
            // La reponse du serveur est contenu dans data
            // On peut faire ce qu'on veut avec ici
            generateGraph(data); //< --- a placer dans la success function
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.error(['API error json', jqXHR, textStatus, errorThrown]);
        }
    });

});

jQuery.ajax({
    type: "GET",
    dataType: "json",
    url: "http://duckyduck.gnugen.ch/webui/json_gui",
    data: {},
    xhrFields: {
        withCredentials: true
    },
    success: function (data, textStatus, jqXHR) {
        fill_encoders(data.encoders);
        fill_samplers(data.samplers);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.error(['API error encoders', jqXHR, textStatus, errorThrown]);
    }
});

fill_metrics(['PSNR', 'SSIM']); // FIXME: no API
<commit_msg>Change the default From date to 7 days before the current date<commit_after>"use strict;"

var dateFromInput = document.getElementById("dateFromInput");
var dateToInput = document.getElementById("dateToInput");
var placeholderDiv = document.getElementById("placeholder1");
var tooltip = "tooltip1";
var tooltipDiv = "#" + tooltip;
var legendDiv = document.getElementById("legend");
var graphDiv = document.getElementById("graph1");
var sampleSelector = document.getElementById("sampleSelector");
var metricSelector = document.getElementById("metricSelector");
var encoderSelector = document.getElementById("encoderSelector");
var executeButton = document.getElementById("fetch");

var thousand = 1000;

var legendTitleClass = "legendTitle";
var legendInfoClass = "legendInfo";

/**
 * Handling link between Encoder and Git Revision
 */
// Specify your encoder with the git revision base link
var mapEncoder = new Object();
mapEncoder["https://github.com/videolan/x265"] = "x265";
mapEncoder["https://www.google.ch/#q="] = "xTOTO";

function gitUrlToEncoder(gitUrl) {
    return mapEncoder[gitUrl];
}

// Combine a git revision with his base link
function mapEncoGitToLink(encoder, git_commit) {
    return encoder + '/commit/' + git_commit;
}

// Date format displayed
function formatDate(date) {
    return '{0} {1}'.format(
        date.toLocaleDateString(),
        date.toLocaleTimeString()
    );
}

/* source:
* http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery */
String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

/**
 * Activate the chosen selector (Sample and Encoders)
 */
$(".my_select_box").chosen({
    no_results_text: "Oops, nothing found!",
    search_contains: true,
    width: "100%"
});

/**
 * Configure the DateTime input adding a new system to chose the minutes and seconds
 * and activate it (dateInputFrom and dateInputTo)
 * From the example : http://trentrichardson.com/examples/timepicker/
 */
var myControl = {
    create: function (tp_inst, obj, unit, val, min, max, step) {
        $('<input class="ui-timepicker-input" value="' + val + '" style="width:50%">')
            .appendTo(obj)
            .spinner({
                min: min,
                max: max,
                step: step,
                change: function (e, ui) { // key events
                    // don't call if api was used and not key press
                    if (e.originalEvent !== undefined)
                        tp_inst._onTimeChange();
                    tp_inst._onSelectHandler();
                },
                spin: function (e, ui) { // spin events
                    tp_inst.control.value(tp_inst, obj, unit, ui.value);
                    tp_inst._onTimeChange();
                    tp_inst._onSelectHandler();
                }
            });
        return obj;
    },
    options: function (tp_inst, obj, unit, opts, val) {
        if (typeof (opts) == 'string' && val !== undefined)
            return obj.find('.ui-timepicker-input').spinner(opts, val);
        return obj.find('.ui-timepicker-input').spinner(opts);
    },
    value: function (tp_inst, obj, unit, val) {
        if (val !== undefined)
            return obj.find('.ui-timepicker-input').spinner('value', val);
        return obj.find('.ui-timepicker-input').spinner('value');
    }
};

$(dateFromInput).datetimepicker({
    controlType: myControl,
    timeFormat: 'HH:mm:ss',
});
var dateFrom = new Date();
dateFrom.setDate(dateFrom.getDate() - 7); //Remove 7 days to the current date
$(dateFromInput).datetimepicker('setDate', dateFrom);

$(dateToInput).datetimepicker({
    controlType: myControl,
    timeFormat: 'HH:mm:ss'
});
$(dateToInput).datetimepicker('setDate', (new Date()));

/**
 * Generate the graph in function of the data
 */
function generateGraph(data) {
    //http://stackoverflow.com/questions/9150964/identifying-hovered-point-with-flot
    //Create a table of tuple (x,y) for each encoder metric

    var xyEncoder = new Object();
    var encoderLabel = new Object();

    for (var i = 0; i < data.length; i++) {

        var entry = data[i];
        var date = new Date(entry.date*thousand); //Unix format To standard one;
        // Each key creates a new line in the graph
        var key = [entry.git_url, entry.git_commit, entry.source];

        // Create a corresponding label for this graph line
        if (!(key in xyEncoder)) {
            xyEncoder[key] = [];

            // How the label is displayed
            hTitle = $('', {'class': legendTitleClass})
                .text('{0}: '.format(entry.source));
            hGitA = $('', {
                'href': mapEncoGitToLink(entry.git_url, entry.git_commit),
                'title': entry.git_commit,
            }).text(gitUrlToEncoder(entry.git_url));
            hInfo = $('', {'class': legendInfoClass})
                .append(hGitA)
                .append(' ({0})'.format(formatDate(date)))
            encoderLabel[key] = hTitle[0].outerHTML + hInfo[0].outerHTML;
        }

        // Each point is bitrate-value pair
        xyEncoder[key].push([entry.bitrate, entry.value]);
    }

    // Create the dataset for the plot
    var dataset = [];
    for (key in xyEncoder) {
        var entry = xyEncoder[key];
        dataset.push({
            "label": encoderLabel[key],
            "data": entry.sort(),
        });
    }

    var precisionAxis = 3;
    //https://github.com/flot/flot/blob/master/API.md
    //Plot
    var plot = $.plot(placeholderDiv, dataset, {
        series: {
            lines: {
                show: true
            },
            points: {
                show: true
            }
        },
        grid: {
            hoverable: true,
        },
        xaxis: {
            tickFormatter: function (v) {
                return v.toFixed(precisionAxis) + " kb/s";
            }
        },
        yaxis: {
            tickFormatter: function (v) {
                return v.toFixed(precisionAxis) + " dB";
            }
        },
        legend: {
            container: legendDiv
        }
    });

    //Design of the tooltip
    $("

").css({
        position: "absolute",
        display: "none",
        border: "4px solid #fdd",
        padding: "2px",
        color: "#fff",
        "background-color": "#000",
        opacity: 0.80
    }).appendTo("body");

    //Event when the mouse go over a point
    var mouseover = false;
    var timeout;

    $(placeholderDiv).bind("plothover", function (event, pos, item) {
        //Show information
        if (item) {
            clearTimeout(timeout);
            var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(2);
            $(tooltipDiv).html("
" + item.series.label + "

" + x + "kb/s" + " at " + y + "dB
")
                .css({
                    top: item.pageY + 5,
                    left: item.pageX + 5,
                    "border-color": item.series.color
                })
                .fadeIn(200);
        } else {
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                $(tooltipDiv).fadeOut(200);
            }, 750);
        }
    });

    $(tooltipDiv).bind("mouseenter", function (event) {
        clearTimeout(timeout);
    });

    // Modify position of the legend
    $(legendDiv).css("position", "relative");
    $(legendDiv).css("top", -$(placeholderDiv).height());
    $(legendDiv).css("right", -$(placeholderDiv).width() * 1.03);
    $(legendDiv).css("background-color", "rgb(255, 255, 255, 0.85)");

    $(graphDiv).hide();
    $(graphDiv).toggle("explode");
    //$( "#toggle" ).toggle( "explode" );
    //$('#placeholder1 > div.legend > div, #placeholder1 > div.legend > table').css("right", -parseInt($('#placeholder1 > div.legend > div').css("width")));
    //$('#placeholder1 > div.legend > table').css("background-image", "url(getPhoto.jpg)").css("background-size", "contain");
};

/**
 * Fill the inputs fron the variable input
 */

// Source : http://stackoverflow.com/questions/3149072/determine-if-html-select-contains-a-value-in-any-of-its-child-options
function optionExists(select, val) {
    return $(select).find("option").filter(function () {
        return this.value === val;
    }).length !== 0;
}

function fill_encoders(data) {
    $.each(data, function (i, v) {
        if(!optionExists(encoderSelector, v)) {
            $(encoderSelector).append("<option>" + v + "</option>");
            $(encoderSelector).trigger('chosen:updated');
        }
    })
}

function fill_samplers(data) {
    $.each(data, function (i, v) {
        if(!optionExists(sampleSelector, v)) {
            $(sampleSelector).append("<option>" + v + "</option>");
            $(sampleSelector).trigger('chosen:updated');
        }
    })
}

function fill_metrics(data) {
    $.each(data, function (i, v) {
        if(!optionExists(metricSelector, v)) {
            $(metricSelector).append("<option>" + v + "</option>");
        }
    });
}

/**
 * Ajax Query for Execute ! button (MAIN)
 *
 * Reyssor: crochets, c'est dictionnaire et brackets listes je crois
 */
$(executeButton).click(function () {

    //Create options and fill it with the different field
    var options = {
        "date_from": "",
        "date_to": "",
        "source": [],
        "metric": "",
        "git_url": []
    };

    //Convertion to UNIX date time
    options.date_from = $(dateFromInput).datetimepicker("getDate").getTime()/thousand;
    options.date_to = $(dateToInput).datetimepicker("getDate").getTime()/thousand;

    $(sampleSelector).find("option:selected").each(function (i, selected) {
        options.source.push(selected.label);
    });

    options.metric = metricSelector.options[metricSelector.selectedIndex].text;

    $(encoderSelector).find("option:selected").each(function (i, selected) {
        options.git_url.push(selected.label);
    });

    jQuery.ajax({
        type: "GET",
        dataType: "json",
        url: "http://duckyduck.gnugen.ch/webui/json",
        data: options,
        success: function (data, textStatus, jqXHR) {
            // La reponse du serveur est contenu dans data
            // On peut faire ce qu'on veut avec ici
            generateGraph(data); //< --- a placer dans la success function
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.error(['API error json', jqXHR, textStatus, errorThrown]);
        }
    });

});

jQuery.ajax({
    type: "GET",
    dataType: "json",
    url: "http://duckyduck.gnugen.ch/webui/json_gui",
    data: {},
    xhrFields: {
        withCredentials: true
    },
    success: function (data, textStatus, jqXHR) {
        fill_encoders(data.encoders);
        fill_samplers(data.samplers);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.error(['API error encoders', jqXHR, textStatus, errorThrown]);
    }
});

fill_metrics(['PSNR', 'SSIM']); // FIXME: no API
<|endoftext|>


<commit_before>if (Meteor.isClient) {

  // XXX in the future, make the jQuery adapter a separate
  // package and make the choice of back-end library
  // configurable.  Adapters all expose the same DomBackend interface.

  if (! Package.jquery)
    throw new Error("Meteor UI jQuery adapter: jQuery not found.");

  var jQuery = Package.jquery.jQuery;

  var DomBackend = {};
  UI.DomBackend = DomBackend;

  ///// Removal detection and interoperability.

  // For an explanation of this technique, see:
  // http://bugs.jquery.com/ticket/12213#comment:23 .
  //
  // In short, an element is considered "removed" when jQuery
  // cleans up its *private* userdata on the element,
  // which we can detect using a custom event with a teardown
  // hook.

  var JQUERY_REMOVAL_WATCHER_EVENT_NAME = 'meteor_ui_removal_watcher';
  var REMOVAL_CALLBACKS_PROPERTY_NAME = '$meteor_ui_removal_callbacks';
  var NOOP = function () {};

  // Causes `elem` (a DOM element) to be detached from its parent, if any.
  // Whether or not `elem` was detached, causes any callbacks registered
  // with `onRemoveElement` on `elem` and its descendants to fire.
  // Not for use on non-element nodes.
  //
  // This method is modeled after the behavior of jQuery's `$(elem).remove()`,
  // which causes teardown on the subtree being removed.
  DomBackend.removeElement = function (elem) {
    jQuery(elem).remove();
  };

  // Registers a callback function to be called when the given element or
  // one of its ancestors is removed from the DOM via the backend library.
  // The callback function is called at most once, and it receives the element
  // in question as an argument.
  DomBackend.onRemoveElement = function (elem, func) {
    if (! elem[REMOVAL_CALLBACKS_PROPERTY_NAME]) {
      elem[REMOVAL_CALLBACKS_PROPERTY_NAME] = [];

      // Set up the event, only the first time.
      jQuery(elem).on(JQUERY_REMOVAL_WATCHER_EVENT_NAME, NOOP);
    }

    elem[REMOVAL_CALLBACKS_PROPERTY_NAME].push(func);
  };

  jQuery.event.special[JQUERY_REMOVAL_WATCHER_EVENT_NAME] = {
    teardown: function() {
      var elem = this;
      var callbacks = elem[REMOVAL_CALLBACKS_PROPERTY_NAME];
      if (callbacks) {
        for (var i = 0; i < callbacks.length; i++)
          callbacks[i](elem);
        elem[REMOVAL_CALLBACKS_PROPERTY_NAME] = null;
      }
    }
  };

  DomBackend.parseHTML = function (html) {
    // Return an array of nodes.
    //
    // jQuery does fancy stuff like creating an appropriate
    // container element and setting innerHTML on it, as well
    // as working around various IE quirks.
    return jQuery.parseHTML(html) || [];
  };

  // Must use jQuery semantics for `context`, not
  // querySelectorAll's.  In other words, all the parts
  // of `selector` must be found under `context`.
  DomBackend.findBySelector = function (selector, context) {
    return jQuery.find(selector, context);
  };

  DomBackend.newFragment = function (nodeArray) {
    // jQuery fragments are built specially in
    // IE<9 so that they can safely hold HTML5
    // elements.
    return jQuery.buildFragment(nodeArray, document);
  };

  // `selector` is non-null.  `type` is one type (but
  // may be in backend-specific form, e.g. have namespaces).
  // Order fired must be order bound.
  DomBackend.delegateEvents = function (elem, type, selector, handler) {
    $(elem).on(type, selector, handler);
  };

  DomBackend.undelegateEvents = function (elem, type, handler) {
    $(elem).off(type, handler);
  };

  DomBackend.bindEventCapturer = function (elem, type, handler) {
    var wrapper = function (event) {
      event = jQuery.event.fix(event);
      event.currentTarget = event.target;
      // Note: It might improve jQuery interop if we called into jQuery
      // here somehow.  Since we don't use jQuery to dispatch the event,
      // we don't fire any of jQuery's event hooks or anything.  However,
      // since jQuery can't bind capturing handlers, it's not clear
      // where we would hook in.  Internal jQuery functions like `dispatch`
      // are too high-level.
      handler.call(elem, event);
    };
    handler._meteorui_wrapper = wrapper;

    type = this.parseEventType(type);
    // add *capturing* event listener
    elem.addEventListener(type, wrapper, true);
  };

  DomBackend.unbindEventCapturer = function (elem, type, handler) {
    type = this.parseEventType(type);
    elem.removeEventListener(type, handler._meteorui_wrapper, true);
  };

  DomBackend.parseEventType = function (type) {
    // strip off namespaces
    var dotLoc = type.indexOf('.');
    if (dotLoc >= 0)
      return type.slice(0, dotLoc);
    return type;
  };

}<commit_msg>Fix DomBackend to access jQuery consistently<commit_after>if (Meteor.isClient) {

  // XXX in the future, make the jQuery adapter a separate
  // package and make the choice of back-end library
  // configurable.  Adapters all expose the same DomBackend interface.

  if (! Package.jquery)
    throw new Error("Meteor UI jQuery adapter: jQuery not found.");

  var $jq = Package.jquery.jQuery;

  var DomBackend = {};
  UI.DomBackend = DomBackend;

  ///// Removal detection and interoperability.

  // For an explanation of this technique, see:
  // http://bugs.jquery.com/ticket/12213#comment:23 .
  //
  // In short, an element is considered "removed" when jQuery
  // cleans up its *private* userdata on the element,
  // which we can detect using a custom event with a teardown
  // hook.

  var JQUERY_REMOVAL_WATCHER_EVENT_NAME = 'meteor_ui_removal_watcher';
  var REMOVAL_CALLBACKS_PROPERTY_NAME = '$meteor_ui_removal_callbacks';
  var NOOP = function () {};

  // Causes `elem` (a DOM element) to be detached from its parent, if any.
  // Whether or not `elem` was detached, causes any callbacks registered
  // with `onRemoveElement` on `elem` and its descendants to fire.
  // Not for use on non-element nodes.
  //
  // This method is modeled after the behavior of jQuery's `$(elem).remove()`,
  // which causes teardown on the subtree being removed.
  DomBackend.removeElement = function (elem) {
    $jq(elem).remove();
  };

  // Registers a callback function to be called when the given element or
  // one of its ancestors is removed from the DOM via the backend library.
  // The callback function is called at most once, and it receives the element
  // in question as an argument.
  DomBackend.onRemoveElement = function (elem, func) {
    if (! elem[REMOVAL_CALLBACKS_PROPERTY_NAME]) {
      elem[REMOVAL_CALLBACKS_PROPERTY_NAME] = [];

      // Set up the event, only the first time.
      $jq(elem).on(JQUERY_REMOVAL_WATCHER_EVENT_NAME, NOOP);
    }

    elem[REMOVAL_CALLBACKS_PROPERTY_NAME].push(func);
  };

  $jq.event.special[JQUERY_REMOVAL_WATCHER_EVENT_NAME] = {
    teardown: function() {
      var elem = this;
      var callbacks = elem[REMOVAL_CALLBACKS_PROPERTY_NAME];
      if (callbacks) {
        for (var i = 0; i < callbacks.length; i++)
          callbacks[i](elem);
        elem[REMOVAL_CALLBACKS_PROPERTY_NAME] = null;
      }
    }
  };

  DomBackend.parseHTML = function (html) {
    // Return an array of nodes.
    //
    // jQuery does fancy stuff like creating an appropriate
    // container element and setting innerHTML on it, as well
    // as working around various IE quirks.
    return $jq.parseHTML(html) || [];
  };

  // Must use jQuery semantics for `context`, not
  // querySelectorAll's.  In other words, all the parts
  // of `selector` must be found under `context`.
  DomBackend.findBySelector = function (selector, context) {
    return $jq.find(selector, context);
  };

  DomBackend.newFragment = function (nodeArray) {
    // jQuery fragments are built specially in
    // IE<9 so that they can safely hold HTML5
    // elements.
    return $jq.buildFragment(nodeArray, document);
  };

  // `selector` is non-null.  `type` is one type (but
  // may be in backend-specific form, e.g. have namespaces).
  // Order fired must be order bound.
  DomBackend.delegateEvents = function (elem, type, selector, handler) {
    $jq(elem).on(type, selector, handler);
  };

  DomBackend.undelegateEvents = function (elem, type, handler) {
    $jq(elem).off(type, handler);
  };

  DomBackend.bindEventCapturer = function (elem, type, handler) {
    var wrapper = function (event) {
      event = $jq.event.fix(event);
      event.currentTarget = event.target;
      // Note: It might improve jQuery interop if we called into jQuery
      // here somehow.  Since we don't use jQuery to dispatch the event,
      // we don't fire any of jQuery's event hooks or anything.  However,
      // since jQuery can't bind capturing handlers, it's not clear
      // where we would hook in.  Internal jQuery functions like `dispatch`
      // are too high-level.
      handler.call(elem, event);
    };
    handler._meteorui_wrapper = wrapper;

    type = this.parseEventType(type);
    // add *capturing* event listener
    elem.addEventListener(type, wrapper, true);
  };

  DomBackend.unbindEventCapturer = function (elem, type, handler) {
    type = this.parseEventType(type);
    elem.removeEventListener(type, handler._meteorui_wrapper, true);
  };

  DomBackend.parseEventType = function (type) {
    // strip off namespaces
    var dotLoc = type.indexOf('.');
    if (dotLoc >= 0)
      return type.slice(0, dotLoc);
    return type;
  };

}<|endoftext|>


<commit_before>/*
 @author Zakai Hamilton
 @component UIRect
 */

package.ui.rect = function UIRect(me) {
    me.movable = {
        get: function(object) {
            return object.rect_movable;
        },
        set: function(object, value) {
            object.rect_movable = value;
        }
    };
    me.resizable = {
        get: function(object) {
            return object.rect_resizable;
        },
        set: function(object, value) {
            object.rect_resizable = value;
        }
    };
    me.move = {
        set: function (object, value) {
            if(!value) {
                value = me.widget.window.window(object);
            }
            object.addEventListener('mousedown', function (e) {
                if(!value.rect_movable) {
                    e.preventDefault();
                    return;
                }
                me.set(value, "ui.focus.active", true);
                var target_region = me.ui.rect.absolute_region(value);
                var info = {
                    target: value,
                    left: e.clientX-target_region.left,
                    top: e.clientY-target_region.top,
                    width: value.offsetWidth,
                    height: value.offsetHeight
                };
                me.ui.property.notifyAll("ui.theme.add", "transition");
                var move_method = function (e) {
                    var target_region = me.ui.rect.absolute_region(value);
                    var shift_region = {};
                    me.ui.rect.empty_region(shift_region);
                    target_region.left = e.clientX - info.left;
                    target_region.top = e.clientY - info.top;
                    me.ui.rect.set_absolute_region(info.target, target_region);
                    me.ui.property.notify(info.target, "draw", null);
                };
                var release_method = function (e) {
                    removeEventListener('mousemove', move_method);
                    removeEventListener('mouseup', release_method);
                    me.ui.property.notifyAll("ui.theme.remove", "transition");
                };
                addEventListener('mousemove', move_method);
                addEventListener('mouseup', release_method);
                e.preventDefault();
            });
        }
    };
    me.resize = {
        set: function (object, value) {
            if(!value) {
                value = me.widget.window.window(object);
            }
            object.addEventListener('mousedown', function (e) {
                if(!value.rect_resizable) {
                    e.preventDefault();
                    return;
                }
                me.set(value, "ui.focus.active", true);
                var info = {
                    target: value,
                    left: e.clientX,
                    top: e.clientY,
                    width: value.offsetWidth,
                    height: value.offsetHeight
                };
                me.ui.property.notifyAll("ui.theme.add", "transition");
                var move_method = function (e) {
                    var target_region = me.ui.rect.absolute_region(value);
                    var object_region = me.ui.rect.absolute_region(object);
                    var shift_region = {};
                    me.ui.rect.empty_region(shift_region);
                    var min_width = parseInt(getComputedStyle(value).minWidth, 10);
                    var min_height = parseInt(getComputedStyle(value).minHeight, 10);
                    if(object_region.left < target_region.left + (target_region.width / 2)) {
                        target_region.width = target_region.width + (target_region.left - e.clientX);
                        target_region.left = e.clientX;
                    }
                    else {
                        target_region.width = e.clientX - info.left + info.width;
                    }
                    if(object_region.top < target_region.top + (target_region.height / 2)) {
                        target_region.height = target_region.height + (target_region.top - e.clientY);
                        target_region.top = e.clientY;
                    }
                    else {
                        target_region.height = e.clientY - info.top + info.height;
                    }
                    if(target_region.width < min_width || target_region.height < min_height) {
                        return;
                    }
                    me.ui.rect.set_absolute_region(info.target, target_region);
                    me.ui.property.notify(info.target, "draw", null);
                };
                var release_method = function (e) {
                    removeEventListener('mousemove', move_method);
                    removeEventListener('mouseup', release_method);
                    me.ui.property.notifyAll("ui.theme.remove", "transition");
                };
                addEventListener('mousemove', move_method);
                addEventListener('mouseup', release_method);
                e.preventDefault();
            });
        }
    };
    me.relative_region = function (object, parent=object.parentNode) {
        var parent_region = me.absolute_region(parent);
        var region = me.absolute_region(object);
        var xPos = region.left - parent_region.left;
        var yPos = region.top - parent_region.top;
        var width = region.width;
        var height = region.height;
        return {
            left: xPos,
            top: yPos,
            width: width,
            height: height,
            right: xPos + width,
            bottom: yPos + height
        };
    };
    me.absolute_region = function (object) {
        if(object === document.body) {
            return me.viewport();
        }
        var clientRect = object.getBoundingClientRect();
        var xPos = 0;
        var yPos = 0;
        var width = object.clientWidth;
        var height = object.clientHeight;
        if(!width) {
            width = clientRect.width;
        }
        if(!height) {
            height = clientRect.height;
        }
        var parent = object;
        while (parent) {
            if (parent === document.body) {
                // deal with browser quirks with body/window/document and page scroll
                var xScroll = parent.scrollLeft || document.documentElement.scrollLeft;
                var yScroll = parent.scrollTop || document.documentElement.scrollTop;

                xPos += (parent.offsetLeft - xScroll + parent.clientLeft);
                yPos += (parent.offsetTop - yScroll + parent.clientTop);
            } else {
                // for all other non-BODY elements
                xPos += (parent.offsetLeft - parent.scrollLeft + parent.clientLeft);
                yPos += (parent.offsetTop - parent.scrollTop + parent.clientTop);
            }

            parent = parent.offsetParent;
        }
        var absoluteRect = {
            left: xPos,
            top: yPos,
            width: width,
            height: height,
            right: xPos + width,
            bottom: yPos + height
        };
        return absoluteRect;
    };
    me.empty_region = function(region) {
        region.left = 0;
        region.top = 0;
        region.width = 0;
        region.height = 0;
    };
    me.set_relative_region = function(object, region, relative_to=null) {
        if(!object || !region) {
            return;
        }
        var parent_region = me.absolute_region(object.parentNode);
        if(relative_to) {
            var relative_to_region = me.absolute_region(relative_to);
            parent_region.left -= relative_to_region.left;
            parent_region.top -= relative_to_region.top;
        }
        object.style.left = region.left - parent_region.left + "px";
        object.style.top = region.top - parent_region.top + "px";
        object.style.width = region.width + "px";
        object.style.height = region.height + "px";
    };
    me.set_absolute_region = function(object, region) {
        if(object.parentNode === document.body) {
            object.style.left = region.left - object.clientLeft + "px";
            object.style.top = region.top - object.clientTop + "px";
        }
        else {
            var parent_region = me.absolute_region(object.parentNode);
            object.style.left = region.left - object.clientLeft - parent_region.left + "px";
            object.style.top = region.top - object.clientLeft - parent_region.top + "px";
        }
        object.style.width = region.width + "px";
        object.style.height = region.height + "px";
    };
    me.in_region = function (region, x, y) {
        return !(x < region.left || y < region.top || x > region.right || y > region.bottom);
    };
    me.in_view_bounds = function(region) {
        var view = me.viewport();
        return !(region.left < view.left || region.top < view.top || region.right > view.right || region.bottom > view.bottom);
    };
    me.viewport = function () {
        var e = window, a = 'inner';
        if (!('innerWidth' in window))
        {
            a = 'client';
            e = document.documentElement || document.body;
        }
        var width = e[ a + 'Width' ];
        var height = e[ a + 'Height' ];
        return {left:0,top:0,width:width,height:height,right:width,bottom:height};
    };
};
<commit_msg>resize bug fix<commit_after>/*
 @author Zakai Hamilton
 @component UIRect
 */

package.ui.rect = function UIRect(me) {
    me.movable = {
        get: function(object) {
            return object.rect_movable;
        },
        set: function(object, value) {
            object.rect_movable = value;
        }
    };
    me.resizable = {
        get: function(object) {
            return object.rect_resizable;
        },
        set: function(object, value) {
            object.rect_resizable = value;
        }
    };
    me.move = {
        set: function (object, value) {
            if(!value) {
                value = me.widget.window.window(object);
            }
            object.addEventListener('mousedown', function (e) {
                if(!value.rect_movable) {
                    e.preventDefault();
                    return;
                }
                me.set(value, "ui.focus.active", true);
                var target_region = me.ui.rect.absolute_region(value);
                var info = {
                    target: value,
                    left: e.clientX-target_region.left,
                    top: e.clientY-target_region.top,
                    width: value.offsetWidth,
                    height: value.offsetHeight
                };
                me.ui.property.notifyAll("ui.theme.add", "transition");
                var move_method = function (e) {
                    var target_region = me.ui.rect.absolute_region(value);
                    var shift_region = {};
                    me.ui.rect.empty_region(shift_region);
                    target_region.left = e.clientX - info.left;
                    target_region.top = e.clientY - info.top;
                    me.ui.rect.set_absolute_region(info.target, target_region);
                    me.ui.property.notify(info.target, "draw", null);
                };
                var release_method = function (e) {
                    removeEventListener('mousemove', move_method);
                    removeEventListener('mouseup', release_method);
                    me.ui.property.notifyAll("ui.theme.remove", "transition");
                };
                addEventListener('mousemove', move_method);
                addEventListener('mouseup', release_method);
                e.preventDefault();
            });
        }
    };
    me.resize = {
        set: function (object, value) {
            if(!value) {
                value = me.widget.window.window(object);
            }
            object.addEventListener('mousedown', function (e) {
                if(!value.rect_resizable) {
                    e.preventDefault();
                    return;
                }
                me.set(value, "ui.focus.active", true);
                var info = {
                    target: value,
                    left: e.clientX,
                    top: e.clientY,
                    width: value.offsetWidth,
                    height: value.offsetHeight
                };
                me.ui.property.notifyAll("ui.theme.add", "transition");
                var move_method = function (e) {
                    var target_region = me.ui.rect.absolute_region(value);
                    var object_region = me.ui.rect.absolute_region(object);
                    var shift_region = {};
                    me.ui.rect.empty_region(shift_region);
                    var min_width = parseInt(getComputedStyle(value).minWidth, 10);
                    var min_height = parseInt(getComputedStyle(value).minHeight, 10);
                    if(object_region.left < target_region.left + (target_region.width / 2)) {
                        target_region.width = target_region.width + (target_region.left - e.clientX);
                        if(target_region.width >= min_width) {
                            target_region.left = e.clientX;
                        }
                    }
                    else {
                        target_region.width = e.clientX - info.left + info.width;
                    }
                    if(object_region.top < target_region.top + (target_region.height / 2)) {
                        target_region.height = target_region.height + (target_region.top - e.clientY);
                        if(target_region.height >= min_height) {
                            target_region.top = e.clientY;
                        }
                    }
                    else {
                        target_region.height = e.clientY - info.top + info.height;
                    }
                    me.ui.rect.set_absolute_region(info.target, target_region);
                    me.ui.property.notify(info.target, "draw", null);
                };
                var release_method = function (e) {
                    removeEventListener('mousemove', move_method);
                    removeEventListener('mouseup', release_method);
                    me.ui.property.notifyAll("ui.theme.remove", "transition");
                };
                addEventListener('mousemove', move_method);
                addEventListener('mouseup', release_method);
                e.preventDefault();
            });
        }
    };
    me.relative_region = function (object, parent=object.parentNode) {
        var parent_region = me.absolute_region(parent);
        var region = me.absolute_region(object);
        var xPos = region.left - parent_region.left;
        var yPos = region.top - parent_region.top;
        var width = region.width;
        var height = region.height;
        return {
            left: xPos,
            top: yPos,
            width: width,
            height: height,
            right: xPos + width,
            bottom: yPos + height
        };
    };
    me.absolute_region = function (object) {
        if(object === document.body) {
            return me.viewport();
        }
        var clientRect = object.getBoundingClientRect();
        var xPos = 0;
        var yPos = 0;
        var width = object.clientWidth;
        var height = object.clientHeight;
        if(!width) {
            width = clientRect.width;
        }
        if(!height) {
            height = clientRect.height;
        }
        var parent = object;
        while (parent) {
            if (parent === document.body) {
                // deal with browser quirks with body/window/document and page scroll
                var xScroll = parent.scrollLeft || document.documentElement.scrollLeft;
                var yScroll = parent.scrollTop || document.documentElement.scrollTop;

                xPos += (parent.offsetLeft - xScroll + parent.clientLeft);
                yPos += (parent.offsetTop - yScroll + parent.clientTop);
            } else {
                // for all other non-BODY elements
                xPos += (parent.offsetLeft - parent.scrollLeft + parent.clientLeft);
                yPos += (parent.offsetTop - parent.scrollTop + parent.clientTop);
            }

            parent = parent.offsetParent;
        }
        var absoluteRect = {
            left: xPos,
            top: yPos,
            width: width,
            height: height,
            right: xPos + width,
            bottom: yPos + height
        };
        return absoluteRect;
    };
    me.empty_region = function(region) {
        region.left = 0;
        region.top = 0;
        region.width = 0;
        region.height = 0;
    };
    me.set_relative_region = function(object, region, relative_to=null) {
        if(!object || !region) {
            return;
        }
        var parent_region = me.absolute_region(object.parentNode);
        if(relative_to) {
            var relative_to_region = me.absolute_region(relative_to);
            parent_region.left -= relative_to_region.left;
            parent_region.top -= relative_to_region.top;
        }
        object.style.left = region.left - parent_region.left + "px";
        object.style.top = region.top - parent_region.top + "px";
        object.style.width = region.width + "px";
        object.style.height = region.height + "px";
    };
    me.set_absolute_region = function(object, region) {
        if(object.parentNode === document.body) {
            object.style.left = region.left - object.clientLeft + "px";
            object.style.top = region.top - object.clientTop + "px";
        }
        else {
            var parent_region = me.absolute_region(object.parentNode);
            object.style.left = region.left - object.clientLeft - parent_region.left + "px";
            object.style.top = region.top - object.clientLeft - parent_region.top + "px";
        }
        object.style.width = region.width + "px";
        object.style.height = region.height + "px";
    };
    me.in_region = function (region, x, y) {
        return !(x < region.left || y < region.top || x > region.right || y > region.bottom);
    };
    me.in_view_bounds = function(region) {
        var view = me.viewport();
        return !(region.left < view.left || region.top < view.top || region.right > view.right || region.bottom > view.bottom);
    };
    me.viewport = function () {
        var e = window, a = 'inner';
        if (!('innerWidth' in window))
        {
            a = 'client';
            e = document.documentElement || document.body;
        }
        var width = e[ a + 'Width' ];
        var height = e[ a + 'Height' ];
        return {left:0,top:0,width:width,height:height,right:width,bottom:height};
    };
};
<|endoftext|>


<commit_before>var Github = require('github-api')
var request = require('request')
var tape = require('tape')

var github = new Github({
  auth: "oauth",
  token: process.env['REPOROBOT_TOKEN']
})

var fork = github.getRepo('reporobot', 'patchwork')
var upstream = github.getRepo('jlord', 'patchwork')
var prnum

tape("Test wrong branch name", function(t) {

  createBranch()

  // create new branch on jlord/Patchwork fork
  function createBranch() {
    fork.branch('gh-pages', 'wrongname', function(err) {
      if (err) return t.error(err, "error creating branch on RRs fork")
      makePR()
    })
  }

  function makePR() {
    var pull = {
      title: "[TESTING] Wrong branch name",
      body: "Running a test on a PR with a wrong branch name",
      base: "gh-pages",
      head: "reporobot:" + "wrongbranch"
    }

    upstream.createPullRequest(pull, function(err, pr) {
      if (err) return t.error(err, "error creating PR")
      prnum = pr.number
      fetchPR()
    })
  }

  function fetchPR() {
    var baseURL = 'https://api.github.com/repos/jlord/patchwork/issues/'
    var prURL = baseURL + prnum + '/comments'

    request(prURL, function(err, res) {
      if (err) return t.error(err, "error fetching PR")
      if (res.length === 0) return t.fail("No comment created")
      setTimeout(getComment(res), 5000)
    })
  }

  function getComment(res) {
    var lastComment = res.pop()
    t.equal(lastComment.user.login, "reporobot")
    t.end()
  }
})

tape("Test cleanup", function(t) {
  function deleteViaBranch() {
    fork.deleteRef('heads/wrongbranch', function(err) {
      if (err && err.error != '422') return t.error(err, "error deleting branch")
      console.log("Branch deleted on RR fork. Cleaned up!")
      })
    }
})
<commit_msg>add cleanup close pr<commit_after>var Github = require('github-api')
var request = require('request')
var tape = require('tape')

var github = new Github({
  auth: "oauth",
  token: process.env['REPOROBOT_TOKEN']
})

var fork = github.getRepo('reporobot', 'patchwork')
var upstream = github.getRepo('jlord', 'patchwork')
var prnum

tape("Test wrong branch name", function(t) {

  createBranch()

  // create new branch on jlord/Patchwork fork
  function createBranch() {
    fork.branch('gh-pages', 'wrongname', function(err) {
      if (err) return t.error(err, "Error creating branch on RRs fork")
      createDiff()
    })
  }

  fucntion createDiff() {
    fork.write('wrongname', 'test.md', 'This is a test', '[TEST] Create diff', function(err) {
        if (err) return t.error(err, "Error creating new file to make diff")
        makePR()
      })
  }

  function makePR() {
    var pull = {
      title: "[TESTING] Wrong branch name",
      body: "Running a test on a PR with a wrong branch name",
      base: "gh-pages",
      head: "reporobot:" + "wrongbranch"
    }

    upstream.createPullRequest(pull, function(err, pr) {
      if (err) return t.error(err, "error creating PR")
      prnum = pr.number
      fetchPR()
    })
  }

  function fetchPR() {
    var baseURL = 'https://api.github.com/repos/jlord/patchwork/issues/'
    var prURL = baseURL + prnum + '/comments'

    request(prURL, function(err, res) {
      if (err) return t.error(err, "error fetching PR")
      if (res.length === 0) return t.fail("No comment created")
      setTimeout(getComment(res), 5000)
    })
  }

  function getComment(res) {
    var lastComment = res.pop()
    t.equal(lastComment.user.login, "reporobot")
    t.end()
  }
})

tape("Test cleanup", function(t) {
  function deleteViaBranch() {
    fork.deleteRef('heads/wrongbranch', function(err) {
      if (err && err.error != '422') return t.error(err, "Error deleting branch")
      console.log("Branch deleted on RR fork.")
      closePR()
      })
    }

    function closePR() {
      var options = {
        url: 'https://api.gihtub.com/repos/jlord/patchwork/pulls/' + prnum,
        json: true,
        body: {
          'state': 'closed'
        }
      }
      request.patch(options, function(err) {
        if (err) t.error(err, "Error closing PR")
        console.log("Deleted test PR")
        t.end()
      })
    }
})
<|endoftext|>


<commit_before>// ==UserScript==
// @name        GitHub News Filter
// @namespace   hckr
// @description Userscript to filter GitHub news feed using case-insensitive regular expression
// @include     https://github.com/
// @version     0.1
// @author      Jakub Młokosiewicz
// @source      https://github.com/hckr/github-news-filter
// @license     MIT
// ==/UserScript==

let news = document.querySelector('.news'),
    minimum = 10;

news.style.position = 'relative';
news.insertAdjacentHTML('afterbegin', `
    <label style="position: absolute; top: 5px; right: 20px; font-weight: normal">
        News filter: <input id="pattern-input" style="width: 150px; border: none; border-bottom: 1px solid #aaa">
    </label>
`);

let patternInput = document.getElementById('pattern-input'),
    underMinimum = 0,
    forcedMore = false,
    inputTimeout = null;

patternInput.addEventListener('input', function() {
    clearTimeout(inputTimeout);
    setTimeout(function() {
        let notHidden = filterNews(news.querySelectorAll('.alert'));
        if (notHidden < minimum) {
            underMinimum = minimum - notHidden;
            forcedMore = true;
            clickMoreIfExists();
        }
    }, 1000);
});

let observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.type === 'childList' && mutation.addedNodes) {
            if (!forcedMore) {
                underMinimum = minimum;
            }
            let notHidden = filterNews(
                [].filter.call(mutation.addedNodes,
                    node => node.className && node.className.match(/alert/)));
            underMinimum -= notHidden;
            if (notHidden == 0 || underMinimum > 0) {
                forcedMore = true;
                clickMoreIfExists();
            }
        }
    });
});
observer.observe(news, { childList: true });

function filterNews(newsItems) {
    let regexp = new RegExp(patternInput.value, 'i'),
        notHidden = 0;
    newsItems.forEach(el => {
        if (el.innerText.match(regexp)) {
            el.style.removeProperty('display');
            notHidden += 1;
        } else {
            el.style.display = 'none';
        }
    });

    return notHidden;
}

function clickMoreIfExists() {
    let moreButton = document.querySelector('.ajax-pagination-btn');
    if (moreButton) {
        moreButton.click();
    }
}
<commit_msg>Replacing input style with default GitHub form control<commit_after>// ==UserScript==
// @name        GitHub News Filter
// @namespace   hckr
// @description Userscript to filter GitHub news feed using case-insensitive regular expression
// @include     https://github.com/
// @version     0.1
// @author      Jakub Młokosiewicz
// @source      https://github.com/hckr/github-news-filter
// @license     MIT
// ==/UserScript==

let news = document.querySelector('.news'),
    minimum = 10;

news.style.position = 'relative';
news.insertAdjacentHTML('afterbegin', `
    <label class="sr-only" for="pattern-input">News filter</label>
    <input id="pattern-input" class="form-control" style="width: 150px; position: absolute; right: 20px;" placeholder="News filter">
`);

let patternInput = document.getElementById('pattern-input'),
    underMinimum = 0,
    forcedMore = false,
    inputTimeout = null;

patternInput.addEventListener('input', function() {
    clearTimeout(inputTimeout);
    setTimeout(function() {
        let notHidden = filterNews(news.querySelectorAll('.alert'));
        if (notHidden < minimum) {
            underMinimum = minimum - notHidden;
            forcedMore = true;
            clickMoreIfExists();
        }
    }, 1000);
});

let observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.type === 'childList' && mutation.addedNodes) {
            if (!forcedMore) {
                underMinimum = minimum;
            }
            let notHidden = filterNews(
                [].filter.call(mutation.addedNodes,
                    node => node.className && node.className.match(/alert/)));
            underMinimum -= notHidden;
            if (notHidden == 0 || underMinimum > 0) {
                forcedMore = true;
                clickMoreIfExists();
            }
        }
    });
});
observer.observe(news, { childList: true });

function filterNews(newsItems) {
    let regexp = new RegExp(patternInput.value, 'i'),
        notHidden = 0;
    newsItems.forEach(el => {
        if (el.innerText.match(regexp)) {
            el.style.removeProperty('display');
            notHidden += 1;
        } else {
            el.style.display = 'none';
        }
    });

    return notHidden;
}

function clickMoreIfExists() {
    let moreButton = document.querySelector('.ajax-pagination-btn');
    if (moreButton) {
        moreButton.click();
    }
}
<|endoftext|>


<commit_before>var http = require('http');
var libdtrace = require('libdtrace');
var io = require('socket.io');
var express = require('express');

/* create our express server and give access to the javascript files in ./public
*/
var app = express.createServer();
app.configure(function(){
	app.use(express.staticProvider(__dirname + '/public'));
    });
app.listen(80);

/* Before we go any further we must realize that each time a user connects we're going to want to
   them send then Dtrace data every second. We can do so using 'setInterval', but we must keep
   track of both the intervals we set and the Dtrace handles that are created inside of them as
   we'll need them later when the client disconnects.
*/
var interval_id_by_session_id = {};
var dtp_by_session_id = {};

/* In order to effecienctly send packets we're going to use the Socket.IO library which seemlessly
   integrates with express.
*/
var websocket_server = io.listen(app);

/* Now that we have a web socket server, we need to create a handler for connection events. These
   events represet a client connecting to our server */
socket.on('connection', function(socket) {

	/* Like the web server object, we must also define handlers for various socket events that
	   will happen during the lifetime of the connection. This will define how we interact with
           the client. The first is a message event which occurs when the client sends something to
	   the server. */

	socket.on( 'message', function(message) {
		/* The only message the client ever sends will be sent right after connecting.
                   So it will happen only once during the lifetime of a socket. This message also
		   contains a d script which defines an agregation to walk.
		   */
		var dtp = new libdtrace.Consumer();
		var dscript = message['dscript'];
		console.log( dscript );
		dtp.strcompile(dscript);
		dtp.go();
		dtp_by_session_id[client.sessionId] = dtp;

		/* All that's left to do is send the aggration data from the dscript.  */
		interval_id_by_session_id[client.sessionId] = setInterval(function () {
			var aggdata = {};
			try {
			    dtp.aggwalk(function (id, key, val) {
				    for( index in val ) {
					/* console.log( 'key: ' + key + ', interval: ' +
					   val[index][0][0] + '-' + val[index][0][1], ', count ' + val[index][1] );
					*/
					aggdata[key] = val;
			    }
				} );
			    client.send( aggdata );
			} catch( err ) {
			    console.log(err);
			}

		    },  1001 );
	    } );

	/* Not so fast. If a client disconnects we don't want we don't want dtrace to keep
	   collecting data any more. We also don't want to try to keep sending period. Clean up. */
	client.on('disconnect', function(){
		//stop sending the data
		clearInterval(clearInterval(interval_id_by_session_id[client.sessionId]));
		var dtp = dtp_by_session_id[client.sessionId];
		//should be only other reference to this should die once out of scope.
		delete dtp_by_session_id[client.sessionId];
		dtp.stop();

		console.log('disconnected');
	    });

    } );

<commit_msg>corrected grammar<commit_after>var http = require('http');
var libdtrace = require('libdtrace');
var io = require('socket.io');
var express = require('express');

/* create our express server and prepare to serve javascript files in ./public
*/
var app = express.createServer();
app.configure(function(){
	app.use(express.staticProvider(__dirname + '/public'));
    });
app.listen(80);

/* Before we go any further we must realize that each time a user connects we're going to want to
   them send them dtrace aggregation every second. We can do so using 'setInterval', but we must
   keep track of both the intervals we set and the dtrace consumers that are created as we'll need
   them later when the client disconnects.
*/
var interval_id_by_session_id = {};
var dtp_by_session_id = {};

/* In order to effecienctly send packets we're going to use the Socket.IO library which seemlessly
   integrates with express.
*/
var websocket_server = io.listen(app);

/* Now that we have a web socket server, we need to create a handler for connection events. These
   events represet a client connecting to our server */
socket.on('connection', function(socket) {

	/* Like the web server object, we must also define handlers for various socket events that
	   will happen during the lifetime of the connection. These will define how we interact with
           the client. The first is a message event which occurs when the client sends something to
	   the server. */
	socket.on( 'message', function(message) {
		/* The only message the client ever sends will be sent right after connecting.
                   So it will happen only once during the lifetime of a socket. This message also
		   contains a d script which defines an agregation to walk.
		   */
		var dtp = new libdtrace.Consumer();
		var dscript = message['dscript'];
		console.log( dscript );
		dtp.strcompile(dscript);
		dtp.go();
		dtp_by_session_id[client.sessionId] = dtp;

		/* All that's left to do is send the aggration data from the dscript.  */
		interval_id_by_session_id[client.sessionId] = setInterval(function () {
			var aggdata = {};
			try {
			    dtp.aggwalk(function (id, key, val) {
				    for( index in val ) {
					/* console.log( 'key: ' + key + ', interval: ' +
					   val[index][0][0] + '-' + val[index][0][1], ', count ' + val[index][1] );
					*/
					aggdata[key] = val;
			    }
				} );
			    client.send( aggdata );
			} catch( err ) {
			    console.log(err);
			}

		    },  1001 );
	    } );

	/* Not so fast. If a client disconnects we don't want their respective dtrace consumer to
	   keep collecting data any more. We also don't want to try to keep sending anything to them
	   period. So clean up. */
	client.on('disconnect', function(){
		clearInterval(clearInterval(interval_id_by_session_id[client.sessionId]));
		var dtp = dtp_by_session_id[client.sessionId];
		delete dtp_by_session_id[client.sessionId];
		dtp.stop();
		console.log('disconnected');
	    });

    } );

<|endoftext|>