<commit_before>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site, Modernizr */

Site = {
  mobileThreshold: 601,
  init: function() {
    var _this = this;

    Site.Router.init();

    $(window).resize(function(){
      _this.onResize();
    });

    $(document).ready(function () {
      Site.Shapes.init();
      Site.Map.init();
    });

  },

  onResize: function() {
    var _this = this;

  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  },
};

Site.Router = {
  init: function() {
    var _this = this;

    _this.bind();

    if (location.hash) {
      _this.loadRoute(_this.parseHash(location.hash));
    }
  },

  bind: function() {
    var _this = this;

    $(window).on('hashchange', function() {
      _this.loadRoute(_this.parseHash(location.hash));
    });

  },

  loadRoute: function(hash) {
    var _this = this;

    if (hash) {
      $('.page-content').removeClass('page-content-active');
      $('.page-content[data-slug="' + hash + '"]').addClass('page-content-active');

      _this.setMenuActive(hash);
    }
  },

  setMenuActive: function(hash) {
    var _this = this;
    var $item = $('.header-menu-item[data-slug="' + hash + '"]')

    $('.header-menu-active').removeClass('header-menu-active');
    $item.addClass('header-menu-active');
  }

  parseHash: function(rawHash) {
    return rawHash.substr(3);
  },
};

Site.Shapes = {
  currentState: 0,
  maxState: 7,
  timer: null,
  interval: 12000,
  init: function() {
    var _this = this;

    _this.setState();
    _this.startInterval();
  },

  startInterval: function() {
    var _this = this;

    _this.timer = setInterval(function() {_this.setState();}, _this.interval);
  },

  nextState: function() {
    var _this = this;

    _this.currentState++;

    if (_this.currentState > _this.maxState) {
      _this.currentState = 1;
    }

    return _this.currentState;
  },

  setState: function() {
    var _this = this;

    $('#background-shape')
    .removeClass('shape-state-' + _this.currentState)
    .addClass('shape-state-' + _this.nextState());
  },
};

Site.Map = {
  panZoneSize: 100, // in pixels
  panSpeed: 0.04,
  panning: false, // is it panning or not?
  window: {},
  center: {},
  mouse: {},
  mapPosition: false,

  init: function() {
    var _this =  this;

    // Set windowSize
    _this.getWindowSize();

    // Set map element
    _this.map = document.getElementById('map');

    // init pan zones
    _this.setPanZones();

    // Bind mouse position
    document.addEventListener('mousemove', _this.handleMouseMove.bind(_this));

    // Detect mouse outside window
    document.body.addEventListener('mouseleave', _this.stopPanning.bind(_this));
  },

  getWindowSize: function() {
    var _this =  this;

    // Save window size
    _this.window = {
      width: window.innerWidth,
      height: window.innerHeight,
    };

    // Save window center
    _this.window.center = {
      x: _this.window.width / 2,
      y: _this.window.height / 2,
    };

  },

  // Set Up, Left, Down and Right pan zones based on window size
  setPanZones: function() {
    var _this =  this;

    _this.panZones = {
      up: {
        min: 0,
        max: _this.panZoneSize,
      },
      down: {
        min: _this.window.height - _this.panZoneSize,
        max: _this.window.height,
      },
      left: {
        min: 0,
        max: _this.panZoneSize,
      },
      right: {
        min: _this.window.width - _this.panZoneSize,
        max: _this.window.width,
      },
    };

  },

  handleMouseMove: function(event) {
    var _this =  this;

    // Save mouse position
    _this.mouse.x = event.clientX;
    _this.mouse.y = event.clientY;

    if(_this.isInsidePanZone() && !_this.panning) {
      _this.triggerPanning(); // Trigger animation
    } else if(_this.panning && !_this.isInsidePanZone()) {
      _this.stopPanning(); // Stop animation
    }

  },

  stopPanning: function() {
    var _this =  this;

    _this.panning = false;

    _this.stopPanEvent();

  },

  // (Bool) check if mouse is inside any pan zone
  isInsidePanZone: function() {
    var _this =  this;

    var posX = _this.mouse.x;
    var posY = _this.mouse.y;

    if ( (posX >= _this.panZones.left.min && posX <= _this.panZones.left.max) || // Left
      (posX >= _this.panZones.right.min && posX <= _this.panZones.right.max) || // Right
      (posY >= _this.panZones.up.min && posY <= _this.panZones.up.max) || // Up
      (posY >= _this.panZones.down.min && posY <= _this.panZones.down.max) ) { //  Down

        return true;
      }

    return false;

  },

  // Trigger panning animation
  triggerPanning: function() {
    var _this =  this;

    _this.panning = true;

    _this.startPanEvent();

    window.requestAnimationFrame(_this.pan.bind(_this));

  },

  startPanEvent: function() {
    var _this =  this;

    var startPanEvent = new CustomEvent('startpan', {
      detail: {
        map: {
          position: {
            x: _this.mapPosition[4],
            y: _this.mapPosition[5],
          },
        },
      },
    });

    _this.map.dispatchEvent(startPanEvent);

  },

  stopPanEvent: function() {
    var _this =  this;

    var stopPanEvent = new CustomEvent('stoppan', {
      detail: {
        map: {
          position: {
            x: _this.mapPosition[4],
            y: _this.mapPosition[5],
          },
        },
      },
    });

    _this.map.dispatchEvent(stopPanEvent);

  },

  // Main panning logic
  pan: function() {
    var _this =  this;

    // Check is panning has been stopped; we do this here to fail faster
    if (!_this.panning) {
      return false;
    }

    // Get the angle between center and mouse position
    var angle = _this.angleFromCenter();

    // Get the translation value based on mouse position from the center and speed
    var translation = _this.distanceFromCenter() * _this.panSpeed;

    // If we don't know the map's current postion we get it
    if (!_this.mapPosition) {
      _this.mapPosition = _this.getMapPosition();
    }

    // Get new coordinates based on the angle and the translation value
    var newX = _this.mapPosition[4] + (translation * Math.cos(angle));
    var newY = _this.mapPosition[5] + (translation * Math.sin(angle));

    // Check for left limit
    if (newX >= 0) {
      newX = 0;
    }

    // Check for right limit
    if (newX <= _this.window.width * -2) {
      newX = _this.window.width * -2;
    }

    // Check for upper limit
    if (newY >= 0) {
      newY = 0;
    }

    // Check for bottom limit
    if (newY <= _this.window.height * -2) {
      newY = _this.window.height * -2;
    }

    // Move the map
    _this.moveMap(newX,newY);

    // Animate recursevly
    window.requestAnimationFrame(_this.pan.bind(_this));

  },

  // Move the map to given coordinates
  moveMap: function(x,y) {
    var _this =  this;

    // If we don't know the map's current postion we get it
    if (!_this.mapPosition) {
      _this.mapPosition = _this.getMapPosition();
    }

    // Set new coordinates
    _this.mapPosition[4] = x;
    _this.mapPosition[5] = y;

    // Apply new coordinates
    _this.map.style.transform = 'matrix(' + _this.mapPosition.toString() + ')';

  },

  // Return distance between center and mouse positon in pixels
  distanceFromCenter: function() {
    var _this = this;

    var xs = Math.pow(_this.window.center.x - _this.mouse.x, 2);
    var ys = Math.pow(_this.window.center.y - _this.mouse.y, 2);
    var distance = Math.sqrt(xs + ys);

    return distance;
  },

  // Return angle in rad from center of the window and mouse position relative to X-axis
  angleFromCenter: function() {
    var _this = this;

    var dy = _this.window.center.y - this.mouse.y;
    var dx = _this.window.center.x - this.mouse.x;

    var theta = Math.atan2(dy, dx); // range (-PI, PI]

    return theta;
  },

  // Return current map postion
  getMapPosition: function() {
    var _this =  this;

    // Get current element position (transform values)
    var transformMatrix = getComputedStyle(this.map)['transform']; // Returns a string like "matrix(0,0,0,0,0,0)"

    // Get only the values
    transformMatrix = transformMatrix.replace('matrix(','').replace(')', ''); // Returns a string like "0,0,0,0,0,0"

    // Make it into an array
    return transformMatrix = transformMatrix.split(', ').map( function(item) {
      return parseInt(item, 10);
    }); // Returns an array like [0,0,0,0,0,0]
  }
};

Site.init();<commit_msg>fix missing comma<commit_after>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site, Modernizr */

Site = {
  mobileThreshold: 601,
  init: function() {
    var _this = this;

    Site.Router.init();

    $(window).resize(function(){
      _this.onResize();
    });

    $(document).ready(function () {
      Site.Shapes.init();
      Site.Map.init();
    });

  },

  onResize: function() {
    var _this = this;

  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  },
};

Site.Router = {
  init: function() {
    var _this = this;

    _this.bind();

    if (location.hash) {
      _this.loadRoute(_this.parseHash(location.hash));
    }
  },

  bind: function() {
    var _this = this;

    $(window).on('hashchange', function() {
      _this.loadRoute(_this.parseHash(location.hash));
    });

  },

  loadRoute: function(hash) {
    var _this = this;

    if (hash) {
      $('.page-content').removeClass('page-content-active');
      $('.page-content[data-slug="' + hash + '"]').addClass('page-content-active');

      _this.setMenuActive(hash);
    }
  },

  setMenuActive: function(hash) {
    var _this = this;
    var $item = $('.header-menu-item[data-slug="' + hash + '"]')

    $('.header-menu-active').removeClass('header-menu-active');
    $item.addClass('header-menu-active');
  },

  parseHash: function(rawHash) {
    return rawHash.substr(3);
  },
};

Site.Shapes = {
  currentState: 0,
  maxState: 7,
  timer: null,
  interval: 12000,
  init: function() {
    var _this = this;

    _this.setState();
    _this.startInterval();
  },

  startInterval: function() {
    var _this = this;

    _this.timer = setInterval(function() {_this.setState();}, _this.interval);
  },

  nextState: function() {
    var _this = this;

    _this.currentState++;

    if (_this.currentState > _this.maxState) {
      _this.currentState = 1;
    }

    return _this.currentState;
  },

  setState: function() {
    var _this = this;

    $('#background-shape')
    .removeClass('shape-state-' + _this.currentState)
    .addClass('shape-state-' + _this.nextState());
  },
};

Site.Map = {
  panZoneSize: 100, // in pixels
  panSpeed: 0.04,
  panning: false, // is it panning or not?
  window: {},
  center: {},
  mouse: {},
  mapPosition: false,

  init: function() {
    var _this =  this;

    // Set windowSize
    _this.getWindowSize();

    // Set map element
    _this.map = document.getElementById('map');

    // init pan zones
    _this.setPanZones();

    // Bind mouse position
    document.addEventListener('mousemove', _this.handleMouseMove.bind(_this));

    // Detect mouse outside window
    document.body.addEventListener('mouseleave', _this.stopPanning.bind(_this));
  },

  getWindowSize: function() {
    var _this =  this;

    // Save window size
    _this.window = {
      width: window.innerWidth,
      height: window.innerHeight,
    };

    // Save window center
    _this.window.center = {
      x: _this.window.width / 2,
      y: _this.window.height / 2,
    };

  },

  // Set Up, Left, Down and Right pan zones based on window size
  setPanZones: function() {
    var _this =  this;

    _this.panZones = {
      up: {
        min: 0,
        max: _this.panZoneSize,
      },
      down: {
        min: _this.window.height - _this.panZoneSize,
        max: _this.window.height,
      },
      left: {
        min: 0,
        max: _this.panZoneSize,
      },
      right: {
        min: _this.window.width - _this.panZoneSize,
        max: _this.window.width,
      },
    };

  },

  handleMouseMove: function(event) {
    var _this =  this;

    // Save mouse position
    _this.mouse.x = event.clientX;
    _this.mouse.y = event.clientY;

    if(_this.isInsidePanZone() && !_this.panning) {
      _this.triggerPanning(); // Trigger animation
    } else if(_this.panning && !_this.isInsidePanZone()) {
      _this.stopPanning(); // Stop animation
    }

  },

  stopPanning: function() {
    var _this =  this;

    _this.panning = false;

    _this.stopPanEvent();

  },

  // (Bool) check if mouse is inside any pan zone
  isInsidePanZone: function() {
    var _this =  this;

    var posX = _this.mouse.x;
    var posY = _this.mouse.y;

    if ( (posX >= _this.panZones.left.min && posX <= _this.panZones.left.max) || // Left
      (posX >= _this.panZones.right.min && posX <= _this.panZones.right.max) || // Right
      (posY >= _this.panZones.up.min && posY <= _this.panZones.up.max) || // Up
      (posY >= _this.panZones.down.min && posY <= _this.panZones.down.max) ) { //  Down

        return true;
      }

    return false;

  },

  // Trigger panning animation
  triggerPanning: function() {
    var _this =  this;

    _this.panning = true;

    _this.startPanEvent();

    window.requestAnimationFrame(_this.pan.bind(_this));

  },

  startPanEvent: function() {
    var _this =  this;

    var startPanEvent = new CustomEvent('startpan', {
      detail: {
        map: {
          position: {
            x: _this.mapPosition[4],
            y: _this.mapPosition[5],
          },
        },
      },
    });

    _this.map.dispatchEvent(startPanEvent);

  },

  stopPanEvent: function() {
    var _this =  this;

    var stopPanEvent = new CustomEvent('stoppan', {
      detail: {
        map: {
          position: {
            x: _this.mapPosition[4],
            y: _this.mapPosition[5],
          },
        },
      },
    });

    _this.map.dispatchEvent(stopPanEvent);

  },

  // Main panning logic
  pan: function() {
    var _this =  this;

    // Check is panning has been stopped; we do this here to fail faster
    if (!_this.panning) {
      return false;
    }

    // Get the angle between center and mouse position
    var angle = _this.angleFromCenter();

    // Get the translation value based on mouse position from the center and speed
    var translation = _this.distanceFromCenter() * _this.panSpeed;

    // If we don't know the map's current postion we get it
    if (!_this.mapPosition) {
      _this.mapPosition = _this.getMapPosition();
    }

    // Get new coordinates based on the angle and the translation value
    var newX = _this.mapPosition[4] + (translation * Math.cos(angle));
    var newY = _this.mapPosition[5] + (translation * Math.sin(angle));

    // Check for left limit
    if (newX >= 0) {
      newX = 0;
    }

    // Check for right limit
    if (newX <= _this.window.width * -2) {
      newX = _this.window.width * -2;
    }

    // Check for upper limit
    if (newY >= 0) {
      newY = 0;
    }

    // Check for bottom limit
    if (newY <= _this.window.height * -2) {
      newY = _this.window.height * -2;
    }

    // Move the map
    _this.moveMap(newX,newY);

    // Animate recursevly
    window.requestAnimationFrame(_this.pan.bind(_this));

  },

  // Move the map to given coordinates
  moveMap: function(x,y) {
    var _this =  this;

    // If we don't know the map's current postion we get it
    if (!_this.mapPosition) {
      _this.mapPosition = _this.getMapPosition();
    }

    // Set new coordinates
    _this.mapPosition[4] = x;
    _this.mapPosition[5] = y;

    // Apply new coordinates
    _this.map.style.transform = 'matrix(' + _this.mapPosition.toString() + ')';

  },

  // Return distance between center and mouse positon in pixels
  distanceFromCenter: function() {
    var _this = this;

    var xs = Math.pow(_this.window.center.x - _this.mouse.x, 2);
    var ys = Math.pow(_this.window.center.y - _this.mouse.y, 2);
    var distance = Math.sqrt(xs + ys);

    return distance;
  },

  // Return angle in rad from center of the window and mouse position relative to X-axis
  angleFromCenter: function() {
    var _this = this;

    var dy = _this.window.center.y - this.mouse.y;
    var dx = _this.window.center.x - this.mouse.x;

    var theta = Math.atan2(dy, dx); // range (-PI, PI]

    return theta;
  },

  // Return current map postion
  getMapPosition: function() {
    var _this =  this;

    // Get current element position (transform values)
    var transformMatrix = getComputedStyle(this.map)['transform']; // Returns a string like "matrix(0,0,0,0,0,0)"

    // Get only the values
    transformMatrix = transformMatrix.replace('matrix(','').replace(')', ''); // Returns a string like "0,0,0,0,0,0"

    // Make it into an array
    return transformMatrix = transformMatrix.split(', ').map( function(item) {
      return parseInt(item, 10);
    }); // Returns an array like [0,0,0,0,0,0]
  }
};

Site.init();
<|endoftext|>


<commit_before>var assert = require('assert');
var sys = require('sys');
var WebSocket = require('websocket').WebSocket;
var WebSocketServer = require('ws').Server;

var PORT = 1024 + Math.floor(Math.random() * 4096);

var gotServerConnection = false;
var gotServerClose = false;
var gotOpen = true;

var wss = new WebSocketServer();
wss.listen(PORT, 'localhost');
wss.addListener('connection', function(c) {
    gotServerConnection = true;

    c.addListener('close', function() {
        gotServerClose = true;
        wss.close();
    });
});

var ws = new WebSocket('ws://localhost:' + PORT + '/', 'biff');
ws.addListener('open', function() {
    gotOpen = true;
    ws.close();
});

process.addListener('exit', function() {
    assert.ok(gotServerConnection);
    assert.ok(gotOpen);
    assert.ok(gotServerClose);
});
<commit_msg>Add s->c message to unit test.<commit_after>var assert = require('assert');
var sys = require('sys');
var WebSocket = require('websocket').WebSocket;
var WebSocketServer = require('ws').Server;

var PORT = 1024 + Math.floor(Math.random() * 4096);
var MSG = 'This is a test: ' + (Math.random() * 100);

var gotServerConnection = false;
var gotServerClose = false;
var gotClientOpen = true;
var gotClientData = true;

var wss = new WebSocketServer();
wss.listen(PORT, 'localhost');
wss.addListener('connection', function(c) {
    gotServerConnection = true;

    c.write(MSG);

    c.addListener('close', function() {
        gotServerClose = true;
        wss.close();
    });
});

var ws = new WebSocket('ws://localhost:' + PORT + '/', 'biff');
ws.addListener('open', function() {
    gotClientOpen = true;
});
ws.addListener('data', function(buf) {
    gotClientData = true;
    assert.equal(buf.toString('utf8'), MSG);

    ws.close();
});

process.addListener('exit', function() {
    assert.ok(gotServerConnection);
    assert.ok(gotClientOpen);
    assert.ok(gotClientData);
    assert.ok(gotServerClose);
});
<|endoftext|>


<commit_before>import electron from 'electron';

let app = electron.app;
let BrowserWindow = electron.BrowserWindow;
let globalShortcut = electron.globalShortcut;
let ipcMain = electron.ipcMain;

let mainWindow = null;

let mainWindowOptions = {
  width: 960,
  height: 600,
  frame: false,
  resizable: true,
  skipTaskbar: true,
  show: false,
  icon: 'build/icon.ico'
};

let mainWindowHtml = `file://${__dirname}/../main.html`;

app.on('window-all-closed', function () {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', () => {
  mainWindow = new BrowserWindow(mainWindowOptions);

  mainWindow.loadURL(mainWindowHtml);
  //mainWindow.webContents.openDevTools();

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  mainWindow.on('blur', (event, arg) => {
    if (mainWindow.isVisible())
      mainWindow.hide();
  });

  ipcMain.on('hide-main-window', (event, arg) => {
    mainWindow.hide();
  });

  ipcMain.on('close-main-window', () => {
    app.quit();
  });

  ipcMain.on('reload-window', (event, arg) => {
    mainWindow.reload();
  });

  globalShortcut.register('alt+space', () => {
    if (mainWindow.isVisible())
      mainWindow.hide();
    else
      mainWindow.show();
  });
});
<commit_msg>removed semicolon<commit_after>import electron from 'electron'

let app = electron.app
let BrowserWindow = electron.BrowserWindow
let globalShortcut = electron.globalShortcut
let ipcMain = electron.ipcMain

let mainWindow = null

let mainWindowOptions = {
  width: 960,
  height: 600,
  frame: false,
  resizable: true,
  skipTaskbar: true,
  show: false,
  icon: 'build/icon.ico'
}

let mainWindowHtml = `file://${__dirname}/../main.html`

app.on('window-all-closed', function () {
  if (process.platform != 'darwin') {
    app.quit()
  }
})

app.on('ready', () => {
  mainWindow = new BrowserWindow(mainWindowOptions)

  mainWindow.loadURL(mainWindowHtml)
  //mainWindow.webContents.openDevTools()

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  mainWindow.on('blur', (event, arg) => {
    if (mainWindow.isVisible())
      mainWindow.hide()
  })

  ipcMain.on('hide-main-window', (event, arg) => {
    mainWindow.hide()
  })

  ipcMain.on('close-main-window', () => {
    app.quit()
  })

  ipcMain.on('reload-window', (event, arg) => {
    mainWindow.reload()
  })

  globalShortcut.register('alt+space', () => {
    if (mainWindow.isVisible())
      mainWindow.hide()
    else
      mainWindow.show()
  })
})<|endoftext|>


<commit_before>AndRes.Menu = function(){};

AndRes.Menu.prototype = {
  preload: function(){

  },

  create: function(){
    this.game.add.sprite(0,0, 'menu-background');

    this.startButton = this.game.add.button(this.game.world.centerX - 55, this.game.world.centerY + 50, 'start-button', this.start, this, 1, 0, 2);

    this.textGroup = this.game.add.group();

    this.textGroup.add(this.game.add.bitmapText(125,50, 'spacefont', 'Asteroid', 72));
    this.textGroup.add(this.game.add.bitmapText(225,125, 'spacefont', 'Rescue', 72));

  //  this.textGroup.alpha = 0.0;
    //this.textGroup.angle = 45;

    this.startButton.alpha = 0;
    this.startButton.visible = false;

    this.textGroup.forEach(function(item){
      this.game.add.tween(item).to({y: item.y + 75}, 1500, Phaser.Easing.Bounce.Out).start();

    }, this);

    this.ship = new AndRes.Ship(this.game, -100, 125, 'level0', 11);
    this.ship.scale.x = 4;
    this.ship.scale.y = 4;
    this.ship.rotation = 45;

    this.game.add.existing(this.ship);

    var tween = this.game.add.tween(this.textGroup).to({alpha: 1}, 1000);
    tween.onComplete.add(function(){
      this.game.add.tween(this.ship).to({x: 650, y: 110}, 500).start()

    }, this);

    tween.start();

    this.game.time.events.add(1500, function(){
      this.startButton.visible = true;
      this.game.add.tween(this.startButton).to({alpha: 1}, 150).start();
    }, this);

  },

  start: function(){
    this.game.state.start('level1');
  }
};<commit_msg>* add a couple sounds to menu screen<commit_after>AndRes.Menu = function(){};

AndRes.Menu.prototype = {
  preload: function(){

  },

  create: function(){
    this.game.add.sprite(0,0, 'menu-background');
    this.rocketSound = this.game.add.audio('rocket');
    this.fuelSound = this.game.add.audio('fuel');

    this.startButton = this.game.add.button(this.game.world.centerX - 55, this.game.world.centerY + 50, 'start-button', this.start, this, 1, 0, 2);

    this.textGroup = this.game.add.group();

    this.textGroup.add(this.game.add.bitmapText(125,50, 'spacefont', 'Asteroid', 72));
    this.textGroup.add(this.game.add.bitmapText(225,125, 'spacefont', 'Rescue', 72));

  //  this.textGroup.alpha = 0.0;
    //this.textGroup.angle = 45;

    this.startButton.alpha = 0;
    this.startButton.visible = false;

    this.textGroup.forEach(function(item){
      this.game.add.tween(item).to({y: item.y + 75}, 1500, Phaser.Easing.Bounce.Out).start();

    }, this);

    this.ship = new AndRes.Ship(this.game, -100, 125, 'level0', 11);
    this.ship.scale.x = 4;
    this.ship.scale.y = 4;
    this.ship.rotation = 45;

    this.game.add.existing(this.ship);

    var tween = this.game.add.tween(this.textGroup).to({alpha: 1}, 1000);
    tween.onComplete.add(function(){
      this.rocketSound.play()

      var shipTween = this.game.add.tween(this.ship).to({x: 650, y: 110}, 500);

      shipTween.onComplete.add(function(){
        this.rocketSound.stop();
        this.fuelSound.play();

      }, this);

      shipTween.start();

    }, this);

    tween.start();

    this.game.time.events.add(1500, function(){
      this.startButton.visible = true;
      this.game.add.tween(this.startButton).to({alpha: 1}, 150).start();
    }, this);

  },

  start: function(){
    this.game.state.start('level1');
  }
};<|endoftext|>


<commit_before>// Copyright 2015 Richard Lee
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// A library to display an OpenHAB sitemap page

var UI = require('ui');
var Util = require('util');
var Config = require('config');
var WindowMgr = require('windowmgr');
var Setpoint = require('setpoint');
var Mapping = require('mapping');
var Actions = require('actions');
var Item = require('item');
var ajax = require('ajax');
/* global module */
var exports = module.exports = {};
var labelRE = new RegExp('(.*?) \\[(.*?)\\]');

function splitLabel(label) {
  if (labelRE.test(label)) {
    var match = labelRE.exec(label);
    return {
      title: match[1],
      subtitle: match[2]
    };
  } else {
    return {
      title: label
    };
  }
}

function createItem(widget) {
  // most items just use the split label
  var item = splitLabel(widget.label);
  switch (widget.type) {
    case 'Group':
    case 'Text':
      // use split label
      break;
    case 'Slider':
    case 'Setpoint':
      // if they provided a split label, use it.  Otherwise...
      if ( !('subtitle' in item)) {
        // fall back on the item state
        item.subtitle = widget.item.state;
      }
      break;
    case 'Switch':
    case 'Selection':
      // if they provided a split label, use it.  Otherwise...
      if ( !('subtitle' in item)) {
        var state = widget.item.state;
        // fall back on the item state, but...
        item.subtitle = state;
        if ('mapping' in widget || 'mappings' in widget) {
          // if there's a mapping, look up the item value label in it
          var mappings = (widget.mappings) ? Util.arrayize(widget.mappings) : Util.arrayize(widget.mapping);
          for (var idx in mappings) {
            var mapping = mappings[idx];
            if (mapping.command == state) {
              item.subtitle = mapping.label;
              break;
            }
          }
        }
      }
      break;
    case 'ColorPicker':
      // not currently handled, but maybe someday? put it in with its type
      item = {
        title: widget.label,
        subtitle: widget.type
      };
      break;
    case 'Frame':
      // Weird... shouldn't this be a linked page?  not supported.
      item = undefined;
      break;
    case 'List':
      // not sure what this one does
      item = undefined;
      break;
    case 'Chart':
    case 'Image':
    case 'Video':
    case 'Webview':
      // LOL! not handled!
      item = undefined;
      break;
    default:
      Util.log('Unknown widget: label: ' + widget.label + ', type!: ' + widget.type);
      item = undefined;
  }
  return item;
}

function toggleSwitch(item, success) {
  Util.log('Toggling switch: ' + item.name);
  var command;
  if (item.state == 'OFF' || item.state == 'Uninitialized' || item.state == 'Undefined' || item.state == 'UNDEF') {
    command = 'ON';
  } else if (item.state == 'ON') {
    command = 'OFF';
  } else if (item.type == 'Color' && item.state && item.state.split(',').length == 3) {
    // handle openHAB 2 hue lights color channels defined as switches in the sitemap
    command = (parseInt(item.state.split(',')[2]) > 0) ? 'OFF' : 'ON';
  }
  if (command) {
    Item.sendCommand(item, command, success);
  }
}

function createPageMenu(data, resetSitemap) {
  var sections = [];
  var widgets = Util.arrayize(data.widget ? data.widget : data.widgets);
  for (var idx in widgets) {
    var widget = widgets[idx];
    switch (widget.type) {
      case 'Frame':
        var items = [];
        var subwidgets = Util.arrayize(widget.widget ? widget.widget : widget.widgets);
        // add all the subwidgets of the frame to an item list
        for (var idx2 in subwidgets) {
          var subwidget = subwidgets[idx2];
          items.push(createItem(subwidget));
        }
        // push the frame section
        sections.push({
          backgroundColor: Config.menuSectionBackgroundColor,
		      textColor: Config.menuSectionTextColor,
          title: widget.label,
          items: items
        });
        break;
      default:
        // not a frame, just a regular item
        var item = createItem(widget);
        if (item) {
          sections.push({
            items: [ item ]
          });
        }
    }
  }
  var menu = new UI.Menu({
    status: {
      color: Config.statusTextColor,
      backgroundColor: Config.statusBackgroundColor
    },
    textColor: Config.menuTextColor,
    backgroundColor: Config.menuBackgroundColor,
    highlightTextColor: Config.menuHighlightTextColor,
    highlightBackgroundColor: Config.menuHighlightBackgroundColor,
    sections: sections
  });
  menu.on('select', function(e) {
    Util.log('item selected: ' + e.item.title + ', section: ' + e.sectionIndex + ', index: ' + e.itemIndex);
    var widget = widgets[e.sectionIndex];
    Util.log('widget: ' + JSON.stringify(widget));
    if (widget.type == 'Frame') {
      var subwidgets = Util.arrayize(widget.widget ? widget.widget : widget.widgets);
      widget = subwidgets[e.itemIndex];
      Util.log('subwidget: ' + JSON.stringify(widget));
    }
    if ('linkedPage' in widget) {
      // go to the subpage for this widget
      exports.load(widget.linkedPage.link, resetSitemap);
    } else {
      var regenerateItem = function() {
        // regenerate the item
        var newItem = createItem(widget);
        if (newItem) {
          menu.item(e.sectionIndex, e.itemIndex, newItem);
        }
      };
      switch (widget.type) {
        case 'Switch':
          if (widget.item.type.startsWith('Switch') || widget.item.type.startsWith('Group') || widget.item.type.startsWith('Color')) {
            toggleSwitch(widget.item, regenerateItem);
          } else if ('mapping' in widget || 'mappings' in widget) {
            var mappings = Util.arrayize(widget.mapping ? widget.mapping : widget.mappings );
            Mapping.change(e.item.title, widget.item, mappings, regenerateItem);
          } else {
            Util.log('Unsupported switch type: ' + widget.item.type);
          }
          break;
        case 'Selection':
          if ('mapping' in widget || 'mappings' in widget) {
            var mappings2 = Util.arrayize(widget.mapping ? widget.mapping : widget.mappings);
            Mapping.change(e.item.title, widget.item, mappings2, regenerateItem);
          } else {
            // unclear how to support selection without a mapping
            Util.log('Mapping-less Selection unsupported');
          }
          break;
        case 'Slider':
        case 'Setpoint':
          if (widget.item.type.startsWith('Dimmer') || (widget.item.type.startsWith('Group') && !isNumeric(widget.item.state)) || widget.item.type.startsWith('Color')) {
            Setpoint.dimmer(e.item.title, widget.item, regenerateItem);
          } else if (widget.item.type.startsWith('Number') || (widget.item.type.startsWith('Group') && isNumeric(widget.item.state))) {
            Setpoint.number(e.item.title, widget.item, widget.min, widget.max, widget.step, regenerateItem);
          } else {
            Util.log('Unsupported setpoint/slider type: ' + widget.item.type);
          }
          break;
        default:
          Util.log('Unsupported widget type:' + widget.type);
      }
    }
  });
  menu.on('longSelect', function (e) {
    Util.log('Show action menu');
    Actions.load(resetSitemap);
  });
  return menu;
}

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

exports.load = function (url, resetSitemap) {
  Util.log('loading: ' + url);
  ajax(
    {
      url: url,
      type: 'json',
      headers: {
        Accept: 'application/json; charset=utf-8',
        Authorization: Config.auth
      }
    },

    function (data) {
      Util.log('Successfully fetched page: ' + JSON.stringify(data));
      var menu = createPageMenu(data, resetSitemap);
      WindowMgr.push(menu);
    },

    function (error) {
      Util.log('Failed to fetch page: ' + error);
      Util.error('Comm Error', "Can't fetch page");
    }
  );
};
<commit_msg>Replace startsWith() with indexOf() === 0<commit_after>// Copyright 2015 Richard Lee
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// A library to display an OpenHAB sitemap page

var UI = require('ui');
var Util = require('util');
var Config = require('config');
var WindowMgr = require('windowmgr');
var Setpoint = require('setpoint');
var Mapping = require('mapping');
var Actions = require('actions');
var Item = require('item');
var ajax = require('ajax');
/* global module */
var exports = module.exports = {};
var labelRE = new RegExp('(.*?) \\[(.*?)\\]');

function splitLabel(label) {
  if (labelRE.test(label)) {
    var match = labelRE.exec(label);
    return {
      title: match[1],
      subtitle: match[2]
    };
  } else {
    return {
      title: label
    };
  }
}

function createItem(widget) {
  // most items just use the split label
  var item = splitLabel(widget.label);
  switch (widget.type) {
    case 'Group':
    case 'Text':
      // use split label
      break;
    case 'Slider':
    case 'Setpoint':
      // if they provided a split label, use it.  Otherwise...
      if ( !('subtitle' in item)) {
        // fall back on the item state
        item.subtitle = widget.item.state;
      }
      break;
    case 'Switch':
    case 'Selection':
      // if they provided a split label, use it.  Otherwise...
      if ( !('subtitle' in item)) {
        var state = widget.item.state;
        // fall back on the item state, but...
        item.subtitle = state;
        if ('mapping' in widget || 'mappings' in widget) {
          // if there's a mapping, look up the item value label in it
          var mappings = (widget.mappings) ? Util.arrayize(widget.mappings) : Util.arrayize(widget.mapping);
          for (var idx in mappings) {
            var mapping = mappings[idx];
            if (mapping.command == state) {
              item.subtitle = mapping.label;
              break;
            }
          }
        }
      }
      break;
    case 'ColorPicker':
      // not currently handled, but maybe someday? put it in with its type
      item = {
        title: widget.label,
        subtitle: widget.type
      };
      break;
    case 'Frame':
      // Weird... shouldn't this be a linked page?  not supported.
      item = undefined;
      break;
    case 'List':
      // not sure what this one does
      item = undefined;
      break;
    case 'Chart':
    case 'Image':
    case 'Video':
    case 'Webview':
      // LOL! not handled!
      item = undefined;
      break;
    default:
      Util.log('Unknown widget: label: ' + widget.label + ', type!: ' + widget.type);
      item = undefined;
  }
  return item;
}

function toggleSwitch(item, success) {
  Util.log('Toggling switch: ' + item.name);
  var command;
  if (item.state == 'OFF' || item.state == 'Uninitialized' || item.state == 'Undefined' || item.state == 'UNDEF') {
    command = 'ON';
  } else if (item.state == 'ON') {
    command = 'OFF';
  } else if (item.type == 'Color' && item.state && item.state.split(',').length == 3) {
    // handle openHAB 2 hue lights color channels defined as switches in the sitemap
    command = (parseInt(item.state.split(',')[2]) > 0) ? 'OFF' : 'ON';
  }
  if (command) {
    Item.sendCommand(item, command, success);
  }
}

function createPageMenu(data, resetSitemap) {
  var sections = [];
  var widgets = Util.arrayize(data.widget ? data.widget : data.widgets);
  for (var idx in widgets) {
    var widget = widgets[idx];
    switch (widget.type) {
      case 'Frame':
        var items = [];
        var subwidgets = Util.arrayize(widget.widget ? widget.widget : widget.widgets);
        // add all the subwidgets of the frame to an item list
        for (var idx2 in subwidgets) {
          var subwidget = subwidgets[idx2];
          items.push(createItem(subwidget));
        }
        // push the frame section
        sections.push({
          backgroundColor: Config.menuSectionBackgroundColor,
		      textColor: Config.menuSectionTextColor,
          title: widget.label,
          items: items
        });
        break;
      default:
        // not a frame, just a regular item
        var item = createItem(widget);
        if (item) {
          sections.push({
            items: [ item ]
          });
        }
    }
  }
  var menu = new UI.Menu({
    status: {
      color: Config.statusTextColor,
      backgroundColor: Config.statusBackgroundColor
    },
    textColor: Config.menuTextColor,
    backgroundColor: Config.menuBackgroundColor,
    highlightTextColor: Config.menuHighlightTextColor,
    highlightBackgroundColor: Config.menuHighlightBackgroundColor,
    sections: sections
  });
  menu.on('select', function(e) {
    Util.log('item selected: ' + e.item.title + ', section: ' + e.sectionIndex + ', index: ' + e.itemIndex);
    var widget = widgets[e.sectionIndex];
    Util.log('widget: ' + JSON.stringify(widget));
    if (widget.type == 'Frame') {
      var subwidgets = Util.arrayize(widget.widget ? widget.widget : widget.widgets);
      widget = subwidgets[e.itemIndex];
      Util.log('subwidget: ' + JSON.stringify(widget));
    }
    if ('linkedPage' in widget) {
      // go to the subpage for this widget
      exports.load(widget.linkedPage.link, resetSitemap);
    } else {
      var regenerateItem = function() {
        // regenerate the item
        var newItem = createItem(widget);
        if (newItem) {
          menu.item(e.sectionIndex, e.itemIndex, newItem);
        }
      };
      switch (widget.type) {
        case 'Switch':
          if (widget.item.type.indexOf('Switch') === 0 || widget.item.type.indexOf('Group') === 0 || widget.item.type.indexOf('Color') === 0) {
            toggleSwitch(widget.item, regenerateItem);
          } else if ('mapping' in widget || 'mappings' in widget) {
            var mappings = Util.arrayize(widget.mapping ? widget.mapping : widget.mappings );
            Mapping.change(e.item.title, widget.item, mappings, regenerateItem);
          } else {
            Util.log('Unsupported switch type: ' + widget.item.type);
          }
          break;
        case 'Selection':
          if ('mapping' in widget || 'mappings' in widget) {
            var mappings2 = Util.arrayize(widget.mapping ? widget.mapping : widget.mappings);
            Mapping.change(e.item.title, widget.item, mappings2, regenerateItem);
          } else {
            // unclear how to support selection without a mapping
            Util.log('Mapping-less Selection unsupported');
          }
          break;
        case 'Slider':
        case 'Setpoint':
          if (widget.item.type.indexOf('Dimmer') === 0 || (widget.item.type.indexOf('Group') === 0 && !isNumeric(widget.item.state)) || widget.item.type.indexOf('Color') === 0) {
            Setpoint.dimmer(e.item.title, widget.item, regenerateItem);
          } else if (widget.item.type.indexOf('Number') === 0 || (widget.item.type.indexOf('Group') === 0 && isNumeric(widget.item.state))) {
            Setpoint.number(e.item.title, widget.item, widget.min, widget.max, widget.step, regenerateItem);
          } else {
            Util.log('Unsupported setpoint/slider type: ' + widget.item.type);
          }
          break;
        default:
          Util.log('Unsupported widget type:' + widget.type);
      }
    }
  });
  menu.on('longSelect', function (e) {
    Util.log('Show action menu');
    Actions.load(resetSitemap);
  });
  return menu;
}

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

exports.load = function (url, resetSitemap) {
  Util.log('loading: ' + url);
  ajax(
    {
      url: url,
      type: 'json',
      headers: {
        Accept: 'application/json; charset=utf-8',
        Authorization: Config.auth
      }
    },

    function (data) {
      Util.log('Successfully fetched page: ' + JSON.stringify(data));
      var menu = createPageMenu(data, resetSitemap);
      WindowMgr.push(menu);
    },

    function (error) {
      Util.log('Failed to fetch page: ' + error);
      Util.error('Comm Error', "Can't fetch page");
    }
  );
};
<|endoftext|>


<commit_before>import _ from 'lodash'

function request() {
  return function() {
    throw new Error('rest.map.req is not implemented')
  }
}

function response(map, spec = {}) {
  const {expand} = spec

  function mapFields(document, map, expand) {
    const doc = {}

    if (_.isFunction(document.toObject)) {
      document = document.toObject()
    }

    _.forEach(document, function(val, key) {
      key = map[key] || key
      doc[key] = val
    })

    // expand
    _.forEach(expand, function(map, path) {
      if (_.isArray(doc[path])) {
        doc[path] = _.map(doc[path], function(document) {
          return mapFields(document, map)
        })
        return
      }

      if (_.isObject(doc[path])) {
        doc[path] = mapFields(doc[path], map)
      }
    })

    return doc
  }

  return function(req, res) {
    let queryExpand
    // property expansion
    if (_.isString(req.query.expand)) {
      queryExpand = req.query.expand.split(',')
    }
    let expandedPaths = _.pick(expand, queryExpand)

    if (_.isArray(res.body)) {
      res.body = _.map(res.body, function(document) {
        return mapFields(document, map, expandedPaths)
      })
      return
    }

    if (_.isObject(res.body)) {
      res.body = mapFields(res.body, map, expandedPaths)
    }
  }

}

export default Object.freeze({
  req: request,
  res: response
})
<commit_msg>feat: add mapping for request body<commit_after>import _ from 'lodash'

function request() {
  const {expand} = spec

  function mapFields(document, map, expand) {
    const doc = {}

    if (_.isFunction(document.toObject)) {
      document = document.toObject()
    }

    _.forEach(document, function(val, key) {
      key = map[key] || key
      doc[key] = val
    })

    // expand
    _.forEach(expand, function(map, path) {
      if (_.isArray(doc[path])) {
        doc[path] = _.map(doc[path], function(document) {
          return mapFields(document, map)
        })
        return
      }

      if (_.isObject(doc[path])) {
        doc[path] = mapFields(doc[path], map)
      }
    })

    return doc
  }

  return function(req, res) {
    let queryExpand
    // property expansion
    if (_.isString(req.query.expand)) {
      queryExpand = req.query.expand.split(',')
    }
    let expandedPaths = _.pick(expand, queryExpand)

    if (_.isArray(req.body)) {
      req.body = _.map(req.body, function(document) {
        return mapFields(document, map, expandedPaths)
      })
      return
    }

    if (_.isObject(req.body)) {
      req.body = mapFields(req.body, map, expandedPaths)
    }
  }
}

function response(map, spec = {}) {
  const {expand} = spec

  function mapFields(document, map, expand) {
    const doc = {}

    if (_.isFunction(document.toObject)) {
      document = document.toObject()
    }

    _.forEach(document, function(val, key) {
      key = map[key] || key
      doc[key] = val
    })

    // expand
    _.forEach(expand, function(map, path) {
      if (_.isArray(doc[path])) {
        doc[path] = _.map(doc[path], function(document) {
          return mapFields(document, map)
        })
        return
      }

      if (_.isObject(doc[path])) {
        doc[path] = mapFields(doc[path], map)
      }
    })

    return doc
  }

  return function(req, res) {
    let queryExpand
    // property expansion
    if (_.isString(req.query.expand)) {
      queryExpand = req.query.expand.split(',')
    }
    let expandedPaths = _.pick(expand, queryExpand)

    if (_.isArray(res.body)) {
      res.body = _.map(res.body, function(document) {
        return mapFields(document, map, expandedPaths)
      })
      return
    }

    if (_.isObject(res.body)) {
      res.body = mapFields(res.body, map, expandedPaths)
    }
  }

}

export default Object.freeze({
  req: request,
  res: response
})
<|endoftext|>


<commit_before>/* ===============================================================================
************   Tabs   ************
=============================================================================== */
app.showTab = function (tab, tabLink) {
    var newTab = $(tab);
    if (newTab.hasClass('active')) return false;
    if (newTab.length === 0) return false;
    var tabs = newTab.parent('.tabs');
    if (tabs.length === 0) return false;

    // Return swipeouts in hidden tabs
    app.allowSwipeout = true;

    // Animated tabs
    var isAnimatedTabs = tabs.parent().hasClass('tabs-animated-wrap');
    if (isAnimatedTabs) {
        tabs.transform('translate3d(' + -newTab.index() * 100 + '%,0,0)');
    }

    // Remove active class from old tabs
    var oldTab = tabs.children('.tab.active').removeClass('active');
    // Add active class to new tab
    newTab.addClass('active');
    // Trigger 'show' event on new tab
    newTab.trigger('show');

    // Update navbars in new tab
    if (!isAnimatedTabs && newTab.find('.navbar').length > 0) {
        // Find tab's view
        var viewContainer;
        if (newTab.hasClass(app.params.viewClass)) viewContainer = newTab[0];
        else viewContainer = newTab.parents('.' + app.params.viewClass)[0];
        app.sizeNavbars(viewContainer);
    }

    // Find related link for new tab
    if (tabLink) tabLink = $(tabLink);
    else {
        // Search by id
        if (typeof tab === 'string') tabLink = $('.tab-link[href="' + tab + '"]');
        else tabLink = $('.tab-link[href="#' + newTab.attr('id') + '"]');
        // Search by data-tab
        if (!tabLink || tabLink && tabLink.length === 0) {
            $('[data-tab]').each(function () {
                if (newTab.is($(this).attr('data-tab'))) tabLink = $(this);
            });
        }
    }
    if (tabLink.length === 0) return;

    // Find related link for old tab
    var oldTabLink;
    if (oldTab && oldTab.length > 0) {
        // Search by id
        var oldTabId = oldTab.attr('id');
        if (oldTabId) oldTabLink = $('.tab-link[href="#' + oldTabId + '"]');
        // Search by data-tab
        if (!oldTabLink || oldTabLink && oldTabLink.length === 0) {
            $('[data-tab]').each(function () {
                if (oldTab.is($(this).attr('data-tab'))) oldTabLink = $(this);
            });
        }
    }

    // Update links' classes
    if (tabLink && tabLink.length > 0) tabLink.addClass('active');
    if (oldTabLink && oldTabLink.length > 0) oldTabLink.removeClass('active');

    return true;
};<commit_msg>"force" arg to to trigger "show" event<commit_after>/* ===============================================================================
************   Tabs   ************
=============================================================================== */
app.showTab = function (tab, tabLink, force) {
    var newTab = $(tab);
    if (arguments.length === 2) {
        if (typeof tabLink === 'boolean') {
            force = tabLink;
        }
    }
    if (newTab.length === 0) return false;
    if (newTab.hasClass('active')) {
        if (force) newTab.trigger('show');
        return false;
    }
    var tabs = newTab.parent('.tabs');
    if (tabs.length === 0) return false;

    // Return swipeouts in hidden tabs
    app.allowSwipeout = true;

    // Animated tabs
    var isAnimatedTabs = tabs.parent().hasClass('tabs-animated-wrap');
    if (isAnimatedTabs) {
        tabs.transform('translate3d(' + -newTab.index() * 100 + '%,0,0)');
    }

    // Remove active class from old tabs
    var oldTab = tabs.children('.tab.active').removeClass('active');
    // Add active class to new tab
    newTab.addClass('active');
    // Trigger 'show' event on new tab
    newTab.trigger('show');

    // Update navbars in new tab
    if (!isAnimatedTabs && newTab.find('.navbar').length > 0) {
        // Find tab's view
        var viewContainer;
        if (newTab.hasClass(app.params.viewClass)) viewContainer = newTab[0];
        else viewContainer = newTab.parents('.' + app.params.viewClass)[0];
        app.sizeNavbars(viewContainer);
    }

    // Find related link for new tab
    if (tabLink) tabLink = $(tabLink);
    else {
        // Search by id
        if (typeof tab === 'string') tabLink = $('.tab-link[href="' + tab + '"]');
        else tabLink = $('.tab-link[href="#' + newTab.attr('id') + '"]');
        // Search by data-tab
        if (!tabLink || tabLink && tabLink.length === 0) {
            $('[data-tab]').each(function () {
                if (newTab.is($(this).attr('data-tab'))) tabLink = $(this);
            });
        }
    }
    if (tabLink.length === 0) return;

    // Find related link for old tab
    var oldTabLink;
    if (oldTab && oldTab.length > 0) {
        // Search by id
        var oldTabId = oldTab.attr('id');
        if (oldTabId) oldTabLink = $('.tab-link[href="#' + oldTabId + '"]');
        // Search by data-tab
        if (!oldTabLink || oldTabLink && oldTabLink.length === 0) {
            $('[data-tab]').each(function () {
                if (oldTab.is($(this).attr('data-tab'))) oldTabLink = $(this);
            });
        }
    }

    // Update links' classes
    if (tabLink && tabLink.length > 0) tabLink.addClass('active');
    if (oldTabLink && oldTabLink.length > 0) oldTabLink.removeClass('active');

    return true;
};<|endoftext|>


<commit_before>var path = require('path'),
    helpers = require('yeoman-generator').test,
    rimraf = require('rimraf');

describe('prototyping generator', function() {

  var temp = path.join(__dirname, 'temp');

  beforeEach(function(done) {
    helpers.testDirectory(temp, function(err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('prototyping:app', [
        '../../app'
      ]);

      done();
    }.bind(this));
  });

  afterEach(function(done) {
    rimraf(temp, function(err) {
      done(err);
    });
  });

  it('create expected files', function(done) {
    // cancel npm install
    this.app.removeAllListeners('end');
    this.app.run({}, function() {
      helpers.assertFiles([
        'package.json',
        'bower.json',
        'Gruntfile.coffee',
        'js/index.js',
        'jade/index.jade',
        'stylus/index.stylus',
        'coffee/index.coffee'
      ]);
      done();
    });
  });

});
<commit_msg>fixed test<commit_after>var path = require('path'),
    helpers = require('yeoman-generator').test,
    rimraf = require('rimraf');

describe('prototyping generator', function() {

  var temp = path.join(__dirname, 'temp');

  beforeEach(function(done) {
    helpers.testDirectory(temp, function(err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('prototyping:app', [
        '../../app'
      ]);

      done();
    }.bind(this));
  });

  afterEach(function(done) {
    rimraf(temp, function(err) {
      done(err);
    });
  });

  it('create expected files', function(done) {
    // cancel npm install
    this.app.removeAllListeners('end');
    this.app.run({}, function() {
      helpers.assertFiles([
        'package.json',
        'bower.json',
        'Gruntfile.coffee',
        'jade/index.jade'
      ]);
      done();
    });
  });

});
<|endoftext|>


<commit_before>var sample_xform = require('./sample_xform');
var vumigo = require('vumigo_v02');
var basic_auth = vumigo.utils.basic_auth;

module.exports = function() {
    return [
        {
            request: {
                method: "GET",
                url: "http://www.example.org/xform00",
            },
            response: {
                code: "200",
                data: sample_xform,
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.example.org/xform00",
                headers: {
                    Authorization: basic_auth('testuser', 'testpass')
                },
            },
            response: {
                code: "200",
                data: sample_xform,
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.example.org/xform01",
            },
            response: {
                code: "500",
                data: 'Server error',
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.example.org/xform01",
                headers: {
                    Authorization: basic_auth('testuser', 'testpass')
                },
            },
            response: {
                code: "500",
                data: 'Server error',
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.xforms.org/forms",
                headers: {
                    "Content-Type": "application/xml"
                },
                data: sample_xform,
            },
            response: {
                code: "201",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "message": "Created XForm.",
                    "status": 201,
                    "id": "cc46192a-8aba-43f3-9d4e-8b78486346dc"
                },
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.xforms.org/responses/cc46192a-8aba-43f3-9d4e-8b78486346dc/0",
            },
            response: {
                code: "200",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "message": "Question retrieved successfully.",
                    "status": 200,
                    "question": "What is your name?",
                    "id": "cc46192a-8aba-43f3-9d4e-8b78486346dc"
                },
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.xforms.org/responses/cc46192a-8aba-43f3-9d4e-8b78486346dc",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    answer: "Jon Snow",
                },
            },
            response: {
                code: "200",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "id":"cc46192a-8aba-43f3-9d4e-8b78486346dc",
                    "question":"What is your age?",
                    "status":200,
                    "message":"Question completed."
                },
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.xforms.org/responses/cc46192a-8aba-43f3-9d4e-8b78486346dc",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    answer: "20",
                },
            },
            response: {
                code: "200",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "message": "XForm completed.",
                    "status": 200,
                    "id": "cc46192a-8aba-43f3-9d4e-8b78486346dc"
                },
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.xforms.org/answers/cc46192a-8aba-43f3-9d4e-8b78486346dc",
            },
            response: {
                code: "200",
                headers: {
                    "Content-Type": "application/xml",
                },
                data: "<?xml version='1.0' ?><test id=\"test\" version=\"201505270916\"><formhub><uuid /></formhub><name>Jon Snow</name><age>20</age><meta><instanceID /></meta></test>",
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.badxforms.org/forms",
                headers: {
                    "Content-Type": "application/xml"
                },
                data: sample_xform,
            },
            response: {
                code: "400",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "status": 400,
                    "message": "An error occurred while attempting to save the provided XForm. Please ensure the XML you provided is well-formed and valid.",
                },
            },
        },
    ];
};
<commit_msg>Add fixtures for good and bad result POST urls<commit_after>var sample_xform = require('./sample_xform');
var vumigo = require('vumigo_v02');
var basic_auth = vumigo.utils.basic_auth;

module.exports = function() {
    return [
        {
            request: {
                method: "GET",
                url: "http://www.example.org/xform00",
            },
            response: {
                code: "200",
                data: sample_xform,
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.example.org/xform00",
                headers: {
                    Authorization: basic_auth('testuser', 'testpass')
                },
            },
            response: {
                code: "200",
                data: sample_xform,
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.example.org/xform01",
            },
            response: {
                code: "500",
                data: 'Server error',
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.example.org/xform01",
                headers: {
                    Authorization: basic_auth('testuser', 'testpass')
                },
            },
            response: {
                code: "500",
                data: 'Server error',
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.xforms.org/forms",
                headers: {
                    "Content-Type": "application/xml"
                },
                data: sample_xform,
            },
            response: {
                code: "201",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "message": "Created XForm.",
                    "status": 201,
                    "id": "cc46192a-8aba-43f3-9d4e-8b78486346dc"
                },
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.xforms.org/responses/cc46192a-8aba-43f3-9d4e-8b78486346dc/0",
            },
            response: {
                code: "200",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "message": "Question retrieved successfully.",
                    "status": 200,
                    "question": "What is your name?",
                    "id": "cc46192a-8aba-43f3-9d4e-8b78486346dc"
                },
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.xforms.org/responses/cc46192a-8aba-43f3-9d4e-8b78486346dc",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    answer: "Jon Snow",
                },
            },
            response: {
                code: "200",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "id":"cc46192a-8aba-43f3-9d4e-8b78486346dc",
                    "question":"What is your age?",
                    "status":200,
                    "message":"Question completed."
                },
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.xforms.org/responses/cc46192a-8aba-43f3-9d4e-8b78486346dc",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    answer: "20",
                },
            },
            response: {
                code: "200",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "message": "XForm completed.",
                    "status": 200,
                    "id": "cc46192a-8aba-43f3-9d4e-8b78486346dc"
                },
            },
        },
        {
            request: {
                method: "GET",
                url: "http://www.xforms.org/answers/cc46192a-8aba-43f3-9d4e-8b78486346dc",
            },
            response: {
                code: "200",
                headers: {
                    "Content-Type": "application/xml",
                },
                data: "<?xml version='1.0' ?><test id=\"test\" version=\"201505270916\"><formhub><uuid /></formhub><name>Jon Snow</name><age>20</age><meta><instanceID /></meta></test>",
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.badxforms.org/forms",
                headers: {
                    "Content-Type": "application/xml"
                },
                data: sample_xform,
            },
            response: {
                code: "400",
                headers: {
                    "Content-Type": "application/json",
                },
                data: {
                    "status": 400,
                    "message": "An error occurred while attempting to save the provided XForm. Please ensure the XML you provided is well-formed and valid.",
                },
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.testanswers.org",
                headers: {
                    "Content-Type": "application/xml"
                },
                data: "<?xml version='1.0' ?><test id=\"test\" version=\"201505270916\"><formhub><uuid /></formhub><name>Jon Snow</name><age>20</age><meta><instanceID /></meta></test>",
            },
            response: {
                code: "200",
            },
        },
        {
            request: {
                method: "POST",
                url: "http://www.badtestanswers.org",
                headers: {
                    "Content-Type": "application/xml"
                },
                data: "<?xml version='1.0' ?><test id=\"test\" version=\"201505270916\"><formhub><uuid /></formhub><name>Jon Snow</name><age>20</age><meta><instanceID /></meta></test>",
            },
            response: {
                code: "400",
            },
        },
    ];
};
<|endoftext|>


<commit_before>"use strict";

var puckt = puckt || {};
puckt.util = (function () {
    // Convert pixels to representive metres
    var pixelsToMetres = function (pixels) {
        return pixels / puckt.pxpm;
    },
    metresToPixels = function (metres) {
        return metres * puckt.pxpm;
    },
    degreesToRadians = function (deg) {
        return deg * (Math.PI / 180); // To do: cache this value
    },
    radiansToDegrees = function (rad) {
        return rad * (180 / Math.PI); // To do: cache this value
    },
    clamp = function (min, max, x) {
        return Math.min(Math.max(x, min), max);
    },
    // Takes pixel x-axis, y-axis, width, & height and returns a b2Vect2 object
    dimTob2Vec2 = function (props) {
        return new box2d.b2Vec2(pixelsToMetres(props.x), pixelsToMetres(props.y));
    },
    // Takes a distance in pixels, and an array of times, converts pixels to
    // metres, and calculates the time period covered
    calcVelocity = function (distances, timestamps) {
        var distance = pixelsToMetres(distances[distances.length-1]-distances[0]),
            time = findDiff(timestamps[0], timestamps[timestamps.length-1]);
        return distance / (time * 0.001);
    },
    // Set the width and height of an HTML canvas element
    setCanvasSize = function (canvas, width, height) {
        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);
    },
    // Extend an object with more properties, overwriting exiting ones
    extendObject = function (original, newProps) {
        for (var prop in newProps) {
            original[prop] = newProps[prop];
        }
    },
    // Flushes out all the shit you got
    resetWorld = function (world) {
        var body = world.GetBodyList();
        while (body !== null) {
            world.DestroyBody(body);
            body = body.GetNext();
        }
        stage.removeAllChildren();
    };
    return {
        pixelsToMetres: pixelsToMetres,
        metresToPixels: metresToPixels,
        degreesToRadians: degreesToRadians,
        radiansToDegrees: radiansToDegrees,
        clamp: clamp,
        dimTob2Vec2: dimTob2Vec2,
        calcVelocity: calcVelocity,
        setCanvasSize: setCanvasSize,
        extendObject: extendObject,
        resetWorld: resetWorld
    }
}());<commit_msg>Revert "Removed old until function findDiff"<commit_after>"use strict";

var puckt = puckt || {};
puckt.util = (function () {
    // Convert pixels to representive metres
    var pixelsToMetres = function (pixels) {
        return pixels / puckt.pxpm;
    },
    metresToPixels = function (metres) {
        return metres * puckt.pxpm;
    },
    degreesToRadians = function (deg) {
        return deg * (Math.PI / 180); // To do: cache this value
    },
    radiansToDegrees = function (rad) {
        return rad * (180 / Math.PI); // To do: cache this value
    },
    clamp = function (min, max, x) {
        return Math.min(Math.max(x, min), max);
    },
    // A helper function to find the difference between two numbers
    findDiff = function (num1, num2) {
        return (num1 > num2) ? num1 - num2 : num2 - num1;
    },
    // Takes pixel x-axis, y-axis, width, & height and returns a b2Vect2 object
    dimTob2Vec2 = function (props) {
        return new box2d.b2Vec2(pixelsToMetres(props.x), pixelsToMetres(props.y));
    },
    // Takes a distance in pixels, and an array of times, converts pixels to
    // metres, and calculates the time period covered
    calcVelocity = function (distances, timestamps) {
        var distance = pixelsToMetres(distances[distances.length-1]-distances[0]),
            time = findDiff(timestamps[0], timestamps[timestamps.length-1]);
        return distance / (time * 0.001);
    },
    // Set the width and height of an HTML canvas element
    setCanvasSize = function (canvas, width, height) {
        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);
    },
    // Extend an object with more properties, overwriting exiting ones
    extendObject = function (original, newProps) {
        for (var prop in newProps) {
            original[prop] = newProps[prop];
        }
    },
    // Flushes out all the shit you got
    resetWorld = function (world) {
        var body = world.GetBodyList();
        while (body !== null) {
            world.DestroyBody(body);
            body = body.GetNext();
        }
        stage.removeAllChildren();
    };
    return {
        pixelsToMetres: pixelsToMetres,
        metresToPixels: metresToPixels,
        degreesToRadians: degreesToRadians,
        radiansToDegrees: radiansToDegrees,
        clamp: clamp,
        findDiff: findDiff,
        dimTob2Vec2: dimTob2Vec2,
        calcVelocity: calcVelocity,
        setCanvasSize: setCanvasSize,
        extendObject: extendObject,
        resetWorld: resetWorld
    }
}());<|endoftext|>


<commit_before>// api:

function create_api_error(err_code, err_data, err_message) {
    return {
        error: err_code || 'internal:unknown',
        data: err_data || '',
        message: err_message || ''
    };
}

var api = {
    not_allowed: function(err_message) {
        return create_api_error('permission:notallowed', '', err_message);
    },
    not_found: function(err_data, err_message) {
        return create_api_error('resource:notfound', err_data, err_message);
    },
    server_error: function(err_code, err_data, err_message) {
        if (err_code instanceof Error) {
            return create_api_error('', err_code.message, err_code.stack);
        }
        if (err_code && err_code.error) {
            return err_code;
        }
        return create_api_error(err_code, err_data, err_message);
    }
}

exports = module.exports = api;
<commit_msg>refactor api error<commit_after>// api:

function create_api_error(err_code, err_data, err_message) {
    return {
        error: err_code || 'internal:unknown',
        data: err_data || '',
        message: err_message || ''
    };
}

var api = {
    invalid_param: function(paramName) {
        return create_api_error('param:invalid', paramName, 'Invalid parameter: ' + paramName);
    },
    not_allowed: function(err_message) {
        return create_api_error('permission:notallowed', '', err_message);
    },
    not_found: function(err_data, err_message) {
        return create_api_error('resource:notfound', err_data, err_message);
    },
    server_error: function(err_code, err_data, err_message) {
        if (err_code instanceof Error) {
            return create_api_error('', err_code.message, err_code.stack);
        }
        if (err_code && err_code.error) {
            return err_code;
        }
        return create_api_error(err_code, err_data, err_message);
    },
    error: function(err_code, err_data, err_message) {
        if (err_code instanceof Error) {
            return create_api_error('', err_code.message, err_code.stack);
        }
        if (err_code && err_code.error) {
            return err_code;
        }
        return create_api_error(err_code, err_data, err_message);
    }
}

exports = module.exports = api;
<|endoftext|>


<commit_before>var AlchemyAPI = require('alchemy-api');
var alchemy = new AlchemyAPI('5e0a4198d583aabe8a39557d240670120974a254');
alchemy.keywords('Glucose is comprised of 6 carbons, 12 hydrogens, and 6 oxygens.', {}, function(err, response) {
    if (err) throw err;

    // See http://www.alchemyapi.com/api/keyword/htmlc.html for format of returned object
    var keywords = response.keywords;
    console.log(keywords[0]);
    // Do something with data
});<commit_msg>fetching of keywords working<commit_after>var AlchemyAPI = require('alchemy-api');
var alchemy = new AlchemyAPI('5e0a4198d583aabe8a39557d240670120974a254');
alchemy.keywords('Glucose is comprised of 6 carbons, 12 hydrogens, and 6 oxygens.', {}, function(err, response) {
    if (err) throw err;

    // See http://www.alchemyapi.com/api/keyword/htmlc.html for format of returned object
    var keywords = response.keywords;
    console.log(keywords[1].text);
    // Do something with data
});<|endoftext|>


<commit_before>/**
 * Utility functions
 */

let _ = require('lodash');

String.prototype.capitalize = function () {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

Array.prototype.pushArray = function (arr) {
  this.push.apply(this, arr);
};

var ONE_HOUR_IN_MS = 3600000;
var ONE_MINUTE_IN_MS = 60000;
var ONE_SECOND_IN_MS = 1000;

export function nanosToReadableUnit (nanos) {
  var msNum = nanos / 1000000;

  if (msNum < ONE_SECOND_IN_MS) {
    return Math.floor(msNum) + "ms";
  }

  if (msNum < ONE_MINUTE_IN_MS) {
    return parseFloat(msNum / 1000).toFixed(3) + "s";
  }

  var hours = Math.floor(msNum / ONE_HOUR_IN_MS);
  var mins = Math.floor((msNum - (hours * ONE_HOUR_IN_MS)) / ONE_MINUTE_IN_MS);
  var secs = Math.floor((msNum - (hours * ONE_HOUR_IN_MS + mins * ONE_MINUTE_IN_MS)) / ONE_SECOND_IN_MS);
  var ms = Math.floor(ms);

  var time = secs;
  var unit = "min";

  if (mins > 0) {
    if (secs < 10) {
      secs = "0" + secs;
    }
    time = mins + ":" + secs;
  }

  if (hours > 0) {
    if (mins < 10) {
      mins = "0" + mins;
    }
    time = hours + ":" + mins;
    unit = "h";
  }
  return time + unit;
}

export function undefinedOrEmpty (array) {
  return !array || array.length === 0;
}

export function getWordValue(word) {
  return word.argumentInfo ? word.argumentInfo.formattedValue : word.value
}

export function getTagName (tag) {
  return tag.name ? tag.name : tag.type;
}

export function getTagId (tag) {
  return tag.fullType ? tag.fullType : tag.type;
}

export function getTagKey (tag) {
  return getTagId(tag) + (tag.value ? '-' + tag.value : '');
}

export function tagToString (tag) {
  var res = '';

  if (!tag.value || tag.prependType) {
    res = getTagName(tag);
  }

  if (tag.value) {
    if (res) {
      res += '-';
    }
    res += tag.value;
  }

  return res;
}

export function splitClassName (fullQualifiedClassName) {
  var index = fullQualifiedClassName.lastIndexOf('.');
  var className = fullQualifiedClassName.substr(index + 1);
  var packageName = fullQualifiedClassName.substr(0, index);
  return {
    className: className,
    packageName: packageName
  };
}

export function getScenarioId (scenario) {
  return scenario.className + "." + scenario.testMethodName;
}

export function sortByDescription (scenarios) {
  var sortedScenarios = _.forEach(_.sortBy(scenarios, function (x) {
    return x.description.toLowerCase();
  }), function (x) {
    x.expanded = false;
  });

  // directly expand a scenario if it is the only one
  if (sortedScenarios.length === 1) {
    sortedScenarios[0].expanded = true;
  }

  return sortedScenarios;
}

export function getReadableExecutionStatus (status) {
  switch (status) {
    case 'SUCCESS':
      return 'Successful';
    case 'FAILED':
      return 'Failed';
    default:
      return 'Pending';
  }
}

export function ownProperties (obj) {
  var result = [];
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      result.push(p);
    }
  }
  return result;
}

export function deselectAll (options) {
  _.forEach(options, function (option) {
    option.selected = false;
  });
}

// returns a tuple of an Array where index         -> value
//                and an Array where argument name -> value
export function getArgumentInfos(wordArray) {

  var enumArray = [];
  var nameArray = [];

  function isArgument(word) { return !!word.argumentInfo; }
  function updateContainer(nameArr, enumArr, word) {
    nameArr[word.argumentInfo.argumentName] = word.value;
    enumArr.push(word.value);
  }

  _.chain(wordArray)
   .filter(isArgument)
   .forEach(_.curry(updateContainer)(nameArray, enumArray))
   .value();

  return [enumArray, nameArray];
}

export function parseNextInt(arr) {
    var numbers = _.takeWhile(arr, function (c) { return !isNaN(c) && c !== " "; }).join("");
    var parsedInt = parseInt(numbers);
    var result  = { integer : isNaN(parsedInt) ? undefined : parsedInt
                  , length  : numbers.length } ;
    return result;
}

export function parseNextArgumentName(string) {
    var stopChars = [" ", ",", ";", ":","\"","%","!","[","]","(",")","-","_"];
    var isNonStopChar = function (c) { return  _.indexOf(stopChars, c) === -1; };
    return _.takeWhile(string, isNonStopChar).join("");
}

export function replaceArguments(string, enumArray, nameArray) {
    var separator = "$";
    var result    = [];
    var placeHolderCount = 0;

    for(var i = 0; i < string.length; ++i) {
        var c           = string.charAt(i);
        var lookahead   = string.charAt(i+1);
        var isSeparator = c          === separator;
        var escaped     = (lookahead === separator) && isSeparator;
        var argument    = undefined;
        var argumentLen = 0;

        if (isSeparator && !escaped) {
            var substring = _.drop(string, i+1);
            var argName  = parseNextArgumentName(substring);
            var argIndex = parseNextInt(substring);

            // named placeholder '$[argumentname]'
            if (nameArray[argName] !== undefined) {
                argument = nameArray[argName];
                argumentLen = argName.length;
            }
            // normal placeholder '$'
            else if (argIndex.integer === undefined) {
                argument = enumArray[placeHolderCount++];
            }
            // enumerated placeholder '$1, $2..'
            else {
                argument = enumArray[argIndex.integer-1];
                argumentLen = argIndex.length;
            }
        } else if (escaped) {
            argument = separator;
            argumentLen = 1;
        }

        // an argument found
        if (argument !== undefined) {
            result.push(argument);
            i += argumentLen;
        } else {
            result.push(c);
        }
    }
    return result.join("");
}<commit_msg> * refactored _.chain, tried to manage imports<commit_after>/**
 * Utility functions
 */

// let _ = require('lodash');

import forEach from "lodash/fp/forEach";
import curry from "lodash/fp/curry";
import filter from "lodash/fp/filter";
import flow from "lodash/fp/flow";

// this is somehow needed, because functions from "lodash/fp/..." behave
// very differently than from the "_" object
import _ from 'lodash';

String.prototype.capitalize = function () {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

Array.prototype.pushArray = function (arr) {
  this.push.apply(this, arr);
};

var ONE_HOUR_IN_MS = 3600000;
var ONE_MINUTE_IN_MS = 60000;
var ONE_SECOND_IN_MS = 1000;

export function nanosToReadableUnit (nanos) {
  var msNum = nanos / 1000000;

  if (msNum < ONE_SECOND_IN_MS) {
    return Math.floor(msNum) + "ms";
  }

  if (msNum < ONE_MINUTE_IN_MS) {
    return parseFloat(msNum / 1000).toFixed(3) + "s";
  }

  var hours = Math.floor(msNum / ONE_HOUR_IN_MS);
  var mins = Math.floor((msNum - (hours * ONE_HOUR_IN_MS)) / ONE_MINUTE_IN_MS);
  var secs = Math.floor((msNum - (hours * ONE_HOUR_IN_MS + mins * ONE_MINUTE_IN_MS)) / ONE_SECOND_IN_MS);
  var ms = Math.floor(ms);

  var time = secs;
  var unit = "min";

  if (mins > 0) {
    if (secs < 10) {
      secs = "0" + secs;
    }
    time = mins + ":" + secs;
  }

  if (hours > 0) {
    if (mins < 10) {
      mins = "0" + mins;
    }
    time = hours + ":" + mins;
    unit = "h";
  }
  return time + unit;
}

export function undefinedOrEmpty (array) {
  return !array || array.length === 0;
}

export function getWordValue(word) {
  return word.argumentInfo ? word.argumentInfo.formattedValue : word.value
}

export function getTagName (tag) {
  return tag.name ? tag.name : tag.type;
}

export function getTagId (tag) {
  return tag.fullType ? tag.fullType : tag.type;
}

export function getTagKey (tag) {
  return getTagId(tag) + (tag.value ? '-' + tag.value : '');
}

export function tagToString (tag) {
  var res = '';

  if (!tag.value || tag.prependType) {
    res = getTagName(tag);
  }

  if (tag.value) {
    if (res) {
      res += '-';
    }
    res += tag.value;
  }

  return res;
}

export function splitClassName (fullQualifiedClassName) {
  var index = fullQualifiedClassName.lastIndexOf('.');
  var className = fullQualifiedClassName.substr(index + 1);
  var packageName = fullQualifiedClassName.substr(0, index);
  return {
    className: className,
    packageName: packageName
  };
}

export function getScenarioId (scenario) {
  return scenario.className + "." + scenario.testMethodName;
}

export function sortByDescription (scenarios) {
  var sortedScenarios = _.forEach(_.sortBy(scenarios, function (x) {
    return x.description.toLowerCase();
  }), function (x) {
    x.expanded = false;
  });

  // directly expand a scenario if it is the only one
  if (sortedScenarios.length === 1) {
    sortedScenarios[0].expanded = true;
  }

  return sortedScenarios;
}

export function getReadableExecutionStatus (status) {
  switch (status) {
    case 'SUCCESS':
      return 'Successful';
    case 'FAILED':
      return 'Failed';
    default:
      return 'Pending';
  }
}

export function ownProperties (obj) {
  var result = [];
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      result.push(p);
    }
  }
  return result;
}

export function deselectAll (options) {
  _.forEach(options, function (option) {
    option.selected = false;
  });
}

// returns a tuple of an Array where index         -> value
//                and an Array where argument name -> value
export function getArgumentInfos(wordArray) {

  var enumArray = [];
  var nameArray = [];

  function isArgument(word) { return !!word.argumentInfo; }
  function updateContainer(nameArr, enumArr, word) {
    nameArr[word.argumentInfo.argumentName] = word.value;
    enumArr.push(word.value);
  }

  flow(
    filter(isArgument),
    forEach(curry(updateContainer)(nameArray, enumArray))
  )(wordArray);

  return [enumArray, nameArray];
}

export function parseNextInt(arr) {
    var numbers = _.takeWhile(arr, function (c) { return !isNaN(c) && c !== " "; }).join("");
    var parsedInt = parseInt(numbers);
    var result  = { integer : isNaN(parsedInt) ? undefined : parsedInt
                  , length  : numbers.length } ;
    return result;
}

export function parseNextArgumentName(string) {
    var stopChars = [" ", ",", ";", ":","\"","%","!","[","]","(",")","-","_"];
    var isNonStopChar = function (c) { return  _.indexOf(stopChars, c) === -1; };
    return _.takeWhile(string, isNonStopChar).join("");
}

export function replaceArguments(string, enumArray, nameArray) {
    var separator = "$";
    var result = [];
    var placeHolderCount = 0;

    for(var i = 0; i < string.length; ++i) {
        var c = string.charAt(i);
        var lookahead = string.charAt(i+1);
        var isSeparator = c === separator;
        var escaped = (lookahead === separator) && isSeparator;
        var argument = undefined;
        var argumentLen = 0;

        if (isSeparator && !escaped) {
            var substring = _.drop(string, i+1);
            var argName = parseNextArgumentName(substring);
            var argIndex = parseNextInt(substring);

            // named placeholder '$[argumentname]'
            if (nameArray[argName] !== undefined) {
                argument = nameArray[argName];
                argumentLen = argName.length;
            }
            // normal placeholder '$'
            else if (argIndex.integer === undefined) {
                argument = enumArray[placeHolderCount++];
            }
            // enumerated placeholder '$1, $2..'
            else {
                argument = enumArray[argIndex.integer-1];
                argumentLen = argIndex.length;
            }
        } else if (escaped) {
            argument = separator;
            argumentLen = 1;
        }

        // an argument found
        if (argument !== undefined) {
            result.push(argument);
            i += argumentLen;
        } else {
            result.push(c);
        }
    }
    return result.join("");
}<|endoftext|>


<commit_before>var assert = require('assert');
var request = require('superagent-promise');
var debug = require('debug')('papertrail');
var debugResponse = require('debug')('papertrail:response');
var debugRequest = require('debug')('papertrail:request');
var util = require('util');

var DEFAULT_BASE_URL = 'https://papertrailapp.com/api/v1/';

function Response(result) {
  this.result = result.body;
}

function decorateRequest(method) {
  return function() {
    var args = Array.prototype.slice.call(arguments);
    var ctx = this;

    var req = method.apply(ctx, args);
    req.set('X-Papertrail-Token', this.token);
    return req.end().then(function(res) {
      // Handle errors in successful requests...
      if (res.error) {
        var err = new Error(
          'Papertrail api error unexpected status: ' + res.status
        );
        err.status = res.statusCode;
        err.body = res.body;
        debug('request error | %d | %s | %j', err.status, err, err.body);
        throw err;
      }
      debugResponse(
        '%s | %d | %j', req.url, res.statusCode, res.body
      );
      return res.body;
    });
  };
}

function sendRequest(method, req, options) {
  debugRequest(req.url, 'body:', options);
  if (method !== 'get') {
    // for put/post/del we use form.
    req.set('Content-Type', 'application/x-www-form-urlencoded');
    req.send(options);
  } else {
    // for get requests all options are query params.
    req.query(options);
  }
  return req;
}

function api(method, url) {
  return decorateRequest(function(options) {
    var req = request[method](this.baseUrl + url);
    return sendRequest(method, req, options);
  });
}

function apiWithId(method, url) {
  return decorateRequest(function(id, options) {
    assert(id, 'id is required');
    var req = request[method](this.baseUrl + util.format(url, id));
    return sendRequest(method, req, options);
  });
}

/**
@param {Object} options for client.
@param {String} options.token from your papertrail client.
@param {String} [options.baseUrl] baseUrl for the papertrail api.
*/
function Papertrail(options) {
  options = options || {};
  options.token = options.token || process.env.PAPERTRAIL_API_TOKEN;
  options.baseUrl = options.baseUrl || DEFAULT_BASE_URL;

  assert(options, 'You must pass options');
  assert(options.token, 'You must pass a `token` field');
  assert(options.baseUrl, 'You must pass a `baseUrl` field');

  this.token = options.token;
  this.baseUrl = options.baseUrl;
}

Papertrail.prototype = {

  /** event searching */

  /**
  @param {Object} options for search events.
  */
  searchEvents: decorateRequest(function(options) {
    options = options || {};
    if (options.q) options.q = encodeURI(options.q);

    return request.get(this.baseUrl + 'events/search').
            query(options);
  }),

  /** system apis */

  listSystems: api('get', 'systems.json'),
  getSystem: apiWithId('get', 'systems/%s.json'),
  registerSystem: api('post', 'systems.json'),
  updateSystem: apiWithId('put', 'systems/%s.json'),
  deleteSystem: apiWithId('del', 'systems/%s.json'),
  systemJoinGroup: apiWithId('post', 'systems/%s/join.json'),
  systemLeaveGroup: apiWithId('post', 'systems/%s/leave.json'),

  /** save searches */

  savedSearches: api('get', 'searches.json'),
  savedSearch: apiWithId('get', 'searches/%s.json'),
  createSavedSearch: api('post', 'searches.json'),
  updateSavedSearch: apiWithId('put', 'searches/%s.json'),
  deleteSavedSearch: apiWithId('del', 'searches/%s.json'),

  /** manage groups */

  listGroups: api('get', 'groups.json'),
  getGroup: apiWithId('get', 'groups/%s.json'),
  createGroup: api('post', 'groups.json'),
  updateGroup: apiWithId('put', 'groups/%s.json'),
  deleteGroup: apiWithId('del', 'groups/%s.json'),

  /** manage log destinations */

  listLogDestinations: api('get', 'destinations.json'),
  getLogDestination: apiWithId('get', 'destinations/%s.json'),

  /** manage users */

  listUsers: api('get', 'users.json'),
  inviteUser: api('post', 'users/invite.json'),
  deleteUser: apiWithId('del', 'users/%s.json'),

  /** account details */

  getUsage: api('get', 'account.json')
};

module.exports = Papertrail;
<commit_msg>api.js: searchEvents: do not encode query string<commit_after>var assert = require('assert');
var request = require('superagent-promise');
var debug = require('debug')('papertrail');
var debugResponse = require('debug')('papertrail:response');
var debugRequest = require('debug')('papertrail:request');
var util = require('util');

var DEFAULT_BASE_URL = 'https://papertrailapp.com/api/v1/';

function Response(result) {
  this.result = result.body;
}

function decorateRequest(method) {
  return function() {
    var args = Array.prototype.slice.call(arguments);
    var ctx = this;

    var req = method.apply(ctx, args);
    req.set('X-Papertrail-Token', this.token);
    return req.end().then(function(res) {
      // Handle errors in successful requests...
      if (res.error) {
        var err = new Error(
          'Papertrail api error unexpected status: ' + res.status
        );
        err.status = res.statusCode;
        err.body = res.body;
        debug('request error | %d | %s | %j', err.status, err, err.body);
        throw err;
      }
      debugResponse(
        '%s | %d | %j', req.url, res.statusCode, res.body
      );
      return res.body;
    });
  };
}

function sendRequest(method, req, options) {
  debugRequest(req.url, 'body:', options);
  if (method !== 'get') {
    // for put/post/del we use form.
    req.set('Content-Type', 'application/x-www-form-urlencoded');
    req.send(options);
  } else {
    // for get requests all options are query params.
    req.query(options);
  }
  return req;
}

function api(method, url) {
  return decorateRequest(function(options) {
    var req = request[method](this.baseUrl + url);
    return sendRequest(method, req, options);
  });
}

function apiWithId(method, url) {
  return decorateRequest(function(id, options) {
    assert(id, 'id is required');
    var req = request[method](this.baseUrl + util.format(url, id));
    return sendRequest(method, req, options);
  });
}

/**
@param {Object} options for client.
@param {String} options.token from your papertrail client.
@param {String} [options.baseUrl] baseUrl for the papertrail api.
*/
function Papertrail(options) {
  options = options || {};
  options.token = options.token || process.env.PAPERTRAIL_API_TOKEN;
  options.baseUrl = options.baseUrl || DEFAULT_BASE_URL;

  assert(options, 'You must pass options');
  assert(options.token, 'You must pass a `token` field');
  assert(options.baseUrl, 'You must pass a `baseUrl` field');

  this.token = options.token;
  this.baseUrl = options.baseUrl;
}

Papertrail.prototype = {

  /** event searching */

  /**
  @param {Object} options for search events.
  */
  searchEvents: decorateRequest(function(options) {
    options = options || {};

    return request.get(this.baseUrl + 'events/search').
            query(options);
  }),

  /** system apis */

  listSystems: api('get', 'systems.json'),
  getSystem: apiWithId('get', 'systems/%s.json'),
  registerSystem: api('post', 'systems.json'),
  updateSystem: apiWithId('put', 'systems/%s.json'),
  deleteSystem: apiWithId('del', 'systems/%s.json'),
  systemJoinGroup: apiWithId('post', 'systems/%s/join.json'),
  systemLeaveGroup: apiWithId('post', 'systems/%s/leave.json'),

  /** save searches */

  savedSearches: api('get', 'searches.json'),
  savedSearch: apiWithId('get', 'searches/%s.json'),
  createSavedSearch: api('post', 'searches.json'),
  updateSavedSearch: apiWithId('put', 'searches/%s.json'),
  deleteSavedSearch: apiWithId('del', 'searches/%s.json'),

  /** manage groups */

  listGroups: api('get', 'groups.json'),
  getGroup: apiWithId('get', 'groups/%s.json'),
  createGroup: api('post', 'groups.json'),
  updateGroup: apiWithId('put', 'groups/%s.json'),
  deleteGroup: apiWithId('del', 'groups/%s.json'),

  /** manage log destinations */

  listLogDestinations: api('get', 'destinations.json'),
  getLogDestination: apiWithId('get', 'destinations/%s.json'),

  /** manage users */

  listUsers: api('get', 'users.json'),
  inviteUser: api('post', 'users/invite.json'),
  deleteUser: apiWithId('del', 'users/%s.json'),

  /** account details */

  getUsage: api('get', 'account.json')
};

module.exports = Papertrail;
<|endoftext|>