<commit_before>var stats = new Stats();

var DIRECTION = Math.random() < 0.5 ? -1 : 1;

var TAU = Math.PI * 2;

var CLOUD_COUNT = 10;
// how much to wiggle the points around
var POINT_WIGGLE = 10;
// how much to wiggle the curves around
var WIGGLE = 10;

// the length of the segment in relation to the circle's radius
var SEGMENT_FACTOR = 3;

var context;
var width, height;

var clouds = [];

// A simple Linear Congruential Generator

// Establish the parameters of the generator
var m = 25;
// a - 1 should be divisible by m's prime factors
var a = 11;
// c and m should be co-prime
var c = 17;
// Setting the seed
var seed = 3;

var rand = function() {
  // define the recurrence relationship
  seed = (a * seed + c) % m;
  // return float in (0, 1)
  return seed / m;
};

var wiggle = function (size) {
  return Math.random() * size - size/2;
};

// compare by highest point on the screen
var sortClouds = function () {
  clouds.sort(function (c1, c2) {
    return (c1.bounds.top + c1.y) - (c2.bounds.top + c2.y);
  });
};

// set the cloud speeds based on vertical position
var updateCloudSpeeds = function () {
  for (var i = 0; i < CLOUD_COUNT; i++) {
    var cloud = clouds[i];
    cloud.velX = 5 + 10 * (cloud.bounds.top + cloud.y)/height;
  }
};

var setupClouds = function () {
  for (var i = 0; i < CLOUD_COUNT; i++) {
    clouds.push(createCloud());
  }
  sortClouds();
  updateCloudSpeeds();
};

var addCloud = function () {
  var cloud = createCloud();
  if (DIRECTION < 0) {
    cloud.x = width - cloud.bounds.left;
  } else {
    cloud.x = -cloud.bounds.right;
  }
  clouds.push(cloud);
  // resort
  sortClouds();
  updateCloudSpeeds();
};

var createCloudCircle = function (x, y) {
  return {
    x: x,
    y: y,
    radius: (height / 5) + wiggle(height/5),
    points: []
  };
};

var generateTriangle = function () {
  var h = (height / 4) + wiggle(30);
  var base = (2 * height / 5) + wiggle(130);
  var top   = {x: 0, y: -h};
  var left  = {x: -base/2 + wiggle(base/5), y: 0};
  var right = {x: base + left.x, y: 0};
  // start on the right to match our line drawing starting point
  return [
    {
      start: right,
      end: left,
      distance: right.x - left.x,
      circles: []
    },
    {
      start: left,
      end: top,
      distance: Math.sqrt(left.x*left.x + h*h),
      circles: []
    },
    {
      start: top,
      end: right,
      distance: Math.sqrt(right.x*right.x + h*h),
      circles: []
    }
  ];
};

var generateCircles = function (legs) {
  var circles = [];
  var startCircle = createCloudCircle(legs[0].start.x, legs[0].start.y);
  circles.push(startCircle);

  for (var i = 0; i < legs.length; i++) {
    var leg = legs[i];
    var endCircle;
    leg.circles.push(startCircle);
    if (i == legs.length-1) {
      endCircle = legs[0].circles[0];
    } else {
      endCircle = createCloudCircle(leg.end.x, leg.end.y);
      circles.push(endCircle);
    }
    leg.circles.push(endCircle);
    var total = startCircle.radius + endCircle.radius;
    startCircle = endCircle;
    // add more if needed
    while (total < leg.distance * 2) {
      var x = 0;
      var y = 0;
      for (var j = 0; j < leg.circles.length; j++) {
        var legCircle = leg.circles[j];
        x += legCircle.x;
        y += legCircle.y;
      }
      x = x / leg.circles.length;
      y = y / leg.circles.length;
      var circle = createCloudCircle(x, y);
      circles.push(circle);
      leg.circles.push(circle);
      total += circle.radius;
    }
  }

  // make the first circle have the rightmost point
  var rightMostPoint = circles[0].x + circles[0].radius;
  for (var i = 1; i < circles.length; i++) {
    var candidate = circles[i].x + circles[i].radius;
    if (candidate > rightMostPoint) {
      circles[0].x += candidate - rightMostPoint + 1;
      rightMostPoint = circles[0].x + circles[0].radius;
    }
  }

  return circles;
};

var traceCircles = function (circles) {
  var points = [];
  var start = 0;
  var currentCircle = circles[0];
  var segments = currentCircle.radius / SEGMENT_FACTOR;
  var increment = TAU / segments;
  var i = 0;
  // do until we're back on the first circle and run out of segments
  while (i < segments || currentCircle != circles[0]) {
    var x = Math.cos(i * increment) * currentCircle.radius + wiggle(POINT_WIGGLE);
    var y = Math.sin(i * increment) * currentCircle.radius + wiggle(POINT_WIGGLE);
    var outside = true;
    for (var j = 0; j < circles.length; j++) {
      var candidate = circles[j];
      if (candidate === currentCircle) {
        continue;
      }
      var translateX = currentCircle.x + x - candidate.x;
      var translateY = currentCircle.y + y - candidate.y;
      var dist = Math.sqrt(translateX * translateX + translateY * translateY);
      if (dist < candidate.radius) {
        currentCircle.points.push({ x: x, y: y, cusp: true });
        points.push({ x: x + currentCircle.x, y: y + currentCircle.y, cusp: true });
        currentCircle = candidate;
        segments = currentCircle.radius / SEGMENT_FACTOR;
        increment = TAU / segments;
        i = Math.round(segments * Math.atan2(translateY, translateX) / TAU);
        if (i < 0) {
          i = segments + i;
        }
        outside = false;
        break;
      }
    }
    if (outside) {
      currentCircle.points.push({ x: x, y: y });
      points.push({ x: x + currentCircle.x, y: y + currentCircle.y });
    }
    i++;
  }

  return points;
};

var createCloud = function () {
  var legs    = generateTriangle();
  var circles = generateCircles(legs);
  var points  = traceCircles(circles);

  var bounds = {
    top:    0,
    bottom: 0,
    left:   0,
    right:  0
  };

  // calculate bounding box
  for (var i = 0; i < points.length; i++) {
    bounds.top    = Math.min(bounds.top,    points[i].y);
    bounds.bottom = Math.max(bounds.bottom, points[i].y);
    bounds.left   = Math.min(bounds.left,   points[i].x);
    bounds.right  = Math.max(bounds.right,  points[i].x);
  }

  var x = Math.random() * width;
  var y = Math.random() * height;

  if (y + bounds.top < 0) {
    y = -bounds.top + 10;
  }

  if (y + bounds.bottom > height) {
    y = height - bounds.bottom - 10;
  }

  return {
    x:          x,
    y:          y,
    bounds:     bounds,
    circles:    circles,
    legs:       legs,
    points:     points,
    seed:       Math.round(Math.random() * 128)
  };
};

var cloudOutside = function (cloud) {
  var bounds = cloud.bounds;
  return (bounds.left   + cloud.x > width)  ||
         (bounds.right  + cloud.x < 0)      ||
         (bounds.bottom + cloud.y > height) ||
         (bounds.top    + cloud.y < 0);
};

var render = function () {
  stats.begin();
  context.clearRect(0, 0, width, height);

  context.fillStyle = 'white';
  var length = clouds.length;
  for (var i = 0; i < length; i++) {
    var cloud = clouds[i];
    context.save();
    context.translate(cloud.x, cloud.y);
    for (var j = 0; j < cloud.circles.length; j++) {
      var circle = cloud.circles[j];
      context.beginPath();
      context.arc(circle.x, circle.y, circle.radius, 0, TAU);
      context.fill();
    }
    seed = cloud.seed;
    context.beginPath();
    var lastPoint = cloud.points[0];
    context.moveTo(lastPoint.x, lastPoint.y);
    for (var j = 1; j < cloud.points.length; j++) {
      var point = cloud.points[j];
      if (point.cusp) {
        continue;
      }
      var midpointX = (point.x + lastPoint.x)/2;
      var midpointY = (point.y + lastPoint.y)/2;
      context.bezierCurveTo(
        midpointX + (rand() * WIGGLE - WIGGLE/2), midpointY + (rand() * WIGGLE - WIGGLE/2),
        midpointX + (rand() * WIGGLE - WIGGLE/2), midpointY + (rand() * WIGGLE - WIGGLE/2),
        point.x, point.y);
      lastPoint = point;
    }
    point = cloud.points[0];
    midpointX = (point.x + lastPoint.x)/2;
    midpointY = (point.y + lastPoint.y)/2;
    context.bezierCurveTo(
      midpointX + (rand() * WIGGLE - WIGGLE/2), midpointY + (rand() * WIGGLE - WIGGLE/2),
      midpointX + (rand() * WIGGLE - WIGGLE/2), midpointY + (rand() * WIGGLE - WIGGLE/2),
      point.x, point.y);
    context.stroke();
    context.restore();
  }

  stats.end();
};

var lastFrame, elapsed;
lastFrame = 0;

var tick = function (timestamp) {
  elapsed = timestamp - lastFrame;
  lastFrame = timestamp;
  step(elapsed);
  render();

  requestAnimationFrame(tick);
};

var step = function (delta) {
  for (var i = 0; i < clouds.length; i++) {
    var cloud = clouds[i];
    if (cloudOutside(cloud)) {
      clouds.splice(i, 1);
      i--;
      continue;
    }
    cloud.x += cloud.velX * delta / 1000;
  }
  if (clouds.length < CLOUD_COUNT) {
    addCloud();
  }
};

window.onload = function() {
  var canvas = document.getElementById('canvas');

  if (document.location.search === "?fps=1") {
    stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    document.body.appendChild(stats.dom);
  }

  context = canvas.getContext('2d');
  context.canvas.width  = window.innerWidth;
  context.canvas.height = window.innerHeight;
  width  = context.canvas.width;
  height = context.canvas.height;

  setupClouds();

  requestAnimationFrame(tick);
};
<commit_msg>make the position more uniform<commit_after>var stats = new Stats();

var DIRECTION = Math.random() < 0.5 ? -1 : 1;

var TAU = Math.PI * 2;

var CLOUD_COUNT = 10;
// how much to wiggle the points around
var POINT_WIGGLE = 10;
// how much to wiggle the curves around
var WIGGLE = 10;

// the length of the segment in relation to the circle's radius
var SEGMENT_FACTOR = 3;

var context;
var width, height;

var clouds = [];

// A simple Linear Congruential Generator

// Establish the parameters of the generator
var m = 25;
// a - 1 should be divisible by m's prime factors
var a = 11;
// c and m should be co-prime
var c = 17;
// Setting the seed
var seed = 3;

var rand = function() {
  // define the recurrence relationship
  seed = (a * seed + c) % m;
  // return float in (0, 1)
  return seed / m;
};

var wiggle = function (size) {
  return Math.random() * size - size/2;
};

// compare by highest point on the screen
var sortClouds = function () {
  clouds.sort(function (c1, c2) {
    return (c1.bounds.top + c1.y) - (c2.bounds.top + c2.y);
  });
};

// set the cloud speeds based on vertical position
var updateCloudSpeeds = function () {
  for (var i = 0; i < clouds.length; i++) {
    var cloud = clouds[i];
    cloud.velX = 5 + 16 * (cloud.bounds.top + cloud.y)/height;
  }
};

var setupClouds = function () {
  for (var i = 0; i < CLOUD_COUNT; i++) {
    clouds.push(createCloud());
  }
  sortClouds();
  updateCloudSpeeds();
};

var addCloud = function () {
  var cloud = createCloud();
  if (DIRECTION < 0) {
    cloud.x = width - cloud.bounds.left;
  } else {
    cloud.x = -cloud.bounds.right;
  }
  clouds.push(cloud);
  // resort
  sortClouds();
  updateCloudSpeeds();
};

var createCloudCircle = function (x, y) {
  return {
    x: x,
    y: y,
    radius: (height / 5) + wiggle(height/5),
    points: []
  };
};

var generateTriangle = function () {
  var h = (height / 4) + wiggle(30);
  var base = (2 * height / 5) + wiggle(130);
  var top   = {x: 0, y: -h};
  var left  = {x: -base/2 + wiggle(base/5), y: 0};
  var right = {x: base + left.x, y: 0};
  // start on the right to match our line drawing starting point
  return [
    {
      start: right,
      end: left,
      distance: right.x - left.x,
      circles: []
    },
    {
      start: left,
      end: top,
      distance: Math.sqrt(left.x*left.x + h*h),
      circles: []
    },
    {
      start: top,
      end: right,
      distance: Math.sqrt(right.x*right.x + h*h),
      circles: []
    }
  ];
};

var generateCircles = function (legs) {
  var circles = [];
  var startCircle = createCloudCircle(legs[0].start.x, legs[0].start.y);
  circles.push(startCircle);

  for (var i = 0; i < legs.length; i++) {
    var leg = legs[i];
    var endCircle;
    leg.circles.push(startCircle);
    if (i == legs.length-1) {
      endCircle = legs[0].circles[0];
    } else {
      endCircle = createCloudCircle(leg.end.x, leg.end.y);
      circles.push(endCircle);
    }
    leg.circles.push(endCircle);
    var total = startCircle.radius + endCircle.radius;
    startCircle = endCircle;
    // add more if needed
    while (total < leg.distance * 2) {
      var x = 0;
      var y = 0;
      for (var j = 0; j < leg.circles.length; j++) {
        var legCircle = leg.circles[j];
        x += legCircle.x;
        y += legCircle.y;
      }
      x = x / leg.circles.length;
      y = y / leg.circles.length;
      var circle = createCloudCircle(x, y);
      circles.push(circle);
      leg.circles.push(circle);
      total += circle.radius;
    }
  }

  // make the first circle have the rightmost point
  var rightMostPoint = circles[0].x + circles[0].radius;
  for (var i = 1; i < circles.length; i++) {
    var candidate = circles[i].x + circles[i].radius;
    if (candidate > rightMostPoint) {
      circles[0].x += candidate - rightMostPoint + 1;
      rightMostPoint = circles[0].x + circles[0].radius;
    }
  }

  return circles;
};

var traceCircles = function (circles) {
  var points = [];
  var start = 0;
  var currentCircle = circles[0];
  var segments = currentCircle.radius / SEGMENT_FACTOR;
  var increment = TAU / segments;
  var i = 0;
  // do until we're back on the first circle and run out of segments
  while (i < segments || currentCircle != circles[0]) {
    var x = Math.cos(i * increment) * currentCircle.radius + wiggle(POINT_WIGGLE);
    var y = Math.sin(i * increment) * currentCircle.radius + wiggle(POINT_WIGGLE);
    var outside = true;
    for (var j = 0; j < circles.length; j++) {
      var candidate = circles[j];
      if (candidate === currentCircle) {
        continue;
      }
      var translateX = currentCircle.x + x - candidate.x;
      var translateY = currentCircle.y + y - candidate.y;
      var dist = Math.sqrt(translateX * translateX + translateY * translateY);
      if (dist < candidate.radius) {
        currentCircle.points.push({ x: x, y: y, cusp: true });
        points.push({ x: x + currentCircle.x, y: y + currentCircle.y, cusp: true });
        currentCircle = candidate;
        segments = currentCircle.radius / SEGMENT_FACTOR;
        increment = TAU / segments;
        i = Math.round(segments * Math.atan2(translateY, translateX) / TAU);
        if (i < 0) {
          i = segments + i;
        }
        outside = false;
        break;
      }
    }
    if (outside) {
      currentCircle.points.push({ x: x, y: y });
      points.push({ x: x + currentCircle.x, y: y + currentCircle.y });
    }
    i++;
  }

  return points;
};

var createCloud = function () {
  var legs    = generateTriangle();
  var circles = generateCircles(legs);
  var points  = traceCircles(circles);

  var bounds = {
    top:    0,
    bottom: 0,
    left:   0,
    right:  0
  };

  // calculate bounding box
  for (var i = 0; i < points.length; i++) {
    bounds.top    = Math.min(bounds.top,    points[i].y);
    bounds.bottom = Math.max(bounds.bottom, points[i].y);
    bounds.left   = Math.min(bounds.left,   points[i].x);
    bounds.right  = Math.max(bounds.right,  points[i].x);
  }

  var x = Math.random() * width;
  var y = (Math.random() * (height - bounds.bottom - 10)) - bounds.top + 10;

  return {
    x:          x,
    y:          y,
    bounds:     bounds,
    circles:    circles,
    legs:       legs,
    points:     points,
    seed:       Math.round(Math.random() * 128)
  };
};

var cloudOutside = function (cloud) {
  var bounds = cloud.bounds;
  return (bounds.left   + cloud.x > width)  ||
         (bounds.right  + cloud.x < 0)      ||
         (bounds.top    + cloud.y > height) ||
         (bounds.bottom + cloud.y < 0);
};

var render = function () {
  stats.begin();
  context.clearRect(0, 0, width, height);

  var length = clouds.length;
  for (var i = 0; i < length; i++) {
    var cloud = clouds[i];
    context.save();
    context.translate(cloud.x, cloud.y);
    seed = cloud.seed;
    context.beginPath();
    var lastPoint = cloud.points[0];
    context.moveTo(lastPoint.x, lastPoint.y);
    for (var j = 1; j < cloud.points.length; j++) {
      var point = cloud.points[j];
      if (point.cusp) {
        continue;
      }
      var midpointX = (point.x + lastPoint.x)/2;
      var midpointY = (point.y + lastPoint.y)/2;
      context.bezierCurveTo(
        midpointX + (rand() * WIGGLE - WIGGLE/2), midpointY + (rand() * WIGGLE - WIGGLE/2),
        midpointX + (rand() * WIGGLE - WIGGLE/2), midpointY + (rand() * WIGGLE - WIGGLE/2),
        point.x, point.y);
      lastPoint = point;
    }
    point = cloud.points[0];
    midpointX = (point.x + lastPoint.x)/2;
    midpointY = (point.y + lastPoint.y)/2;
    context.bezierCurveTo(
      midpointX + (rand() * WIGGLE - WIGGLE/2), midpointY + (rand() * WIGGLE - WIGGLE/2),
      midpointX + (rand() * WIGGLE - WIGGLE/2), midpointY + (rand() * WIGGLE - WIGGLE/2),
      point.x, point.y);
    context.fill();
    context.stroke();
    context.restore();
  }

  stats.end();
};

var lastFrame, elapsed;
lastFrame = 0;

var tick = function (timestamp) {
  elapsed = timestamp - lastFrame;
  lastFrame = timestamp;
  step(elapsed);
  render();

  requestAnimationFrame(tick);
};

var step = function (delta) {
  for (var i = 0; i < clouds.length; i++) {
    var cloud = clouds[i];
    if (cloudOutside(cloud)) {
      clouds.splice(i, 1);
      i--;
      continue;
    }
    cloud.x += cloud.velX * delta / 1000;
  }
  if (clouds.length < CLOUD_COUNT) {
    addCloud();
  }
};

window.onload = function() {
  var canvas = document.getElementById('canvas');

  if (document.location.search === "?fps=1") {
    stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    document.body.appendChild(stats.dom);
  }

  context = canvas.getContext('2d');
  context.canvas.width  = window.innerWidth;
  context.canvas.height = window.innerHeight;
  width  = context.canvas.width;
  height = context.canvas.height;
  context.fillStyle = 'white';

  setupClouds();

  requestAnimationFrame(tick);
};
<|endoftext|>


<commit_before>module.exports = function(config) {
	return function(view) {
		return function setView(req, res, next) {
			res.view = view;
			next();
		};
	};
};
<commit_msg>Removed set-view mw.<commit_after><|endoftext|>


<commit_before>var
    expect = require('chai').expect,
    sinon = require('sinon'),
    lodown = require('../../index'),
    customers = require('./fixtures/customers.json');

describe('lodown', function() {
    describe('each', function() {
        it('should iterate an Array, applying action to each element, index of the element, and the collection', function() {
            var action = sinon.spy();
            lodown.each(customers, action);
            expect(action.callCount).to.equal(customers.length);
            customers.forEach(function(customer, index){
               expect(action.calledWith(customer, index, customers)).to.be.true;
            });
        });

        it('should iterate an Object, applying action for each value, key of value, and Object', function() {
            var action = sinon.spy();
            var customer = customers[0];
            lodown.each(customer, action);
            expect(action.callCount).to.equal(Object.keys(customer).length);
            for(var key in customer) {
              expect(action.calledWith(customer[key], key, customer)).to.be.true;
            }
        });
    });

    describe('filter', function() {
        it('filter should filter Array items based on test provided', function () {
            expect(lodown.filter([1, 2, 3], function(value) { return value > 2; } )).to.eql([3]);
        });
        it('filter should filter Object values based on test provided', function() {
            expect(lodown.filter({one: 'one', two: 'two', three: 'three'}, function(value) { return value[0] === 't' })).to.eql(['two', 'three']);
        });
    });

    describe('map', function() {
        it('map should create an Array of transformations for each value in an Array', function () {
            expect(lodown.map([1, 2, 3], function(value) { return value + 1; } )).to.eql([2, 3, 4]);
        });
        it('map should create an Array of transformations for each value in an Object', function() {
            expect(lodown.map({one: 'one', two: 'two', three: 'three'}, function(value) { return value.toUpperCase(); })).to.eql(['ONE', 'TWO', 'THREE']);
        });
    });

    describe("identity", function() {
        it('identity should return the value passed to it, including types Number, String, Boolean, Array, Object, Function', function(){
            expect(lodown.identity(1)).to.equal(1);
            expect(lodown.identity('identity')).to.equal('identity');
            expect(lodown.identity({a: "one"})).to.eql({a: "one"});
            expect(lodown.identity([1,2,3])).to.eql([1,2,3]);
            var fn = function() {  };
            expect(lodown.identity(fn)).to.eql(fn);
        });
    });
});<commit_msg>* add first, last<commit_after>var
    expect = require('chai').expect,
    sinon = require('sinon'),
    lodown = require('../../index'),
    customers = require('./fixtures/customers.json');

describe('lodown', function() {
    describe('each', function() {
        it('should iterate an Array, applying action to each element, index of the element, and the collection', function() {
            var action = sinon.spy();
            lodown.each(customers, action);
            expect(action.callCount).to.equal(customers.length);
            customers.forEach(function(customer, index){
               expect(action.calledWith(customer, index, customers)).to.be.true;
            });
        });

        it('should iterate an Object, applying action for each value, key of value, and Object', function() {
            var action = sinon.spy();
            var customer = customers[0];
            lodown.each(customer, action);
            expect(action.callCount).to.equal(Object.keys(customer).length);
            for(var key in customer) {
              expect(action.calledWith(customer[key], key, customer)).to.be.true;
            }
        });
    });

    describe('filter', function() {
        it('filter should filter Array items based on test provided', function () {
            expect(lodown.filter([1, 2, 3], function(value) { return value > 2; } )).to.eql([3]);
        });
        it('filter should filter Object values based on test provided', function() {
            expect(lodown.filter({one: 'one', two: 'two', three: 'three'}, function(value) { return value[0] === 't' })).to.eql(['two', 'three']);
        });
    });

    describe('map', function() {
        it('map should create an Array of transformations for each value in an Array', function () {
            expect(lodown.map([1, 2, 3], function(value) { return value + 1; } )).to.eql([2, 3, 4]);
        });
        it('map should create an Array of transformations for each value in an Object', function() {
            expect(lodown.map({one: 'one', two: 'two', three: 'three'}, function(value) { return value.toUpperCase(); })).to.eql(['ONE', 'TWO', 'THREE']);
        });
    });

    describe("identity", function() {
        it('identity should return the value passed to it, including types Number, String, Boolean, Array, Object, Function', function(){
            expect(lodown.identity(1)).to.equal(1);
            expect(lodown.identity('identity')).to.equal('identity');
            expect(lodown.identity({a: "one"})).to.eql({a: "one"});
            expect(lodown.identity([1,2,3])).to.eql([1,2,3]);
            var fn = function() {  };
            expect(lodown.identity(fn)).to.eql(fn);
        });
    });

    describe('typeOf', function() {
        it('should return a String representing the type of the value provided', function() {
            expect(lodown.typeOf([])).to.equal('array');
            expect(lodown.typeOf('a')).to.equal('string');
            expect(lodown.typeOf(null)).to.equal('null');
            expect(lodown.typeOf(new Date())).to.equal('date');
            expect(lodown.typeOf(function () { })).to.equal('function');
        });
    });

    describe('first', function() {
        it('should return the first value or n values in an Array', function() {
            expect(lodown.first(["a","b","c"])).to.equal("a");
            expect(lodown.first(["a","b","c"], 2)).to.eql(["a","b"]);
        });
        it('should return empty Array if first is invoked with negative n value', function() {
            expect(lodown.first(["a","b","c"], -1)).to.eql([]);
        });
        it('Should return the whole Array first is invoked with n value greater than the array\'s length.', function(){
            expect(lodown.first(["a","b","c"], 5)).to.eql(["a","b","c"]);
        });
        it('Should return empty Array if the array param is not an Array.', function() {
            expect(lodown.first({a:"b"}, 2)).to.eql([]);
        });
    });

    describe('last', function() {
        it('should return the last value or n values in an Array', function() {
            expect(lodown.last(["a","b","c"])).to.equal("c");
            expect(lodown.last(["a","b","c"], 2)).to.eql(["b","c"]);
        });
        it('should return empty Array if last is invoked with negative n value', function() {
            expect(lodown.last(["a","b","c"], -1)).to.eql([]);
        });
        it('Should return the whole Array last is invoked with n value greater than the array\'s length.', function() {
            expect(lodown.last(["a","b","c"], 5)).to.eql(["a","b","c"]);
        });
        it('Should return empty Array if the Array param is not an Array.', function() {
            expect(lodown.last({a:"b"}, 2)).to.eql([]);
        });
    });

});<|endoftext|>


<commit_before>// eventemitter.js version 0.1.0.
(function() {
  // An EventEmitter makes it easy to emit and subscribe to events.
  function EventEmitter() {
    this._listeners = {};
  }

  EventEmitter.makeSubclass = function(p) {
    var keys = Object.keys(EventEmitter.prototype);
    for (var i = 0, len = keys.length; i < len; ++i) {
      var key = keys[i];
      p[key] = EventEmitter.prototype[key];
    }
  };

  EventEmitter.prototype.listeners = function(name) {
    return (this._listeners[name] || []).slice();
  };

  EventEmitter.prototype.addListener = function(name, listener) {
    var listeners = this._listeners[name];
    if (!listeners) {
      this._listeners[name] = [listener];
    } else {
      listeners.push(listener);
    }
  };

  EventEmitter.prototype.removeListener = function(name, listener) {
    var listeners = this._listeners[name];
    if (!listeners) {
      return;
    }
    var idx = listeners.indexOf(listener);
    if (idx < 0) {
      return;
    }
    listeners.splice(idx, 1);
  };

  EventEmitter.prototype.on = EventEmitter.prototype.addListener;

  EventEmitter.prototype.once = function(name, listener) {
    var f;
    f = function() {
      listener();
      this.removeListener(name, f);
    }.bind(this);
    this.addListener(name, f);
  };

  EventEmitter.prototype.removeAllListeners = function(name) {
    if ('undefined' === typeof name) {
      this._listeners = {};
    } else {
      this._listeners[name] = [];
    }
  };

  EventEmitter.prototype.emit = function(name) {
    var listeners = this.listeners(name);
    var eventArgs = Array.prototype.slice.call(arguments, 1);
    for (var i = 0, len = listeners.length; i < len; ++i) {
      listeners[i].apply(null, eventArgs);
    }
  };

  window.EventEmitter = EventEmitter;

})();
<commit_msg>pass arguments to once() handlers<commit_after>// eventemitter.js version 0.1.1.
(function() {
  // An EventEmitter makes it easy to emit and subscribe to events.
  function EventEmitter() {
    this._listeners = {};
  }

  EventEmitter.makeSubclass = function(p) {
    var keys = Object.keys(EventEmitter.prototype);
    for (var i = 0, len = keys.length; i < len; ++i) {
      var key = keys[i];
      p[key] = EventEmitter.prototype[key];
    }
  };

  EventEmitter.prototype.listeners = function(name) {
    return (this._listeners[name] || []).slice();
  };

  EventEmitter.prototype.addListener = function(name, listener) {
    var listeners = this._listeners[name];
    if (!listeners) {
      this._listeners[name] = [listener];
    } else {
      listeners.push(listener);
    }
  };

  EventEmitter.prototype.removeListener = function(name, listener) {
    var listeners = this._listeners[name];
    if (!listeners) {
      return;
    }
    var idx = listeners.indexOf(listener);
    if (idx < 0) {
      return;
    }
    listeners.splice(idx, 1);
  };

  EventEmitter.prototype.on = EventEmitter.prototype.addListener;

  EventEmitter.prototype.once = function(name, listener) {
    var f;
    f = function() {
      listener.apply(this, arguments);
      this.removeListener(name, f);
    }.bind(this);
    this.addListener(name, f);
  };

  EventEmitter.prototype.removeAllListeners = function(name) {
    if ('undefined' === typeof name) {
      this._listeners = {};
    } else {
      this._listeners[name] = [];
    }
  };

  EventEmitter.prototype.emit = function(name) {
    var listeners = this.listeners(name);
    var eventArgs = Array.prototype.slice.call(arguments, 1);
    for (var i = 0, len = listeners.length; i < len; ++i) {
      listeners[i].apply(null, eventArgs);
    }
  };

  window.EventEmitter = EventEmitter;

})();
<|endoftext|>


<commit_before>/**
 * xkcd-today: Event Page
 */

'use strict';

/**
 * All stuff connected with the backgroung, e.g. looking for updates
 * @type {Object}
 */
var BG = {};
/**
 * An url to the api
 * @constant {string}
 */
BG.API_URL = 'http://xkcd.com/info.0.json';
/**
 * Name used to regonize the alarm
 * @constant {string}
 */
BG.ALARM_NAME = 'check-update';
/**
 * Chrome Alarm for updates stuff
 * @type {Alarm}
 */
BG.alarm = {
    when: Date.now(),
    periodInMinutes: 3 * 60 // 3h
};
/**
 * An id of the latest entry on xkcd.com
 * @type {string}
 */
BG.latestEntryId = 0;
// Load the latest entry's id from storage
chrome.storage.sync.get({
    latestEntryId: BG.latestEntryId
}, function (items) {
    BG.latestEntryId = items.latestEntryId;
});
/**
 * Method looking for updates
 */
BG.checkUpdates = function checkUpdates() {
    console.log("Checking for updates..");
    var self = this;

    $.get(this.API_URL, function (data) {
        var id = data['num'];

        // replace '' with the right link and save
        if (self.latestEntryId === 0) {
            chrome.storage.sync.set({
                latestEntryId: id
            });
            self.latestEntryId = id;
        }

        if (id !== BG.latestEntryId) {
            /* new posts */
            console.log('BG: New posts');

            self.latestEntryId = id;
            chrome.storage.sync.set({
                latestEntryId: id
            });
            // Send notification
            chrome.notifications.create('xkcd-updates', {
                type: "basic",
                iconUrl: "images/icon128.png",
                title: "New comics arrived",
                message: "Check it out now!"
            }, function () {
            });
            chrome.browserAction.setIcon({
                path: "images/icon-notify19.png"
            });
        }
    });
};
/**
 * A callback method for the updates Alarm
 */
BG.alarmCallback = function alarmCallback() {
    this.checkUpdates();
};

chrome.alarms.create(BG.ALARM_NAME, BG.alarm);
chrome.alarms.onAlarm.addListener(function (alarm) {
    if (alarm.name === BG.ALARM_NAME) {
        BG.alarmCallback();
    }
});<commit_msg>updates: Check on startup<commit_after>/**
 * xkcd-today: Event Page
 */

'use strict';

/**
 * All stuff connected with the backgroung, e.g. looking for updates
 * @type {Object}
 */
var BG = {};
/**
 * An url to the api
 * @constant {string}
 */
BG.API_URL = 'http://xkcd.com/info.0.json';
/**
 * Name used to regonize the alarm
 * @constant {string}
 */
BG.ALARM_NAME = 'check-update';
/**
 * Chrome Alarm for updates stuff
 * @type {Alarm}
 */
BG.alarm = {
    when: Date.now(),
    periodInMinutes: 3 * 60 // 3h
};
/**
 * An id of the latest entry on xkcd.com
 * @type {string}
 */
BG.latestEntryId = 0;
// Load the latest entry's id from storage
chrome.storage.sync.get({
    latestEntryId: BG.latestEntryId
}, function (items) {
    BG.latestEntryId = items.latestEntryId;
});
/**
 * Method looking for updates
 */
BG.checkUpdates = function checkUpdates() {
    console.log("Checking for updates..");
    var self = this;

    $.get(this.API_URL, function (data) {
        var id = data['num'];

        // replace '' with the right link and save
        if (self.latestEntryId === 0) {
            chrome.storage.sync.set({
                latestEntryId: id
            });
            self.latestEntryId = id;
        }

        if (id !== BG.latestEntryId) {
            /* new posts */
            console.log('BG: New posts');

            self.latestEntryId = id;
            chrome.storage.sync.set({
                latestEntryId: id
            });
            // Send notification
            chrome.notifications.create('xkcd-updates', {
                type: "basic",
                iconUrl: "images/icon128.png",
                title: "New comics arrived",
                message: "Check it out now!"
            }, function () {
            });
            chrome.browserAction.setIcon({
                path: "images/icon-notify19.png"
            });
        }
    });
};
/**
 * A callback method for the updates Alarm
 */
BG.alarmCallback = function alarmCallback() {
    this.checkUpdates();
};

// Always check on startup
chrome.runtime.onStartup.addListener(function () {
    BG.alarmCallback();
});
chrome.alarms.create(BG.ALARM_NAME, BG.alarm);
chrome.alarms.onAlarm.addListener(function (alarm) {
    if (alarm.name === BG.ALARM_NAME) {
        BG.alarmCallback();
    }
});
<|endoftext|>


<commit_before>var $ = require('jquery');
var React = require('react/addons');
var RetinaImage = require('react-retina-image');
var ContainerStore = require('./ContainerStore');
var metrics = require('./Metrics');
var OverlayTrigger = require('react-bootstrap').OverlayTrigger;
var Tooltip = require('react-bootstrap').Tooltip;
var util = require('./Util');

var ImageCard = React.createClass({
  getInitialState: function () {
    return {
      tags: [],
      chosenTag: 'latest'
    };
  },
  handleTagClick: function (tag) {
    this.setState({
      chosenTag: tag
    });
    var $tagOverlay = $(this.getDOMNode()).find('.tag-overlay');
    $tagOverlay.fadeOut(300);
    metrics.track('Selected Image Tag');
  },
  handleClick: function (name) {
    metrics.track('Created Container');
    ContainerStore.create(name, this.state.chosenTag, function () {
      $(document.body).find('.new-container-item').parent().fadeOut();
    }.bind(this));
  },
  handleTagOverlayClick: function (name) {
    var $tagOverlay = $(this.getDOMNode()).find('.tag-overlay');
    $tagOverlay.fadeIn(300);
    $.get('https://registry.hub.docker.com/v1/repositories/' + name + '/tags', function (result) {
      this.setState({
        tags: result
      });
    }.bind(this));
  },
  handleCloseTagOverlay: function () {
    var $tagOverlay = $(this.getDOMNode()).find('.tag-overlay');
    $tagOverlay.fadeOut(300);
  },
  handleRepoClick: function () {
    var $repoUri = 'https://registry.hub.docker.com/';
    if (this.props.image.is_official) {
      $repoUri = $repoUri + "_/";
    } else {
      $repoUri = $repoUri + "u/";
    }
    util.exec(['open', $repoUri + this.props.image.name]);
  },
  render: function () {
    var self = this;
    var name;
    var imageNameTokens = this.props.image.name.split('/');
    var namespace;
    var repo;
    if (imageNameTokens.length > 1) {
      namespace = imageNameTokens[0];
      repo = imageNameTokens[1];
    } else {
      namespace = "official";
      repo = imageNameTokens[0];
    }
    if (this.props.image.is_official) {
      name = (

{namespace}

          <OverlayTrigger placement="bottom" overlay={<Tooltip>View on DockerHub</Tooltip>}>
            {repo}
          </OverlayTrigger>

      );
    } else {
      name = (

{namespace}

          <OverlayTrigger placement="bottom" overlay={<Tooltip>{this.props.image.name}</Tooltip>}>
            {repo}
          </OverlayTrigger>

      );
    }
    var description;
    if (this.props.image.description) {
      description = this.props.image.description;
    } else {
      description = "No description.";
    }
    var logoStyle = {
      backgroundImage: `linear-gradient(-180deg, ${this.props.image.gradient_start} 4%, ${this.props.image.gradient_end}  100%)`
    };
    var imgsrc;
    if (this.props.image.img) {
      imgsrc = `http://kitematic.com/recommended/${this.props.image.img}`;
    } else {
      imgsrc = 'http://kitematic.com/recommended/kitematic_html.png';
    }
    var tags;
    if (self.state.tags.length > 0) {
      var tagDisplay = self.state.tags.map(function (t) {
        if (t.name === self.state.chosenTag) {
          return
{t.name}
;
        } else {
          return
{t.name}
;
        }
      });
      tags = (

          {tagDisplay}

      );
    } else {
      tags = <RetinaImage className="tags-loading" src="loading-white.png"/>;
    }
    var officialBadge;
    if (this.props.image.is_official) {
      officialBadge = (
        <RetinaImage src="official.png" />
      );
    }
    return (

          {tags}

          <RetinaImage src={imgsrc}/>

            {officialBadge}

            {name}

            {description}

            <OverlayTrigger placement="bottom" overlay={<Tooltip>Favorites</Tooltip>}>

                {this.props.image.star_count}

            </OverlayTrigger>

              <OverlayTrigger placement="bottom" overlay={<Tooltip>Change Tag</Tooltip>}>
                {this.state.chosenTag}
              </OverlayTrigger>

              Create

    );
  }
});

module.exports = ImageCard;
<commit_msg>Missed updating one tool tip.<commit_after>var $ = require('jquery');
var React = require('react/addons');
var RetinaImage = require('react-retina-image');
var ContainerStore = require('./ContainerStore');
var metrics = require('./Metrics');
var OverlayTrigger = require('react-bootstrap').OverlayTrigger;
var Tooltip = require('react-bootstrap').Tooltip;
var util = require('./Util');

var ImageCard = React.createClass({
  getInitialState: function () {
    return {
      tags: [],
      chosenTag: 'latest'
    };
  },
  handleTagClick: function (tag) {
    this.setState({
      chosenTag: tag
    });
    var $tagOverlay = $(this.getDOMNode()).find('.tag-overlay');
    $tagOverlay.fadeOut(300);
    metrics.track('Selected Image Tag');
  },
  handleClick: function (name) {
    metrics.track('Created Container');
    ContainerStore.create(name, this.state.chosenTag, function () {
      $(document.body).find('.new-container-item').parent().fadeOut();
    }.bind(this));
  },
  handleTagOverlayClick: function (name) {
    var $tagOverlay = $(this.getDOMNode()).find('.tag-overlay');
    $tagOverlay.fadeIn(300);
    $.get('https://registry.hub.docker.com/v1/repositories/' + name + '/tags', function (result) {
      this.setState({
        tags: result
      });
    }.bind(this));
  },
  handleCloseTagOverlay: function () {
    var $tagOverlay = $(this.getDOMNode()).find('.tag-overlay');
    $tagOverlay.fadeOut(300);
  },
  handleRepoClick: function () {
    var $repoUri = 'https://registry.hub.docker.com/';
    if (this.props.image.is_official) {
      $repoUri = $repoUri + "_/";
    } else {
      $repoUri = $repoUri + "u/";
    }
    util.exec(['open', $repoUri + this.props.image.name]);
  },
  render: function () {
    var self = this;
    var name;
    var imageNameTokens = this.props.image.name.split('/');
    var namespace;
    var repo;
    if (imageNameTokens.length > 1) {
      namespace = imageNameTokens[0];
      repo = imageNameTokens[1];
    } else {
      namespace = "official";
      repo = imageNameTokens[0];
    }
    if (this.props.image.is_official) {
      name = (

{namespace}

          <OverlayTrigger placement="bottom" overlay={<Tooltip>View on DockerHub</Tooltip>}>
            {repo}
          </OverlayTrigger>

      );
    } else {
      name = (

{namespace}

          <OverlayTrigger placement="bottom" overlay={<Tooltip>View on DockerHub</Tooltip>}>
            {repo}
          </OverlayTrigger>

      );
    }
    var description;
    if (this.props.image.description) {
      description = this.props.image.description;
    } else {
      description = "No description.";
    }
    var logoStyle = {
      backgroundImage: `linear-gradient(-180deg, ${this.props.image.gradient_start} 4%, ${this.props.image.gradient_end}  100%)`
    };
    var imgsrc;
    if (this.props.image.img) {
      imgsrc = `http://kitematic.com/recommended/${this.props.image.img}`;
    } else {
      imgsrc = 'http://kitematic.com/recommended/kitematic_html.png';
    }
    var tags;
    if (self.state.tags.length > 0) {
      var tagDisplay = self.state.tags.map(function (t) {
        if (t.name === self.state.chosenTag) {
          return
{t.name}
;
        } else {
          return
{t.name}
;
        }
      });
      tags = (

          {tagDisplay}

      );
    } else {
      tags = <RetinaImage className="tags-loading" src="loading-white.png"/>;
    }
    var officialBadge;
    if (this.props.image.is_official) {
      officialBadge = (
        <RetinaImage src="official.png" />
      );
    }
    return (

          {tags}

          <RetinaImage src={imgsrc}/>

            {officialBadge}

            {name}

            {description}

            <OverlayTrigger placement="bottom" overlay={<Tooltip>Favorites</Tooltip>}>

                {this.props.image.star_count}

            </OverlayTrigger>

              <OverlayTrigger placement="bottom" overlay={<Tooltip>Change Tag</Tooltip>}>
                {this.state.chosenTag}
              </OverlayTrigger>

              Create

    );
  }
});

module.exports = ImageCard;
<|endoftext|>


<commit_before>define(['app',
'text!views/directives/home-articles-small.html', 'services/articles-service'],
    function(app, template, _) {
        app.directive('homeArticlesSmall', function($http) {
            return {
                restrict: 'EAC',
                replace: true,
                template: template,
                scope   : {
                    tags: '@?'
                },
                controller: ['$scope', '$http','$q', '$filter', '$location', 'articlesService',
                    function($scope, $http, $q, $filter, $location, articlesService) {

                        $scope.status   = "loading";
                        $scope.error    = null;

                        $scope.articles = [];

                        loadArticles();
                        //---------------------------------------------------------------------
                        function loadArticles(){
                            var ag = [];
                            var agLimit = [];
                            ag.push({"$match":{"$and":[{"adminTags.title.en":encodeURIComponent($scope.tags||"ABSCH-Announcement")}]}});
                            ag.push({"$project" : {"title":1, "content":1, "coverImage":1, "meta":1, "summary":1}});
                            ag.push({"$sort" : {"meta.modifiedOn":-1}});

                            agLimit = JSON.parse(JSON.stringify(ag))
                            agLimit.push({"$limit" : 6});

                            var qs = {
                              "ag" : JSON.stringify(agLimit)
                            };
                            articlesService.getArticles(qs).then(function(data){
                                $scope.articles = data;
                            })

                            ag.push({"$count" : "mycount"});
                            var qsCount = {
                                "ag" : JSON.stringify(ag)
                             };

                            articlesService.getArticles(qsCount).then(function(data){
                                $scope.articlesCount = (data[0]||{}).mycount||0;
                              })

                          }
                        //---------------------------------------------------------------------
                         $scope.getSizedImage = function(url, size){
                            // return url;

                            return url && url
                            .replace(/attachments.cbd.int\//, '$&'+size+'/')
                            .replace(/\.s3-website-us-east-1\.amazonaws\.com\//, '$&'+size+'/')
                        }
                        //---------------------------------------------------------------------
                        $scope.loadArticle = function(id){
                            $location.path('/articles/' + id );
                        }

                    }
                ]
            };

        });
    });
<commit_msg>remove unused field<commit_after>define(['app',
'text!views/directives/home-articles-small.html', 'services/articles-service'],
    function(app, template, _) {
        app.directive('homeArticlesSmall', function($http) {
            return {
                restrict: 'EAC',
                replace: true,
                template: template,
                scope   : {
                    tags: '@?'
                },
                controller: ['$scope', '$http','$q', '$filter', '$location', 'articlesService',
                    function($scope, $http, $q, $filter, $location, articlesService) {

                        $scope.status   = "loading";
                        $scope.error    = null;

                        $scope.articles = [];

                        loadArticles();
                        //---------------------------------------------------------------------
                        function loadArticles(){
                            var ag = [];
                            var agLimit = [];
                            ag.push({"$match":{"$and":[{"adminTags.title.en":encodeURIComponent($scope.tags||"ABSCH-Announcement")}]}});
                            ag.push({"$project" : {"title":1, "coverImage":1, "meta":1, "summary":1}});
                            ag.push({"$sort" : {"meta.modifiedOn":-1}});

                            agLimit = JSON.parse(JSON.stringify(ag))
                            agLimit.push({"$limit" : 6});

                            var qs = {
                              "ag" : JSON.stringify(agLimit)
                            };
                            articlesService.getArticles(qs).then(function(data){
                                $scope.articles = data;
                            })

                            ag.push({"$count" : "mycount"});
                            var qsCount = {
                                "ag" : JSON.stringify(ag)
                             };

                            articlesService.getArticles(qsCount).then(function(data){
                                $scope.articlesCount = (data[0]||{}).mycount||0;
                              })

                          }
                        //---------------------------------------------------------------------
                         $scope.getSizedImage = function(url, size){
                            // return url;

                            return url && url
                            .replace(/attachments.cbd.int\//, '$&'+size+'/')
                            .replace(/\.s3-website-us-east-1\.amazonaws\.com\//, '$&'+size+'/')
                        }
                        //---------------------------------------------------------------------
                        $scope.loadArticle = function(id){
                            $location.path('/articles/' + id );
                        }

                    }
                ]
            };

        });
    });
<|endoftext|>


<commit_before>var page = require("webpage").create();
var system = require("system");

page.paperSize = {
    width: '6in',
    height: '4in',
    margin: {
        top: '10px',
        left: '15px',
        right: '15px',
        bottom: '10px'
    }
}

page.zoomFactor = 0.5;

page.viewportSize = {
  width: 850,
  height: 680
};

page.open(system.args[1], function (status) {
    window.setTimeout(function () {
        var size = page.evaluate(function () {
            return {width: width = 850, height : 680 };
        });
        page.paperSize = size;

        page.render(system.args[2]);
        phantom.exit();
    }, 3000);
});

page.onError = function(msg, trace) {
    console.log(msg);
}<commit_msg>adjustment of sizes<commit_after>var page = require("webpage").create();
var system = require("system");

page.paperSize = {
    width: '6in',
    height: '4in',
    margin: {
        top: '10px',
        left: '15px',
        right: '15px',
        bottom: '10px'
    }
}

page.zoomFactor = 0.5;

page.viewportSize = {
  width: 800,
  height: 580
};

page.open(system.args[1], function (status) {
    window.setTimeout(function () {
        var size = page.evaluate(function () {
            return {width: width = 800, height : 580 };
        });
        page.paperSize = size;

        page.render(system.args[2]);
        phantom.exit();
    }, 3000);
});

page.onError = function(msg, trace) {
    console.log(msg);
}<|endoftext|>


<commit_before>let assert = require('assert')

describe("Dashboard", () => {
  it("logs in", function(){
    browser.url('http://localhost:8080/')
    browser.setViewportSize({
        width: 1000,
        height: 700
    });

    $("input[name=email]").waitForExist()
    $('input[name=email]').setValue("test@serverboards.io")
    $('input[name=password]').setValue("asdfasdf")
    $('button.login').click()

    browser.waitUntil(() => $('body').getText().includes("This is how Serverboards works."))
  })

  it("Creates a project", function(){
    $('#add_project').waitForExist()
    $('#add_project').click()
    $('input[name=name]').waitForExist()

    browser.saveScreenshot("./shots/010-add-project.png")

    $('input[name=name]').setValue("TEST-01")
    $('textarea[name=description]').setValue("This is the TEST nr 01")
    $('button[type=submit]').click()
    browser.waitUntil(() => $('body').getText().includes("Start adding Widgets into your project's Dashboard"))
    $$('.message .close.icon').map( f => f.click() ) // Close messages

    browser.saveScreenshot("./shots/011-add-project-ok.png")

    $('#project_selector').click()
    $('=TEST-01').waitForExist()

    browser.saveScreenshot("./shots/017-dashboard-list-1.png")

  })

  it("Adds a widget", function(){
    $('.ui.floating.bottom.right.add a').click()
    $('.ui.mid.massive.button.add.area.chart.yellow.icon').waitForExist()
    $('.ui.mid.massive.button.add.area.chart.yellow.icon').click()

    browser.saveScreenshot("./shots/012-add-widget.png")
    $('div.selection.ui.dropdown').click()
    $('div[data-value="serverboards.core.widgets/markdown"]').waitForExist()
    $('div[data-value="serverboards.core.widgets/markdown"]').click()

    $('textarea[name=text]').waitForExist()
    $('textarea[name=text]').setValue("# This is a widget test")
    $('.ui.modal button.ui.button.yellow').click()

    $('.board .card h1').waitForExist()
    browser.saveScreenshot("./shots/013-markdown-widget.png")
  })

  it("Adds another board", function(){
    $('a#add_dashboard').click()
    $('.ui.modal .ui.field input[type=text]').waitForExist()
    browser.saveScreenshot("./shots/014-add-dashboard.png")
    $('.ui.modal .ui.field input[type=text]').setValue("test")
    $('.ui.modal button').click()

    $('.ui.attached.tabular.menu').$('=test').waitForExist()
    $('.ui.attached.tabular.menu').$('=test').click()
    // now has not
    $('.board .card h1').waitForExist(500, true) // not exists. May fail if previous test failed.

    $('.ui.attached.tabular.menu').$('=Monitoring').click()
    // now has it
    $('.board .card h1').waitForExist(500)
    browser.saveScreenshot("./shots/015-at-new-dashboard.png")
  })

  it("Another project, change of widgets", function(){
    $('#side_menu_toggle').click()

    $('#add_project').waitForExist()
    $('#add_project').click()
    $('input[name=name]').waitForExist()
    $('input[name=name]').setValue("TEST-02")
    $('textarea[name=description]').setValue("This is the TEST nr 02")
    $('button[type=submit]').click()
    $$('.message .close.icon').map( f => f.click() ) // Close messages

    $('#project_selector').click()
    $('=TEST-01').waitForExist()

    browser.saveScreenshot("./shots/016-dashboard-list.png")

    $('=TEST-01').click()
    $('.board .card h1').waitForExist()

    $('#project_selector').click()
    $('=TEST-02').waitForExist()
    $('=TEST-02').click()
    $('.board .card h1').waitForExist(500, true) // not exists
  })
})
<commit_msg>Improved resilency on dashboard UI test<commit_after>let assert = require('assert')

describe("Dashboard", () => {
  it("logs in", function(){
    browser.url('http://localhost:8080/')
    browser.setViewportSize({
        width: 1000,
        height: 700
    });

    $("input[name=email]").waitForExist()
    $('input[name=email]').setValue("test@serverboards.io")
    $('input[name=password]').setValue("asdfasdf")
    $('button.login').click()

    browser.waitUntil(() => $('body').getText().includes("This is how Serverboards works."))
  })

  it("Creates a project", function(){
    $('#add_project').waitForExist()
    $('#add_project').click()
    $('input[name=name]').waitForExist()

    browser.saveScreenshot("./shots/010-add-project.png")

    $('input[name=name]').setValue("TEST-01")
    $('textarea[name=description]').setValue("This is the TEST nr 01")
    $('button[type=submit]').click()
    browser.waitUntil(() => $('body').getText().includes("Start adding Widgets into your project's Dashboard"))
    $$('.message .close.icon').map( f => f.click() ) // Close messages

    browser.saveScreenshot("./shots/011-add-project-ok.png")

    $('#project_selector').waitForExist()
    $('#project_selector').click()
    $('=TEST-01').waitForExist()

    browser.saveScreenshot("./shots/017-dashboard-list-1.png")

  })

  it("Adds a widget", function(){
    $('.ui.floating.bottom.right.add a').click()
    $('.ui.mid.massive.button.add.area.chart.yellow.icon').waitForExist()
    $('.ui.mid.massive.button.add.area.chart.yellow.icon').click()

    browser.saveScreenshot("./shots/012-add-widget.png")
    $('div.selection.ui.dropdown').click()
    $('div[data-value="serverboards.core.widgets/markdown"]').waitForExist()
    $('div[data-value="serverboards.core.widgets/markdown"]').click()

    $('textarea[name=text]').waitForExist()
    $('textarea[name=text]').setValue("# This is a widget test")
    $('.ui.modal button.ui.button.yellow').click()

    $('.board .card h1').waitForExist()
    browser.saveScreenshot("./shots/013-markdown-widget.png")
  })

  it("Adds another board", function(){
    $('a#add_dashboard').click()
    $('.ui.modal .ui.field input[type=text]').waitForExist()
    browser.saveScreenshot("./shots/014-add-dashboard.png")
    $('.ui.modal .ui.field input[type=text]').setValue("test")
    $('.ui.modal button').click()

    $('.ui.attached.tabular.menu').$('=test').waitForExist()
    $('.ui.attached.tabular.menu').$('=test').click()
    // now has not
    $('.board .card h1').waitForExist(500, true) // not exists. May fail if previous test failed.

    $('.ui.attached.tabular.menu').$('=Monitoring').click()
    // now has it
    $('.board .card h1').waitForExist(500)
    browser.saveScreenshot("./shots/015-at-new-dashboard.png")
  })

  it("Another project, change of widgets", function(){
    $('#side_menu_toggle').click()

    $('#add_project').waitForExist()
    $('#add_project').click()
    $('input[name=name]').waitForExist()
    $('input[name=name]').setValue("TEST-02")
    $('textarea[name=description]').setValue("This is the TEST nr 02")
    $('button[type=submit]').click()
    $$('.message .close.icon').map( f => f.click() ) // Close messages

    $('#project_selector').waitForExist()
    $('#project_selector').click()
    $('=TEST-01').waitForExist()

    browser.saveScreenshot("./shots/016-dashboard-list.png")

    $('=TEST-01').click()
    $('.board .card h1').waitForExist()

    $('#project_selector').waitForExist()
    $('#project_selector').click()
    $('=TEST-02').waitForExist()
    $('=TEST-02').click()
    $('.board .card h1').waitForExist(500, true) // not exists
  })
})
<|endoftext|>


<commit_before>define(['app', '/app/views/forms/edit/edit.js'], function (app) {

  app.controller("editAbsPermit", ["$scope", "authHttp", "Thesaurus", "guid", "$filter", "$q", "Enumerable", "editFormUtility", "$controller", function ($scope, $http, Thesaurus, guid, $filter, $q, Enumerable, editFormUtility, $controller) {
    $controller('editController', {$scope: $scope});

    _.extend($scope.options, {
      usage		: function () {
        return $http.get("/api/v2013/thesaurus/domains/A7B77788-8C90-4849-9327-E181E9522F3A/terms",	{ cache: true }).then(function (o) {
          return o.data;
        });
      },
      keywords  : function () {
        return $q.all([
          $http.get("/api/v2013/thesaurus/domains/1A22EAAB-9BBC-4543-890E-DEF913F59E98/terms", { cache: true }),
          $http.get("/api/v2013/thesaurus/terms/5B6177DD-5E5E-434E-8CB7-D63D67D5EBED",   { cache: true })
        ]).then(function (o) {
          var data = o[0].data;
          data.push(o[1].data)
          return Thesaurus.buildTree(data);
        });
      },
    });

    //==================================
    //
    //==================================
    $scope.$watch("document.gisFiles", function () {

      var qLinks = [];
      var qGis = [];

      if ($scope.document)
        qLinks = $scope.document.gisFiles || [];

      /* global L: true */ // JSHint for leaflet

      angular.forEach(qLinks, function (link) {
        qGis.push($http.get(link.url).then(function (res) {
          return L.geoJson(res.data);
        }));
      });

      $q.all(qGis).then(function (layers) {
        $scope.gisLayer = layers;
      });
    });

    //==================================
    //
    //==================================
    $scope.$on("loadDocument", function(evt, info) {

      if(info.schema!="absPermit")
        return;

      if(info.identifier)//$scope.status=="loading"
          $q.when(editFormUtility.documentExists(info.identifier),function(exists){
              $scope.documentExists = exists;
              //amendment intent shoudl be entered by users for every edit/ clear it on load if any from previous update
              if($scope.document.amendmentIntent != undefined){
                $scope.document.amendmentIntent = undefined;
}
              if($scope.document.amendmentsDescription)
                $scope.document.amendmentsDescription = undefined;

          });
    });

    //==================================
    //
    //==================================
    $scope.getCleanDocument = function(document) {

      document = document || $scope.document;

      if (!document)
        return undefined;

      document = angular.fromJson(angular.toJson(document));

      if (!document.consentGranted) {
        document.consentInformation = undefined;
        document.consentDocuments = undefined;
      }

      if (!document.mutuallyAgreedTermsEstablished) {
        document.mutuallyAgreedTermsInformation = undefined;
        document.mutuallyAgreedTermsDocuments = undefined;
      }

      if (document.gisFiles && document.gisFiles.length===0) {
        document.gisFiles = undefined;
      }

      if (document.amendedPermits && document.amendedPermits.length===0) {
        document.amendedPermits = undefined;
      }

      if (!document.amendedPermits) {
        document.consentedAmendment = undefined;
        //document.amendmentsDescription = undefined;
      }
      if (document.providerConfidential) {
        document.providers = undefined;
      }
      if (document.informedConsentConfidential) {
        document.informedConsents = undefined;
      }

      if (document.expiration=="") {
        document.expiration = undefined;
      }
      if (document.geneticResourcesConfidential) {
        document.geneticResources = undefined;
      }
      if(!$scope.documentExists){
        document.amendmentIntent = undefined;
        document.amendmentsDescription = undefined;
      }
      if(!$scope.isOthers()){
        document.keywordOthers = undefined;
      }
      if (/^\s*$/g.test(document.notes))
        document.notes = undefined;

      return document;
    };

    //==================================
    //
    //==================================
    $scope.isCommercial = function (document) {
      document = document || $scope.document;

      if (!document || !document.usage)
        return false;

      var qLibraries = Enumerable.from(document.usage);

      return qLibraries.Any(function (o) { return o.identifier == "5E833A3F-87D1-4ADD-8701-9F1B76383017"; });
    };

    //This edit contact stuff should NOT be here... it should probably be in a directive or something.
    //==================================
    //
    //==================================
    $scope.editContact = function(property) {
      $scope.editedProperty = property;
      $scope.editedContact  = clone($scope.document[property] || { source : guid(),  type: "organization" });
    };

    //==================================
    //
    //==================================
    $scope.isOthers = function(document) {

      document = document || $scope.document;
      if (!document || !document.keywords)
        return false;

      var qLibraries = Enumerable.from(document.keywords);

      return qLibraries.any(function (o) { return o.identifier == "5B6177DD-5E5E-434E-8CB7-D63D67D5EBED"; });

    };

    //==================================
    //
    //==================================
    $scope.saveContact = function() {

      if(!$scope.editedProperty)
        return;

      $scope.document[$scope.editedProperty] = clone($scope.editedContact);
    };

    $scope.setDocument();
  }]);
});
<commit_msg>resolve confilit<commit_after>define(['app', '/app/views/forms/edit/edit.js'], function (app) {

  app.controller("editAbsPermit", ["$scope", "authHttp", "Thesaurus", "guid", "$filter", "$q", "Enumerable", "editFormUtility", "$controller", function ($scope, $http, Thesaurus, guid, $filter, $q, Enumerable, editFormUtility, $controller) {
    $controller('editController', {$scope: $scope});

    _.extend($scope.options, {
      usage		: function () {
        return $http.get("/api/v2013/thesaurus/domains/A7B77788-8C90-4849-9327-E181E9522F3A/terms",	{ cache: true }).then(function (o) {
          return o.data;
        });
      },
      keywords  : function () {
        return $q.all([
          $http.get("/api/v2013/thesaurus/domains/1A22EAAB-9BBC-4543-890E-DEF913F59E98/terms", { cache: true }),
          $http.get("/api/v2013/thesaurus/terms/5B6177DD-5E5E-434E-8CB7-D63D67D5EBED",   { cache: true })
        ]).then(function (o) {
          var data = o[0].data;
          data.push(o[1].data)
          return Thesaurus.buildTree(data);
        });
      },
    });
    //==================================
    //
    //==================================
    $scope.$watch("document.gisFiles", function () {

      var qLinks = [];
      var qGis = [];

      if ($scope.document)
        qLinks = $scope.document.gisFiles || [];

      /* global L: true */ // JSHint for leaflet

      angular.forEach(qLinks, function (link) {
        qGis.push($http.get(link.url).then(function (res) {
          return L.geoJson(res.data);
        }));
      });

      $q.all(qGis).then(function (layers) {
        $scope.gisLayer = layers;
      });
    });

    //==================================
    //
    //==================================
    $scope.$on("loadDocument", function(evt, info) {

      if(info.schema!="absPermit")
        return;

      if(info.identifier)//$scope.status=="loading"
          $q.when(editFormUtility.documentExists(info.identifier),function(exists){
              $scope.documentExists = exists;
              //amendment intent shoudl be entered by users for every edit/ clear it on load if any from previous update
              if($scope.document.amendmentIntent != undefined){
                $scope.document.amendmentIntent = undefined;
}
              if($scope.document.amendmentsDescription)
                $scope.document.amendmentsDescription = undefined;

          });
    });

    //==================================
    //
    //==================================
    $scope.getCleanDocument = function(document) {

      document = document || $scope.document;

      if (!document)
        return undefined;

      document = angular.fromJson(angular.toJson(document));

      if (!document.consentGranted) {
        document.consentInformation = undefined;
        document.consentDocuments = undefined;
      }

      if (!document.mutuallyAgreedTermsEstablished) {
        document.mutuallyAgreedTermsInformation = undefined;
        document.mutuallyAgreedTermsDocuments = undefined;
      }

      if (document.gisFiles && document.gisFiles.length===0) {
        document.gisFiles = undefined;
      }

      if (document.amendedPermits && document.amendedPermits.length===0) {
        document.amendedPermits = undefined;
      }

      if (!document.amendedPermits) {
        document.consentedAmendment = undefined;
        //document.amendmentsDescription = undefined;
      }
      if (document.providerConfidential) {
        document.providers = undefined;
      }
      if (document.informedConsentConfidential) {
        document.informedConsents = undefined;
      }

      if (document.expiration=="") {
        document.expiration = undefined;
      }
      if (document.geneticResourcesConfidential) {
        document.geneticResources = undefined;
      }
      if(!$scope.documentExists){
        document.amendmentIntent = undefined;
        document.amendmentsDescription = undefined;
      }
      if(!$scope.isOthers()){
        document.keywordOthers = undefined;
      }
      if (/^\s*$/g.test(document.notes))
        document.notes = undefined;

      return document;
    };

    //==================================
    //
    //==================================
    $scope.isCommercial = function (document) {
      document = document || $scope.document;

      if (!document || !document.usage)
        return false;

      var qLibraries = Enumerable.from(document.usage);

      return qLibraries.Any(function (o) { return o.identifier == "5E833A3F-87D1-4ADD-8701-9F1B76383017"; });
    };

    //This edit contact stuff should NOT be here... it should probably be in a directive or something.
    //==================================
    //
    //==================================
    $scope.editContact = function(property) {
      $scope.editedProperty = property;
      $scope.editedContact  = clone($scope.document[property] || { source : guid(),  type: "organization" });
    };

    //==================================
    //
    //==================================
    $scope.isOthers = function(document) {

      document = document || $scope.document;
      if (!document || !document.keywords)
        return false;

      var qLibraries = Enumerable.from(document.keywords);

      return qLibraries.any(function (o) { return o.identifier == "5B6177DD-5E5E-434E-8CB7-D63D67D5EBED"; });

    };

    //==================================
    //
    //==================================
    $scope.saveContact = function() {

      if(!$scope.editedProperty)
        return;

      $scope.document[$scope.editedProperty] = clone($scope.editedContact);
    };

    $scope.setDocument();
  }]);
});
<|endoftext|>


<commit_before><!-- Yandex.Metrika counter -->
<script type="text/javascript">
    (function (d, w, c) {
        (w[c] = w[c] || []).push(function() {
            try {
                w.yaCounter29684095 = new Ya.Metrika({
                    id:29684095,
                    clickmap:true,
                    trackLinks:true,
                    accurateTrackBounce:true,
                    webvisor:true
                });
            } catch(e) { }
        });

        var n = d.getElementsByTagName("script")[0],
            s = d.createElement("script"),
            f = function () { n.parentNode.insertBefore(s, n); };
        s.type = "text/javascript";
        s.async = true;
        s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js";

        if (w.opera == "[object Opera]") {
            d.addEventListener("DOMContentLoaded", f, false);
        } else { f(); }
    })(document, window, "yandex_metrika_callbacks");
</script>
<commit_msg>yaMetrics bug<commit_after>    (function (d, w, c) {
        (w[c] = w[c] || []).push(function() {
            try {
                w.yaCounter29684095 = new Ya.Metrika({
                    id:29684095,
                    clickmap:true,
                    trackLinks:true,
                    accurateTrackBounce:true,
                    webvisor:true
                });
            } catch(e) { }
        });

        var n = d.getElementsByTagName("script")[0],
            s = d.createElement("script"),
            f = function () { n.parentNode.insertBefore(s, n); };
        s.type = "text/javascript";
        s.async = true;
        s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js";

        if (w.opera == "[object Opera]") {
            d.addEventListener("DOMContentLoaded", f, false);
        } else { f(); }
    })(document, window, "yandex_metrika_callbacks");
<|endoftext|>


<commit_before>/**
 * @fileoverview The game model, which is composed of every model used in a
 * single game.
 *
 * @author joseph@cs.utexas.edu (Joe Tessler)
 */

goog.provide('cn.model.Game');

goog.require('cn.LevelData.levels');
goog.require('cn.constants');
goog.require('cn.model.Bot');
goog.require('cn.model.Cargo');
goog.require('cn.model.CargoColor');
goog.require('cn.model.Level');
goog.require('cn.model.Log');
goog.require('cn.model.PathModel');
goog.require('cn.model.Program');
goog.require('cn.model.Stack');
goog.require('goog.array');

/**
 * @param {number=} opt_width The entire game's screen width.
 * @param {number=} opt_height The entire game's screen height.
 * @constructor
 * @extends {cn.model.PathModel}
 */
cn.model.Game = function(opt_width, opt_height) {
  goog.base(
      this,
      opt_width || cn.constants.GAME_WIDTH,
      opt_height || cn.constants.GAME_HEIGHT,
      cn.constants.GAME_COLOR);
  this.path.moveTo(0, 0)
           .lineTo(this.width, 0)
           .lineTo(this.width, this.height)
           .lineTo(0, this.height)
           .lineTo(0, 0);

  this.bot = new cn.model.Bot();
  this.program = new cn.model.Program();
  this.log = new cn.model.Log();
};
goog.inherits(cn.model.Game, cn.model.PathModel);

/** @type {!cn.model.Bot} */
cn.model.Game.prototype.bot;

/** @type {!cn.model.Level} */
cn.model.Game.prototype.level;

/** @type {!cn.model.Level} */
cn.model.Game.prototype.goal;

/** @type {!cn.LevelData} */
cn.model.Game.prototype.levelData;

/** @type {!cn.model.Program} */
cn.model.Game.prototype.program;

/** @type {!cn.model.Log} */
cn.model.Game.prototype.log;

/** @type {string} */
cn.model.Game.prototype.id;

/**
 * Sets up the game models' positions.
 */
cn.model.Game.prototype.setupModelPositions = function() {
  this.goal.setPosition(
      Math.floor((this.width - this.level.width) / 2),
      cn.constants.GOAL_HEIGHT * 2 - this.level.height
          - cn.constants.GOAL_MARGIN);
  this.goal.scale(0.5);
  this.level.setPosition(
      Math.floor((this.width - this.level.width) / 2),
      this.height - this.level.height - cn.constants.GAME_MARGIN);
  this.bot.setPosition(
      this.level.stacks[this.bot.position].getX(),
      cn.constants.GAME_MARGIN + Math.floor(this.bot.height / 2));
};

/**
 * @inheritDoc
 */
cn.model.Game.prototype.forEachSubModel = function(f, opt_obj) {
  goog.array.forEach([this.bot, this.level], f, opt_obj);
};

/**
 * @inheritDoc
 */
cn.model.Game.prototype.reset = function() {
  goog.base(this, 'reset');
  this.program.reset();
  this.bot.position = this.levelData.botPosition;
  this.setupModelPositions();
};

/**
 * @param {!cn.LevelData} levelData The level to load.
 */
cn.model.Game.prototype.loadLevel = function(levelData) {
  this.levelData = levelData;
  this.level = new cn.model.Level(levelData.initial);
  this.goal = new cn.model.Level(levelData.goal);
  this.program.init(levelData.functions);
  this.reset();
};

/**
 * @return {number} The number of stars awarded based on the number of registers
 * used.
 */
cn.model.Game.prototype.getStars = function() {
  var count = this.program.instructionCount();
  if (count <= this.levelData.stars[2]) {
    return 3;
  }
  if (count <= this.levelData.stars[1]) {
    return 2;
  }
  if (count <= this.levelData.stars[0]) {
    return 1;
  }
  return 0;
};
<commit_msg>Lint fix.<commit_after>/**
 * @fileoverview The game model, which is composed of every model used in a
 * single game.
 *
 * @author joseph@cs.utexas.edu (Joe Tessler)
 */

goog.provide('cn.model.Game');

goog.require('cn.LevelData.levels');
goog.require('cn.constants');
goog.require('cn.model.Bot');
goog.require('cn.model.Cargo');
goog.require('cn.model.CargoColor');
goog.require('cn.model.Level');
goog.require('cn.model.Log');
goog.require('cn.model.PathModel');
goog.require('cn.model.Program');
goog.require('cn.model.Stack');
goog.require('goog.array');

/**
 * @param {number=} opt_width The entire game's screen width.
 * @param {number=} opt_height The entire game's screen height.
 * @constructor
 * @extends {cn.model.PathModel}
 */
cn.model.Game = function(opt_width, opt_height) {
  goog.base(
      this,
      opt_width || cn.constants.GAME_WIDTH,
      opt_height || cn.constants.GAME_HEIGHT,
      cn.constants.GAME_COLOR);
  this.path.moveTo(0, 0)
           .lineTo(this.width, 0)
           .lineTo(this.width, this.height)
           .lineTo(0, this.height)
           .lineTo(0, 0);

  this.bot = new cn.model.Bot();
  this.program = new cn.model.Program();
  this.log = new cn.model.Log();
};
goog.inherits(cn.model.Game, cn.model.PathModel);

/** @type {!cn.model.Bot} */
cn.model.Game.prototype.bot;

/** @type {!cn.model.Level} */
cn.model.Game.prototype.level;

/** @type {!cn.model.Level} */
cn.model.Game.prototype.goal;

/** @type {!cn.LevelData} */
cn.model.Game.prototype.levelData;

/** @type {!cn.model.Program} */
cn.model.Game.prototype.program;

/** @type {!cn.model.Log} */
cn.model.Game.prototype.log;

/** @type {string} */
cn.model.Game.prototype.id;

/**
 * Sets up the game models' positions.
 */
cn.model.Game.prototype.setupModelPositions = function() {
  var consts = cn.constants;
  this.goal.setPosition(
      Math.floor((this.width - this.level.width) / 2),
      consts.GOAL_HEIGHT * 2 - this.level.height - consts.GOAL_MARGIN);
  this.goal.scale(0.5);
  this.level.setPosition(
      Math.floor((this.width - this.level.width) / 2),
      this.height - this.level.height - consts.GAME_MARGIN);
  this.bot.setPosition(
      this.level.stacks[this.bot.position].getX(),
      consts.GAME_MARGIN + Math.floor(this.bot.height / 2));
};

/**
 * @inheritDoc
 */
cn.model.Game.prototype.forEachSubModel = function(f, opt_obj) {
  goog.array.forEach([this.bot, this.level], f, opt_obj);
};

/**
 * @inheritDoc
 */
cn.model.Game.prototype.reset = function() {
  goog.base(this, 'reset');
  this.program.reset();
  this.bot.position = this.levelData.botPosition;
  this.setupModelPositions();
};

/**
 * @param {!cn.LevelData} levelData The level to load.
 */
cn.model.Game.prototype.loadLevel = function(levelData) {
  this.levelData = levelData;
  this.level = new cn.model.Level(levelData.initial);
  this.goal = new cn.model.Level(levelData.goal);
  this.program.init(levelData.functions);
  this.reset();
};

/**
 * @return {number} The number of stars awarded based on the number of registers
 * used.
 */
cn.model.Game.prototype.getStars = function() {
  var count = this.program.instructionCount();
  if (count <= this.levelData.stars[2]) {
    return 3;
  }
  if (count <= this.levelData.stars[1]) {
    return 2;
  }
  if (count <= this.levelData.stars[0]) {
    return 1;
  }
  return 0;
};
<|endoftext|>


<commit_before>var en_US_trans = {
	// aggregates - keys should match Kaltura server
	"audience": "Audience",
	"seconds_viewed": "Minutes Viewed", // text should read minutes, not seconds
	"buffertime": "Average Buffering Time per Minute (seconds)",
	"bitrate": "Average Bitrate",
	"agg_audience_tt":"the number of viewers at the moment",
	"agg_secs_tt":"sum of minutes viewed by all viewers so far",
	"agg_buffer_tt":"average time per minute that viewers experienced buffering",
	"agg_bitrate_tt":"the average bitrate viewers are consuming",

	"dashboard" : {
		"Live_Content_36": "Live Content (in past 36 hours)",
		"Show_All_Entries": "Show All Entries",
		"Show_Kaltura": "Show Kaltura Live Now Only",
		"Audience": "Audience",
		"Peak_Audience": "Peak Audience",
		"Minutes_Viewed": "Minutes Viewed",
		"Buffer_Time": "Buffering Time",
		"Avg_Bitrate": "Average Bitrate",
		"Investigate": "Investigate"
	},

	"entry" : {
		"Live_Content": "Live Content",
		"Investigate": "Investigate",
		"Audience": "Audience",
		"Location": "Location",
		"Location_tt": "audience change based on geography and time",
		"Top_referals": "Top Referrers",
		"Top_referals_tt": "top HTTP referrers that most viewers visited to view the live media",
		"Domain": "Referrer",
		"Visits": "Visits",
		"of_total": "% of total"
	},

	"main" : {
		// tab names (translations) should match names in KMC analytics
		"Content_Reports": "Content Reports",
		"Community_Reports": "Users & Community Reports",
		"Storage_Reports": "Bandwidth & Storage Reports",
		"System_Reports": "System Reports",
		"Live_Reports": "Live Reports"
	}
};
<commit_msg>PLAT-1782 text change<commit_after>var en_US_trans = {
	// aggregates - keys should match Kaltura server
	"audience": "Audience",
	"seconds_viewed": "Minutes Viewed", // text should read minutes, not seconds
	"buffertime": "Average Buffering Time per Minute (seconds)",
	"bitrate": "Average Bitrate",
	"agg_audience_tt":"the number of viewers at the moment",
	"agg_secs_tt":"sum of minutes viewed by all viewers so far",
	"agg_buffer_tt":"average time per minute that viewers experienced buffering",
	"agg_bitrate_tt":"the average bitrate viewers are consuming",

	"dashboard" : {
		"Live_Content_36": "Live Content (in past 36 hours)",
		"Show_All_Entries": "Show All Entries",
		"Show_Kaltura": "Show Kaltura Live Now Only",
		"Audience": "Audience",
		"Peak_Audience": "Peak Audience",
		"Minutes_Viewed": "Minutes Viewed",
		"Buffer_Time": "Buffering Time",
		"Avg_Bitrate": "Average Bitrate",
		"Investigate": "Details"
	},

	"entry" : {
		"Live_Content": "Live Content",
		"Investigate": "Details",
		"Audience": "Audience",
		"Location": "Location",
		"Location_tt": "audience change based on geography and time",
		"Top_referals": "Top Referrers",
		"Top_referals_tt": "top HTTP referrers that most viewers visited to view the live media",
		"Domain": "Referrer",
		"Visits": "Visits",
		"of_total": "% of total"
	},

	"main" : {
		// tab names (translations) should match names in KMC analytics
		"Content_Reports": "Content Reports",
		"Community_Reports": "Users & Community Reports",
		"Storage_Reports": "Bandwidth & Storage Reports",
		"System_Reports": "System Reports",
		"Live_Reports": "Live Reports"
	}
};
<|endoftext|>


<commit_before>/* Set the defaults for DataTables initialisation */
$.extend( true, $.fn.dataTable.defaults, {
	"sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sLengthMenu": "_MENU_",
        "sSearch": "",
        "sInfoFiltered": "",
    },
    "fnPreDrawCallback": function(oSettings, json) {
        $('.dataTables_filter input').addClass('form-control input');
        $('.dataTables_length select').addClass('form-control input');
        $('.dataTables_info').addClass('form-control');
    }
} );

/* Default class modification */
$.extend( $.fn.dataTableExt.oStdClasses, {
    "sWrapper": "dataTables_wrapper form-inline",
    "sFilterInput": "form-control input-sm",
    "sLengthSelect": "form-control input-sm"
} );

/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
    return {
        "iStart":         oSettings._iDisplayStart,
        "iEnd":           oSettings.fnDisplayEnd(),
        "iLength":        oSettings._iDisplayLength,
        "iTotal":         oSettings.fnRecordsTotal(),
        "iFilteredTotal": oSettings.fnRecordsDisplay(),
        "iPage":          oSettings._iDisplayLength === -1 ?
            0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
        "iTotalPages":    oSettings._iDisplayLength === -1 ?
            0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
    };
};

/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
    "bootstrap": {
        "fnInit": function( oSettings, nPaging, fnDraw ) {
            var oLang = oSettings.oLanguage.oPaginate;
            var fnClickHandler = function ( e ) {
                e.preventDefault();
                if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                    fnDraw( oSettings );
                }
            };

            $(nPaging).append(
                '
'+
					'
'+oLang.sPrevious+'
'+
					'
'+oLang.sNext+'
'+
                '
'
            );
            var els = $('a', nPaging);
            $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
            $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
        },

        "fnUpdate": function ( oSettings, fnDraw ) {
            var iListLength = 5;
            var oPaging = oSettings.oInstance.fnPagingInfo();
            var an = oSettings.aanFeatures.p;
            var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

            if ( oPaging.iTotalPages < iListLength) {
                iStart = 1;
                iEnd = oPaging.iTotalPages;
            }
            else if ( oPaging.iPage <= iHalf ) {
                iStart = 1;
                iEnd = iListLength;
            } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
                iStart = oPaging.iTotalPages - iListLength + 1;
                iEnd = oPaging.iTotalPages;
            } else {
                iStart = oPaging.iPage - iHalf + 1;
                iEnd = iStart + iListLength - 1;
            }

            for ( i=0, ien=an.length ; i<ien ; i++ ) {
                // Remove the middle elements
                $('li:gt(0)', an[i]).filter(':not(:last)').remove();

                // Add the new list items and their event handlers
                for ( j=iStart ; j<=iEnd ; j++ ) {
                    sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                    $('
'+j+'
')
                        .insertBefore( $('li:last', an[i])[0] )
                        .bind('click', function (e) {
                            e.preventDefault();
                            oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                            fnDraw( oSettings );
                        } );
                }

                // Add / remove disabled classes from the static elements
                if ( oPaging.iPage === 0 ) {
                    $('li:first', an[i]).addClass('disabled');
                } else {
                    $('li:first', an[i]).removeClass('disabled');
                }

                if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                    $('li:last', an[i]).addClass('disabled');
                } else {
                    $('li:last', an[i]).removeClass('disabled');
                }
            }
        }
    }
} );

/*
 * TableTools Bootstrap compatibility
 * Required TableTools 2.1+
 */
if ( $.fn.DataTable.TableTools ) {
    // Set the classes that TableTools uses to something suitable for Bootstrap
    $.extend( true, $.fn.DataTable.TableTools.classes, {
        "container": "DTTT btn-group",
        "buttons": {
            "normal": "btn btn-default",
            "disabled": "disabled"
        },
        "collection": {
            "container": "DTTT_dropdown dropdown-menu",
            "buttons": {
                "normal": "",
                "disabled": "disabled"
            }
        },
        "print": {
            "info": "DTTT_print_info modal"
        },
        "select": {
            "row": "active"
        }
    } );

    // Have the collection use a bootstrap compatible dropdown
    $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
        "collection": {
            "container": "ul",
            "button": "li",
            "liner": "a"
        }
    } );
}

<commit_msg>Toggle bAutoWidth for datatable<commit_after>/* Set the defaults for DataTables initialisation */
$.extend( true, $.fn.dataTable.defaults, {
	"sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sLengthMenu": "_MENU_",
        "sSearch": "",
        "sInfoFiltered": "",
    },
    "bAutoWidth": false,
    "fnPreDrawCallback": function(oSettings, json) {
        $('.dataTables_filter input').addClass('form-control input');
        $('.dataTables_length select').addClass('form-control input');
        $('.dataTables_info').addClass('form-control');
    }
} );

/* Default class modification */
$.extend( $.fn.dataTableExt.oStdClasses, {
    "sWrapper": "dataTables_wrapper form-inline",
    "sFilterInput": "form-control input-sm",
    "sLengthSelect": "form-control input-sm"
} );

/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
    return {
        "iStart":         oSettings._iDisplayStart,
        "iEnd":           oSettings.fnDisplayEnd(),
        "iLength":        oSettings._iDisplayLength,
        "iTotal":         oSettings.fnRecordsTotal(),
        "iFilteredTotal": oSettings.fnRecordsDisplay(),
        "iPage":          oSettings._iDisplayLength === -1 ?
            0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
        "iTotalPages":    oSettings._iDisplayLength === -1 ?
            0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
    };
};

/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
    "bootstrap": {
        "fnInit": function( oSettings, nPaging, fnDraw ) {
            var oLang = oSettings.oLanguage.oPaginate;
            var fnClickHandler = function ( e ) {
                e.preventDefault();
                if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                    fnDraw( oSettings );
                }
            };

            $(nPaging).append(
                '
'+
					'
'+oLang.sPrevious+'
'+
					'
'+oLang.sNext+'
'+
                '
'
            );
            var els = $('a', nPaging);
            $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
            $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
        },

        "fnUpdate": function ( oSettings, fnDraw ) {
            var iListLength = 5;
            var oPaging = oSettings.oInstance.fnPagingInfo();
            var an = oSettings.aanFeatures.p;
            var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

            if ( oPaging.iTotalPages < iListLength) {
                iStart = 1;
                iEnd = oPaging.iTotalPages;
            }
            else if ( oPaging.iPage <= iHalf ) {
                iStart = 1;
                iEnd = iListLength;
            } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
                iStart = oPaging.iTotalPages - iListLength + 1;
                iEnd = oPaging.iTotalPages;
            } else {
                iStart = oPaging.iPage - iHalf + 1;
                iEnd = iStart + iListLength - 1;
            }

            for ( i=0, ien=an.length ; i<ien ; i++ ) {
                // Remove the middle elements
                $('li:gt(0)', an[i]).filter(':not(:last)').remove();

                // Add the new list items and their event handlers
                for ( j=iStart ; j<=iEnd ; j++ ) {
                    sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                    $('
'+j+'
')
                        .insertBefore( $('li:last', an[i])[0] )
                        .bind('click', function (e) {
                            e.preventDefault();
                            oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                            fnDraw( oSettings );
                        } );
                }

                // Add / remove disabled classes from the static elements
                if ( oPaging.iPage === 0 ) {
                    $('li:first', an[i]).addClass('disabled');
                } else {
                    $('li:first', an[i]).removeClass('disabled');
                }

                if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                    $('li:last', an[i]).addClass('disabled');
                } else {
                    $('li:last', an[i]).removeClass('disabled');
                }
            }
        }
    }
} );

/*
 * TableTools Bootstrap compatibility
 * Required TableTools 2.1+
 */
if ( $.fn.DataTable.TableTools ) {
    // Set the classes that TableTools uses to something suitable for Bootstrap
    $.extend( true, $.fn.DataTable.TableTools.classes, {
        "container": "DTTT btn-group",
        "buttons": {
            "normal": "btn btn-default",
            "disabled": "disabled"
        },
        "collection": {
            "container": "DTTT_dropdown dropdown-menu",
            "buttons": {
                "normal": "",
                "disabled": "disabled"
            }
        },
        "print": {
            "info": "DTTT_print_info modal"
        },
        "select": {
            "row": "active"
        }
    } );

    // Have the collection use a bootstrap compatible dropdown
    $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
        "collection": {
            "container": "ul",
            "button": "li",
            "liner": "a"
        }
    } );
}

<|endoftext|>