<commit_before>var map_obj;

function limit_download_level_wrapper() {
    _limit_download_level($(this).val(), $(this).parent());
}

function _limit_download_level(source_id, parent) {
    var min_lvl = raster_sources[source_id]['download_level_start'];
    var max_lvl = raster_sources[source_id]['download_level_end'];

    $(parent.find('#start_level > option, #end_level > option')).remove();

    for (i=min_lvl; i <= max_lvl;i++) {
        $(parent.find('#start_level, #end_level'))
         .append($("<option></option>")
            .attr("value",i)
            .text(i)
        );
    }

    parent.find('#start_level option').first().attr('selected', 'selected');
    parent.find('#end_level option').last().attr('selected', 'selected');
}

function add_raster_layer() {
    var last_raster_layer = $('.raster_layer').last();
    var new_layer = raster_layer_template.clone();

    new_layer.find('#raster_source').change(limit_download_level_wrapper).change(show_selected_source);
    new_layer.find('select').change(get_data_volume).change(verify_zoom_level);
    new_layer.find('#remove_layer').click(remove_raster_layer).click(toggle_start_button);

    _limit_download_level(new_layer.find('#raster_source').val(), new_layer);

    if(last_raster_layer.length) {
        new_layer[0].id = 'rl_' + (parseInt(last_raster_layer[0].id.split('_')[1]) + 1);
        last_raster_layer.after(new_layer);
    } else {
        new_layer[0].id = 'rl_1';
        $('#add_layer').before(new_layer);
    }

    set_layer_inputs_by_format_type();
    $('#'+new_layer[0].id+' #raster_source').change();
    new_layer.show();
    return false;
}

function remove_raster_layer() {
    var $this = $(this);
    map_obj.removeLayer($this.parent().find('#raster_source').data('ol_layer'));
    $this.parent().remove();
    return false;
}

function set_layer_inputs_by_format_type() {
    var format = $('#format');
    var value = format.val();
    if( value == 'MBTiles' || value == 'CouchDB' ) {
        $('#srs option[value="EPSG:3857"]').attr('selected', 'selected')
        $('#srs').attr('disabled', 'disabled');
        $('.raster_layer').each(function(idx, elem) {
            $(elem).find('#start_level').prev().text(start_level_text);
            $(elem).find('#end_level').show().prev().show();
        });
    } else {
        $('.raster_layer').each(function(idx, elem) {
            $(elem).find('#start_level').prev().text(level_text);
            $(elem).find('#end_level').hide().prev().hide();
        })
        $('#srs').removeAttr('disabled');
    }

}

function show_selected_source() {
    var source = $(this);
    var id = source.val();

    if(typeof source.data('ol_layer') !== "undefined") {
        map_obj.removeLayer(source.data('ol_layer'));
    }
    layer = raster_sources[id].clone();
    source.data('ol_layer', layer);
    map_obj.addLayer(layer);

    if (draw_layer) {
        map_obj.raiseLayer(draw_layer, map_obj.layers.length +1);
    }
}

function add_remove_vector() {
    $('.vector_source').toggle();
    if($('.vector_source').is(":visible")) {
        $(this).text(remove_vector_text);
        $('.vector_source').children().removeAttr('disabled');
    } else {
        $(this).text(add_vector_text);
        $('.vector_source').children().attr('disabled', 'disabled');
    }
    return false;
}

function set_layer_data(layer_id, source_id, zoom_start, zoom_end) {
    var layer = $('#rl_'+layer_id);
    select_option(layer.find('#raster_source option'), source_id);
    select_option(layer.find('#start_level option'), zoom_start);
    if(zoom_end!=='undefined')
        select_option(layer.find('#end_level option'), zoom_end);
}

function select_option(option_list, value) {
    option_list.each(function(idx, elem) {
        elem = $(elem);
        if(elem.val() == value)
            elem.attr('selected', 'selected');
    })
}

function init() {
    map_obj = init_map();
    draw_layer = activate_draw_controls(map_obj);
    if(coverage) {
        load_features(coverage);
    }
    raster_layer_template = $('#rl_0').clone();
    $('#rl_0').remove()
    $('#format').change(set_layer_inputs_by_format_type).change(verify_zoom_level);
    if($.isEmptyObject(raster_sources)) {
        $('#add_layer').attr('disabled', 'disabled');
    } else {
        $('#add_layer').click(add_raster_layer).click(toggle_start_button);
    }
    $('.raster_layer #remove_layer').click(remove_raster_layer).click(toggle_start_button);
    $('#vector_add_remove').click(add_remove_vector).click(toggle_start_button);
    $('form').submit(submit_data);
    $('.raster_layer #raster_source')
        .change(limit_download_level_wrapper)
        .change(show_selected_source)
        .change();
    $('.raster_layer select').change(get_data_volume).change(verify_zoom_level);

    $('#format, #srs').change(get_data_volume)

    set_layer_inputs_by_format_type();
    $('#start_btn').click(submit_and_start);
    $('#load_couchdb_coverage').click(function() {
        load_coverage_from_project(true)
        return false;
    });

    $('#load_coverage').click(function() {
        load_coverage_from_project(false)
        return false;
    });

};<commit_msg>show correct raster source in map on loading export<commit_after>var map_obj;

function limit_download_level_wrapper() {
    _limit_download_level($(this).val(), $(this).parent());
}

function _limit_download_level(source_id, parent) {
    var min_lvl = raster_sources[source_id]['download_level_start'];
    var max_lvl = raster_sources[source_id]['download_level_end'];

    $(parent.find('#start_level > option, #end_level > option')).remove();

    for (i=min_lvl; i <= max_lvl;i++) {
        $(parent.find('#start_level, #end_level'))
         .append($("<option></option>")
            .attr("value",i)
            .text(i)
        );
    }

    parent.find('#start_level option').first().attr('selected', 'selected');
    parent.find('#end_level option').last().attr('selected', 'selected');
}

function add_raster_layer() {
    var last_raster_layer = $('.raster_layer').last();
    var new_layer = raster_layer_template.clone();

    new_layer.find('#raster_source').change(limit_download_level_wrapper).change(show_selected_source);
    new_layer.find('select').change(get_data_volume).change(verify_zoom_level);
    new_layer.find('#remove_layer').click(remove_raster_layer).click(toggle_start_button);

    _limit_download_level(new_layer.find('#raster_source').val(), new_layer);

    if(last_raster_layer.length) {
        new_layer[0].id = 'rl_' + (parseInt(last_raster_layer[0].id.split('_')[1]) + 1);
        last_raster_layer.after(new_layer);
    } else {
        new_layer[0].id = 'rl_1';
        $('#add_layer').before(new_layer);
    }

    set_layer_inputs_by_format_type();
    $('#'+new_layer[0].id+' #raster_source').change();
    new_layer.show();
    return false;
}

function remove_raster_layer() {
    var $this = $(this);
    map_obj.removeLayer($this.parent().find('#raster_source').data('ol_layer'));
    $this.parent().remove();
    return false;
}

function set_layer_inputs_by_format_type() {
    var format = $('#format');
    var value = format.val();
    if( value == 'MBTiles' || value == 'CouchDB' ) {
        $('#srs option[value="EPSG:3857"]').attr('selected', 'selected')
        $('#srs').attr('disabled', 'disabled');
        $('.raster_layer').each(function(idx, elem) {
            $(elem).find('#start_level').prev().text(start_level_text);
            $(elem).find('#end_level').show().prev().show();
        });
    } else {
        $('.raster_layer').each(function(idx, elem) {
            $(elem).find('#start_level').prev().text(level_text);
            $(elem).find('#end_level').hide().prev().hide();
        })
        $('#srs').removeAttr('disabled');
    }

}

function show_selected_source(layer_id, source_id) {
    var id;
    var source;
    if (source_id) {
        source = $("#rl_"+ layer_id +"> select#raster_source");
        id = source_id;
    } else {
        source = $(this);
        id = source.val();
    }

    if(typeof source.data('ol_layer') !== "undefined") {
        map_obj.removeLayer(source.data('ol_layer'));
    }
    layer = raster_sources[id].clone();
    source.data('ol_layer', layer);
    map_obj.addLayer(layer);
    if (draw_layer) {
        map_obj.raiseLayer(draw_layer, map_obj.layers.length +1);
    }
}

function add_remove_vector() {
    $('.vector_source').toggle();
    if($('.vector_source').is(":visible")) {
        $(this).text(remove_vector_text);
        $('.vector_source').children().removeAttr('disabled');
    } else {
        $(this).text(add_vector_text);
        $('.vector_source').children().attr('disabled', 'disabled');
    }
    return false;
}

function set_layer_data(layer_id, source_id, zoom_start, zoom_end) {
    var layer = $('#rl_'+layer_id);
    select_option(layer.find('#raster_source option'), source_id);
    select_option(layer.find('#start_level option'), zoom_start);
    if(zoom_end!=='undefined')
        select_option(layer.find('#end_level option'), zoom_end);
    show_selected_source(layer_id, source_id)
}

function select_option(option_list, value) {
    option_list.each(function(idx, elem) {
        elem = $(elem);
        if(elem.val() == value)
            elem.attr('selected', 'selected');
    })
}

function init() {
    map_obj = init_map();
    draw_layer = activate_draw_controls(map_obj);
    if(coverage) {
        load_features(coverage);
    }
    raster_layer_template = $('#rl_0').clone();
    $('#rl_0').remove()
    $('#format').change(set_layer_inputs_by_format_type).change(verify_zoom_level);
    if($.isEmptyObject(raster_sources)) {
        $('#add_layer').attr('disabled', 'disabled');
    } else {
        $('#add_layer').click(add_raster_layer).click(toggle_start_button);
    }
    $('.raster_layer #remove_layer').click(remove_raster_layer).click(toggle_start_button);
    $('#vector_add_remove').click(add_remove_vector).click(toggle_start_button);
    $('form').submit(submit_data);
    $('.raster_layer #raster_source')
        .change(limit_download_level_wrapper)
        .change(show_selected_source);
    $('.raster_layer select').change(get_data_volume).change(verify_zoom_level);

    $('#format, #srs').change(get_data_volume)

    set_layer_inputs_by_format_type();
    $('#start_btn').click(submit_and_start);
    $('#load_couchdb_coverage').click(function() {
        load_coverage_from_project(true)
        return false;
    });

    $('#load_coverage').click(function() {
        load_coverage_from_project(false)
        return false;
    });
};<|endoftext|>


<commit_before>const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const ipcMain = electron.ipcMain;
var Menu = electron.Menu;
const path = require('path');
const os = require('os');
const autoUpdater = electron.autoUpdater;
const Menu = electron.Menu;
//electron.crashReporter.start();

var platform = os.platform() + '_' + os.arch();
var version = app.getVersion();

var mainWindow = null;
var procStarted = false;
var subpy = null;
var mainAddr;

try {
  autoUpdater.setFeedURL('https://pokemon-go-updater.mike.ai/update/'+platform+'/'+version);
} catch (e) {}

autoUpdater.on('update-downloaded', function(){
  mainWindow.webContents.send('update-ready');
});

// Setup menu bar
var template = [
  {
    label: "Application",
    submenu: [
        { label: "About Pokémon GO Live Map", selector: "orderFrontStandardAboutPanel:" },
        { type: "separator" },
        { label: "Quit", accelerator: "Command+Q", click: function() { app.quit(); }}
    ]
  },
  {
    label: "Edit",
    submenu: [
        { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
        { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
        { type: "separator" },
        { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
        { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
        { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
        { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
    ]
  },
  {
    label: "Tools",
    submenu: [
      {
        label: "Refresh",
        accelerator: "CmdOrCtrl+R",
        click(item, focusedWindow) {
          if (focusedWindow) focusedWindow.reload();
        }
      },
      {
        label: 'Toggle Developer Tools',
        accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
        click(item, focusedWindow) {
          if (focusedWindow)
            focusedWindow.webContents.toggleDevTools();
        }
      }
    ]
  }
];

app.on('window-all-closed', function() {
  if (subpy && subpy.pid) {
    killProcess(subpy.pid);
  }
  app.quit();
});

app.on('ready', function() {

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  mainWindow = new BrowserWindow({width: 800, height: 600, minWidth: 700, minHeight: 500});
  mainWindow.loadURL('file://' + __dirname + '/login.html');

  var template = [{
      label: "Application",
      submenu: [{
          label: "About Application",
          selector: "orderFrontStandardAboutPanel:"
      }, {
          type: "separator"
      }, {
          label: "Quit",
          accelerator: "Command+Q",
          click: function() {
              app.quit();
          }
      }]
  }, {
      label: "Edit",
      submenu: [{
          label: "Undo",
          accelerator: "CmdOrCtrl+Z",
          selector: "undo:"
      }, {
          label: "Redo",
          accelerator: "Shift+CmdOrCtrl+Z",
          selector: "redo:"
      }, {
          type: "separator"
      }, {
          label: "Cut",
          accelerator: "CmdOrCtrl+X",
          selector: "cut:"
      }, {
          label: "Copy",
          accelerator: "CmdOrCtrl+C",
          selector: "copy:"
      }, {
          label: "Paste",
          accelerator: "CmdOrCtrl+V",
          selector: "paste:"
      }, {
          label: "Select All",
          accelerator: "CmdOrCtrl+A",
          selector: "selectAll:"
      }]
  }];

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  mainWindow.on('closed', function() {
    mainWindow = null;
    if (subpy && subpy.pid) {
      killProcess(subpy.pid);
    }
  });
});

function logData(str){
  console.log(str);
  // if(mainWindow){
  //   mainWindow.webContents.executeJavaScript('console.log(unescape("'+escape(str)+'"))');
  // }
}

function killProcess(pid) {
  try {
    process.kill(-pid, 'SIGINT');
  } catch (e) {
    process.kill(pid, 'SIGINT');
  }
}

ipcMain.on('startPython', function(event, auth, code, lat, long) {
  if (!procStarted) {
    logData('Starting Python process...');
    startPython(auth, code, lat, long);
  }
  procStarted = true;
});

ipcMain.on('getServer', function(event) {
  event.sender.send('server-up', mainAddr);
});

ipcMain.on('installUpdate', function(event) {
  autoUpdater.quitAndInstall();
});

function startPython(auth, code, lat, long) {

  mainWindow.loadURL('file://' + __dirname + '/main.html');
  //mainWindow.openDevTools();

  // Find open port
  var portfinder = require('portfinder');
  portfinder.getPort(function (err, port) {

    logData('Got open port: ' + port);

    // Run python web server
    var cmdLine = [
      './example.py',
      '--auth_service',
      auth,
      '--token',
      code,
      '--location',
      lat + ',' + long,
      '--auto_refresh',
      '10',
      '--step-limit',
      '7',
      //'--display-pokestop',
      '--display-gym',
      '--port',
      port,
      '--parent_pid',
      process.pid
    ];
    // console.log(cmdLine);
    logData('Maps path: ' + path.join(__dirname, 'map'));
    logData('python ' + cmdLine.join(' '))

    var pythonCmd = 'python';
    if (os.platform() == 'win32') {
      pythonCmd = path.join(__dirname, 'pywin', 'python.exe');
    }

    subpy = require('child_process').spawn(pythonCmd, cmdLine, {
      cwd: path.join(__dirname, 'map'),
      detached: true
    });

    subpy.stdout.on('data', (data) => {
      logData(`Python: ${data}`);
    });
    subpy.stderr.on('data', (data) => {
      logData(`Python: ${data}`);
    });

    var rq = require('request-promise');
    mainAddr = 'http://localhost:' + port;

    var openWindow = function(){
      mainWindow.webContents.send('server-up', mainAddr);
      mainWindow.webContents.executeJavaScript(
        'serverUp("'+mainAddr+'")');
      mainWindow.on('closed', function() {
        mainWindow = null;
        if (subpy && subpy.pid) {
          killProcess(subpy.pid);
        }
        procStarted = false;
      });
    };

    var startUp = function(){
      rq(mainAddr)
        .then(function(htmlString){
          logData('server started!');
          openWindow();
        })
        .catch(function(err){
          //console.log('waiting for the server start...');
          startUp();
        });
    };

    startUp();

  });

};
<commit_msg>Change var to const<commit_after>const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const ipcMain = electron.ipcMain;
const Menu = electron.Menu;
const path = require('path');
const os = require('os');
const autoUpdater = electron.autoUpdater;
const Menu = electron.Menu;
//electron.crashReporter.start();

var platform = os.platform() + '_' + os.arch();
var version = app.getVersion();

var mainWindow = null;
var procStarted = false;
var subpy = null;
var mainAddr;

try {
  autoUpdater.setFeedURL('https://pokemon-go-updater.mike.ai/update/'+platform+'/'+version);
} catch (e) {}

autoUpdater.on('update-downloaded', function(){
  mainWindow.webContents.send('update-ready');
});

// Setup menu bar
var template = [
  {
    label: "Application",
    submenu: [
        { label: "About Pokémon GO Live Map", selector: "orderFrontStandardAboutPanel:" },
        { type: "separator" },
        { label: "Quit", accelerator: "Command+Q", click: function() { app.quit(); }}
    ]
  },
  {
    label: "Edit",
    submenu: [
        { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
        { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
        { type: "separator" },
        { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
        { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
        { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
        { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
    ]
  },
  {
    label: "Tools",
    submenu: [
      {
        label: "Refresh",
        accelerator: "CmdOrCtrl+R",
        click(item, focusedWindow) {
          if (focusedWindow) focusedWindow.reload();
        }
      },
      {
        label: 'Toggle Developer Tools',
        accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
        click(item, focusedWindow) {
          if (focusedWindow)
            focusedWindow.webContents.toggleDevTools();
        }
      }
    ]
  }
];

app.on('window-all-closed', function() {
  if (subpy && subpy.pid) {
    killProcess(subpy.pid);
  }
  app.quit();
});

app.on('ready', function() {

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  mainWindow = new BrowserWindow({width: 800, height: 600, minWidth: 700, minHeight: 500});
  mainWindow.loadURL('file://' + __dirname + '/login.html');

  var template = [{
      label: "Application",
      submenu: [{
          label: "About Application",
          selector: "orderFrontStandardAboutPanel:"
      }, {
          type: "separator"
      }, {
          label: "Quit",
          accelerator: "Command+Q",
          click: function() {
              app.quit();
          }
      }]
  }, {
      label: "Edit",
      submenu: [{
          label: "Undo",
          accelerator: "CmdOrCtrl+Z",
          selector: "undo:"
      }, {
          label: "Redo",
          accelerator: "Shift+CmdOrCtrl+Z",
          selector: "redo:"
      }, {
          type: "separator"
      }, {
          label: "Cut",
          accelerator: "CmdOrCtrl+X",
          selector: "cut:"
      }, {
          label: "Copy",
          accelerator: "CmdOrCtrl+C",
          selector: "copy:"
      }, {
          label: "Paste",
          accelerator: "CmdOrCtrl+V",
          selector: "paste:"
      }, {
          label: "Select All",
          accelerator: "CmdOrCtrl+A",
          selector: "selectAll:"
      }]
  }];

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  mainWindow.on('closed', function() {
    mainWindow = null;
    if (subpy && subpy.pid) {
      killProcess(subpy.pid);
    }
  });
});

function logData(str){
  console.log(str);
  // if(mainWindow){
  //   mainWindow.webContents.executeJavaScript('console.log(unescape("'+escape(str)+'"))');
  // }
}

function killProcess(pid) {
  try {
    process.kill(-pid, 'SIGINT');
  } catch (e) {
    process.kill(pid, 'SIGINT');
  }
}

ipcMain.on('startPython', function(event, auth, code, lat, long) {
  if (!procStarted) {
    logData('Starting Python process...');
    startPython(auth, code, lat, long);
  }
  procStarted = true;
});

ipcMain.on('getServer', function(event) {
  event.sender.send('server-up', mainAddr);
});

ipcMain.on('installUpdate', function(event) {
  autoUpdater.quitAndInstall();
});

function startPython(auth, code, lat, long) {

  mainWindow.loadURL('file://' + __dirname + '/main.html');
  //mainWindow.openDevTools();

  // Find open port
  var portfinder = require('portfinder');
  portfinder.getPort(function (err, port) {

    logData('Got open port: ' + port);

    // Run python web server
    var cmdLine = [
      './example.py',
      '--auth_service',
      auth,
      '--token',
      code,
      '--location',
      lat + ',' + long,
      '--auto_refresh',
      '10',
      '--step-limit',
      '7',
      //'--display-pokestop',
      '--display-gym',
      '--port',
      port,
      '--parent_pid',
      process.pid
    ];
    // console.log(cmdLine);
    logData('Maps path: ' + path.join(__dirname, 'map'));
    logData('python ' + cmdLine.join(' '))

    var pythonCmd = 'python';
    if (os.platform() == 'win32') {
      pythonCmd = path.join(__dirname, 'pywin', 'python.exe');
    }

    subpy = require('child_process').spawn(pythonCmd, cmdLine, {
      cwd: path.join(__dirname, 'map'),
      detached: true
    });

    subpy.stdout.on('data', (data) => {
      logData(`Python: ${data}`);
    });
    subpy.stderr.on('data', (data) => {
      logData(`Python: ${data}`);
    });

    var rq = require('request-promise');
    mainAddr = 'http://localhost:' + port;

    var openWindow = function(){
      mainWindow.webContents.send('server-up', mainAddr);
      mainWindow.webContents.executeJavaScript(
        'serverUp("'+mainAddr+'")');
      mainWindow.on('closed', function() {
        mainWindow = null;
        if (subpy && subpy.pid) {
          killProcess(subpy.pid);
        }
        procStarted = false;
      });
    };

    var startUp = function(){
      rq(mainAddr)
        .then(function(htmlString){
          logData('server started!');
          openWindow();
        })
        .catch(function(err){
          //console.log('waiting for the server start...');
          startUp();
        });
    };

    startUp();

  });

};
<|endoftext|>


<commit_before>/**
 * @module timed
 * @submodule timed-controllers
 * @public
 */
import Controller         from 'ember-controller'
import computed, { sort } from 'ember-computed-decorators'
import moment             from 'moment'

/**
 * Controller to edit an activity
 *
 * @class IndexActivitiesEditController
 * @extends Ember.Controller
 * @public
 */
export default Controller.extend({
  /**
   * The sort key by which the blocks should be sorted
   *
   * @property {String[]} sortBy
   * @public
   */
  sortBy: [ 'from:desc' ],

  /**
   * The sorted blocks of the activity
   *
   * @property {ActivitBlock[]} blocks
   * @public
   */
  @sort('activity.blocks.[]', 'sortBy')
  blocks: [],

  /**
   * The total duration of all inactive blocks
   *
   * @property {moment.duration} total
   * @public
   */
  @computed('blocks.@each.{from,to}')
  total(blocks) {
    return blocks.reduce((dur, block) => {
      let { from, to } = block.getProperties('from', 'to')

      if (to) {
        dur.add(to.diff(from))
      }

      return dur
    }, moment.duration())
  }
})
<commit_msg>Please don't ask...<commit_after>/**
 * @module timed
 * @submodule timed-controllers
 * @public
 */
import Controller         from 'ember-controller'
import computed, { sort } from 'ember-computed-decorators'
import moment             from 'moment'

/**
 * Controller to edit an activity
 *
 * @class IndexActivitiesEditController
 * @extends Ember.Controller
 * @public
 */
const IndexActivitiesEditController = Controller.extend({
  /**
   * The sort key by which the blocks should be sorted
   *
   * @property {String[]} sortBy
   * @public
   */
  sortBy: [ 'from:desc' ],

  /**
   * The sorted blocks of the activity
   *
   * @property {ActivitBlock[]} blocks
   * @public
   */
  @sort('activity.blocks.[]', 'sortBy')
  blocks: [],

  /**
   * The total duration of all inactive blocks
   *
   * @property {moment.duration} total
   * @public
   */
  @computed('blocks.@each.{from,to}')
  total(blocks) {
    return blocks.reduce((dur, block) => {
      let { from, to } = block.getProperties('from', 'to')

      if (to) {
        dur.add(to.diff(from))
      }

      return dur
    }, moment.duration())
  }
})

export default IndexActivitiesEditController
<|endoftext|>


<commit_before>var DIR_LEFT = 0;
var DIR_RIGHT = 1;
var DIR_UP = 2;
var DIR_DOWN = 3;
var enemyAmount = 1;
enchant();

window.onload = function(){
    var game = new Core(320,320);
    game.preload('images/chara5.png','images/map0.png');

    game.onload = function(){
        var bg = new Sprite(320,320);
        var maptip = game.assets['images/map0.png'];
        var image = new Surface(320,320);
        for(var j=0; j<320; j+=16){
            for(var i=0; i<320; i+=16){
                image.draw(maptip,0,0,16,16,i,j,16,16);
            }
        }
        bg.image = image;
        game.rootScene.addChild(bg);

        var Player1 = enchant.Class.create(enchant.Sprite,{
            initialize: function(){
                enchant.Sprite.call(this,32,32);
                this.image = game.assets['images/chara5.png'];
                this.x = null;
                this.y = null;
                this.dir = null;
                this.anim = null;
                this.frame = 7;
                this.movement();
            },
            remove: function(){

            },
            movement: function(){
                this.x = 100;
                this.y = 16;
                this.dir = DIR_DOWN;
                this.anim = [
                    9,10,11,10, //left
                    18,19,20,19, //right
                    27,28,29,28, //up
                    0,1,2,1]; //down

                this.addEventListener(Event.ENTER_FRAME,function(e){
                    if(game.input.up){
                        this.dir = DIR_UP;
                        this.y -= 4;
                    } else if(game.input.down){
                        this.dir = DIR_DOWN;
                        this.y += 4;
                    } else if(game.input.left){
                        this.dir = DIR_LEFT;
                        this.x -= 4;
                    } else if(game.input.right){
                        this.dir = DIR_RIGHT;
                        this.x += 4;
                    }

                    if(!game.input.up && !game.input.down && !game.input.left && !game.input.right) this.age = 1;
                    this.frame = this.anim[this.dir*4 + (this.age%4)];
                });
            }
        });

        var Enemy = enchant.Class.create(enchant.Sprite,{
            initialize: function(x,y,speed){
                enchant.Sprite.call(this,32,32);
                this.image = game.assets['images/chara5.png'];
                this.x = x - 16;
                this.y = y - 16;
                this.frame = 7;
                this.movement();
            },
            remove: function(){

            },
            movement: function(){
                this.toX = this.x;
                this.toY = this.y;
                this.dir = DIR_DOWN;
                this.anim = [
                15,16,17,16, //Left
                24,25,26,24, //Right
                33,34,35,34, //Up
                6,7,8,7]; //Down

                this.addEventListener(Event.ENTER_FRAME,function(){
                if(this.y>this.toY){
                    this.dir = DIR_UP;
                    if(Math.abs(this.y - this.toY)<3){
                        this.y = this.toY;
                    } else {
                        this.y -= 3;
                    }
                 } else if (this.y < this.toY) {
                    this.dir = DIR_DOWN;
                    if(Math.abs(this.y - this.toY) < 3){
                        this.y = this.toY;
                    } else {
                        this.y += 3;
                    }
                }

                if(this.x>this.toX){
                    this.dir = DIR_LEFT;
                    if(Math.abs(this.x - this.toX)<3){
                        this.x = this.toX;
                    } else {
                        this.x -= 3;
                    }
                 } else if (this.x < this.toX) {
                    this.dir = DIR_RIGHT;
                    if(Math.abs(this.x - this.toX) < 3){
                        this.x = this.toX;
                    } else {
                        this.x += 3;
                    }
                }
                if (this.x == this.toX && this.y == this.toY) this.age = 1;
                this.frame = this.anim[this.dir*4 + (this.age % 4)];

                this.addEventListener(Event.ENTER_FRAME,function(e){
                    if(!this.intersect(player1)){
                        this.toX = player1.x;
                        this.toY = player1.y;
                    } else {
                    }
                });
             });
          }
        });

        var enemy1 = new Enemy(160,160,0);
        var player1 = new Player1();
        game.rootScene.addChild(enemy1);
        game.rootScene.addChild(player1);
        };
    game.start();

};
<commit_msg>added guard class defined boundaries fixed chest boundaries<commit_after>//Global Variables
var DIR_LEFT = 0;
var DIR_RIGHT = 1;
var DIR_UP = 2;
var DIR_DOWN = 3;
var chestsAmount = 3;
var chests = [];
var guardAmount = chestsAmount;
var guards = [];

enchant();
window.onload = function(){
    var game = new Core(320,320);
    game.preload('images/chara5.png','images/map0.png','images/chara6.png');

    game.onload = function(){
        var bg = new Sprite(320,320);
        var maptip = game.assets['images/map0.png'];
        var image = new Surface(320,320);
        for(var j=0; j<320; j+=16){
            for(var i=0; i<320; i+=16){
                image.draw(maptip,0,0,16,16,i,j,16,16);
            }
        }
        bg.image = image;
        game.rootScene.addChild(bg);

        var Player1 = enchant.Class.create(enchant.Sprite,{
            initialize: function(){
                enchant.Sprite.call(this,32,32);
                this.image = game.assets['images/chara5.png'];
                this.x = null;
                this.y = null;
                this.dir = null;
                this.anim = null;
                this.frame = 7;

                this.movement();
            },
            remove: function(){

            },
            movement: function(){
                this.x = 100;
                this.y = 16;
                this.dir = DIR_DOWN;
                this.anim = [
                    9,10,11,10, //left
                    18,19,20,19, //right
                    27,28,29,28, //up
                    0,1,2,1]; //down

                this.addEventListener(Event.ENTER_FRAME,function(e){

                        if(game.input.up){
                            this.dir = DIR_UP;
                            if(this.y > 0)
                            this.y -= 4;
                        } else if(game.input.down){
                            this.dir = DIR_DOWN;
                            if(this.y < 320 - this.height)
                            this.y += 4;
                        } else if(game.input.left){
                            this.dir = DIR_LEFT;
                            if(this.x > 0)
                            this.x -= 4;
                        } else if(game.input.right){
                            this.dir = DIR_RIGHT;
                            if(this.x < 320 - this.width)
                            this.x += 4;
                        }

                        if(!game.input.up && !game.input.down && !game.input.left && !game.input.right) this.age = 1;
                        this.frame = this.anim[this.dir*4 + (this.age%4)];

                    this.checkChest();
                });
            },
            checkChest: function(){
                for(var i=0;i<chestsAmount;i++){
                    if(this.intersect(chests[i])){
                        if(chests[i].special == true){
                            console.log('RIGHT CHEST');
                        }else{
                            console.log('TRY AGAIN');
                        }
                    }
                }
            }

        });

        var Enemy = enchant.Class.create(enchant.Sprite,{
            initialize: function(x,y,speed){
                enchant.Sprite.call(this,32,32);
                this.image = game.assets['images/chara5.png'];
                this.x = x - 16;
                this.y = y - 16;
                this.frame = 7;
                this.movement();
            },
            remove: function(){

            },
            movement: function(){
                this.toX = this.x;
                this.toY = this.y;
                this.dir = DIR_DOWN;
                this.anim = [
                15,16,17,16, //Left
                24,25,26,24, //Right
                33,34,35,34, //Up
                6,7,8,7]; //Down

                this.addEventListener(Event.ENTER_FRAME,function(){
                if(this.y>this.toY){
                    this.dir = DIR_UP;
                    if(Math.abs(this.y - this.toY)<3){
                        this.y = this.toY;
                    } else {
                        this.y -= 3;
                    }
                 } else if (this.y < this.toY) {
                    this.dir = DIR_DOWN;
                    if(Math.abs(this.y - this.toY) < 3){
                        this.y = this.toY;
                    } else {
                        this.y += 3;
                    }
                }

                if(this.x>this.toX){
                    this.dir = DIR_LEFT;
                    if(Math.abs(this.x - this.toX)<3){
                        this.x = this.toX;
                    } else {
                        this.x -= 3;
                    }
                 } else if (this.x < this.toX) {
                    this.dir = DIR_RIGHT;
                    if(Math.abs(this.x - this.toX) < 3){
                        this.x = this.toX;
                    } else {
                        this.x += 3;
                    }
                }
                if (this.x == this.toX && this.y == this.toY) this.age = 1;
                this.frame = this.anim[this.dir*4 + (this.age % 4)];

                this.addEventListener(Event.ENTER_FRAME,function(e){
                    if(!this.intersect(player1)){
                        this.toX = player1.x;
                        this.toY = player1.y;
                    } else {
                    }
                });
             });
          }
        });

        var Chest = enchant.Class.create(enchant.Sprite,{
            initialize:function(x,y){
                enchant.Sprite.call(this,16,16);
                this.image = game.assets['images/map0.png'];
                this.frame = 25;
                this.x = x;
                this.y = y;
                this.special = false;
            },
            remove:function(){

            }
        });

        //UNFINISHED
        var Guard = enchant.Class.create(enchant.Sprite,{
            initialize:function(chestx,chesty,speed){
                enchant.Sprite.call(this,16,16);
                this.image = game.assets['images/chara6.png'];
                this.frame = 5;
                this.x = 0;
                this.y = 0;
                this.speed = speed;

            },
            remove:function(){

            },
            movement:function(chest,speed){

            }
        });

        //helpers
        function rand(num){
            return Math.floor(Math.random() * num);
        }

        var enemy1 = new Enemy(160,160,0);
        var player1 = new Player1();

        for(var i=0;i<chestsAmount;i++){
            chests.push(new Chest(rand(304),rand(304)));
            game.rootScene.addChild(chests[i]);

            //UNFINISHED
            for(var j=0;j<guardAmount;j++){
                guards.push(new Guard(chests[i].x,chests[i].y,2));
                game.rootScene.addChild(guards[j]);
            }

        }
            chests[rand(chestsAmount)].special = true;

        game.rootScene.addChild(enemy1);
        game.rootScene.addChild(player1);
        };
    game.start();

};
<|endoftext|>


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

    // Function used to create SVG elements. jquery does not handle the namespace issue correctly
    function $s(elem) {
        return $(document.createElementNS('http://www.w3.org/2000/svg', elem));
    }

    (function init() {
        $('video').each( function () {
            if (this.readyState !== 4) {
                this.addEventListener('loadedmetadata', function() {
                    return parseVideoSource(this);
                });
            } else {
                return parseVideoSource(this);
            }
        });
    })();

    function parseVideoSource(video) {
        var source = video.currentSrc;
        var hash = source.substring(source.indexOf('#') + 1).split('&');
        var parameters = {};
        hash.map(function(keyValue) {
            var key = keyValue.split('=')[0];
            var value = keyValue.split('=')[1];
            parameters[key] = value;
        });

        var start = parameters.t.split(',')[0];
        var end = parameters.t.split(',')[1];
        var debug = parameters.debug;
        var fragmentDuration = end - start;

        var shape = parameters.shape; // SVG path
        var trajectory = parameters.trajectory; // Subset of SVG path

        // Ensure that video element has an id
        var id = video.id || 'video_' + (Math.random()).toString().substr(2);
        video.id = id;

        $(video).wrap("

").each( function () {
            var container = $(this).parent().css("position", "relative");
            $(this).css({
                position: "absolute",
                top: "0px",
                left: "0px"
            });

            var width = $(this).width();
            var height = $(this).height();
            var svg = $s("svg")
                    .attr({
                        class: "svg_overlay",
                        version:"1.1",
                        xmlns: "http://www.w3.org/2000/svg",
                        "xmlns:xlink": "http://www.w3.org/1999/xlink",
                        x: "0px",
                        y: "0px",
                        viewBox: "0 0 " + width + " " + height,
                        "enable-background": "new 0 0 " + width + " " + height,
                        "xml:space": "preserve",
                        width: width,
                        height: height,
                        id: video.id + "_overlay" })
                    .css({
                        position: "absolute",
                        top: "0px",
                        left: "0px"
                    });
            container.append(svg);

            var g = $s("g")
                    .attr("id", video.id + "_overlay_group");
            svg.append(g);

            var _data = /^(circle|rect|ellipse|path):(.+)/.exec(shape);
            if (! _data) {
                // If no shape type is specified, consider it is a path
                _data = [ shape, 'path', shape ];
            }
            var obj;
            var points;
            switch (_data[1]) {
            case 'path':
                obj = $s("path")
                    .attr("d", _data[2]);
                break;
            case 'rect':
                points = _data[2].split(" ");
                obj = $s("rect")
                    .attr("x", points[0])
                    .attr("y", points[1])
                    .attr("width", points[2])
                    .attr("height", points[3]);
                break;
            case 'circle':
                points = _data[2].split(" ");
                obj = $s("circle")
                    .attr("cx", points[0])
                    .attr("cy", points[1])
                    .attr("r", points[2]);
                break;
            case 'ellipse':
                points = _data[2].split(" ");
                obj = $s("ellipse")
                    .attr("cx", points[0])
                    .attr("cy", points[1])
                    .attr("rx", points[2])
                    .attr("ry", points[3]);
                break;
            };
            // Define common attributes
            obj.attr("id", video.id + "_overlay_shape")
                .attr("class", "overlay_shape");
            g.append(obj);

            var update_position = function(current_time, g) {
                return;
            };

            // Create a trajectory path
            if (trajectory) {
                // Inspired by https://github.com/yairEO/pathAnimator
                var object = $s('path')
                        .attr('d', trajectory)
                        .attr('fill', 'none')
                        .attr('stroke', 'red')[0];
                if (debug)
                    svg.append($(object));
                var length = object.getTotalLength();
                update_position =  function (current_time, g) {
                    var percent = (current_time - start) / fragmentDuration;
                    var point = object.getPointAtLength( length * percent);
                    g.attr("transform", "translate(" + point.x + "," + point.y + ")");
                };
            }
            var HIDDEN = 0, SHOWN = 1;
            var state = SHOWN;
            function hide_shape() {
                if (state !== HIDDEN) {
                    svg.hide();
                    state = HIDDEN;
                }
            }
            function show_shape() {
                if (state != SHOWN) {
                    svg.show();
                    state = SHOWN;
                }
            }
            // If a trajectory is defined, its starting point may not
            // be the initialization point, so start by hiding the
            // shape
            if (trajectory)
                hide_shape();

            video.addEventListener('timeupdate', function() {
                if (video.currentTime < start || video.currentTime > end) {
                    hide_shape();
                } else {
                    if (trajectory)
                        update_position(video.currentTime, g);
                    if (state !== SHOWN)
                        show_shape();
                }
            });
        });
    }
})(jQuery);
<commit_msg>Coding style fixes<commit_after>(function($) {
    'use strict';

    // Function used to create SVG elements. jquery does not handle the namespace issue correctly
    function $s(elem) {
        return $(document.createElementNS('http://www.w3.org/2000/svg', elem));
    }

    (function init() {
        $('video').each(function () {
            if (this.readyState !== 4) {
                this.addEventListener('loadedmetadata', function() {
                    return parseVideoSource(this);
                });
            } else {
                return parseVideoSource(this);
            }
        });
    })();

    function parseVideoSource(video) {
        var source = video.currentSrc;
        var hash = source.substring(source.indexOf('#') + 1).split('&');
        var parameters = {};
        hash.map(function(keyValue) {
            var key = keyValue.split('=')[0];
            var value = keyValue.split('=')[1];
            parameters[key] = value;
        });

        var start = parameters.t.split(',')[0];
        var end = parameters.t.split(',')[1];
        var debug = parameters.debug;
        var fragmentDuration = end - start;

        var shape = parameters.shape; // SVG path
        var trajectory = parameters.trajectory; // Subset of SVG path

        // Ensure that video element has an id
        var id = video.id || 'video_' + (Math.random()).toString().substr(2);
        video.id = id;

        $(video).wrap("

").each(function () {
            var container = $(this).parent().css("position", "relative");
            $(this).css({
                position: "absolute",
                top: "0px",
                left: "0px"
            });

            var width = $(this).width();
            var height = $(this).height();
            var svg = $s("svg")
                    .attr({
                        class: "svg_overlay",
                        version:"1.1",
                        xmlns: "http://www.w3.org/2000/svg",
                        "xmlns:xlink": "http://www.w3.org/1999/xlink",
                        x: "0px",
                        y: "0px",
                        viewBox: "0 0 " + width + " " + height,
                        "enable-background": "new 0 0 " + width + " " + height,
                        "xml:space": "preserve",
                        width: width,
                        height: height,
                        id: video.id + "_overlay" })
                    .css({
                        position: "absolute",
                        top: "0px",
                        left: "0px"
                    });
            container.append(svg);

            var g = $s("g")
                    .attr("id", video.id + "_overlay_group");

            if (parameters.mode == 'mask') {
                var defs = $s("defs");
                svg.append(defs);
                var mask = $s("mask")
                        .attr("id", video.id + "_overlay_mask")
                        .attr("maskUnits", "userSpaceOnUse")
                        .attr("maskContentUnits", "userSpaceOnUse");
                defs.append(mask);
                mask.append(g);
            } else {
                svg.append(g);
            }

            var _data = /^(circle|rect|ellipse|path):(.+)/.exec(shape);
            if (!_data) {
                // If no shape type is specified, consider it is a path
                _data = [ shape, 'path', shape ];
            }
            var obj;
            var points;
            switch (_data[1]) {
            case 'path':
                obj = $s("path")
                    .attr("d", _data[2]);
                break;
            case 'rect':
                points = _data[2].split(" ");
                obj = $s("rect")
                    .attr("x", points[0])
                    .attr("y", points[1])
                    .attr("width", points[2])
                    .attr("height", points[3]);
                break;
            case 'circle':
                points = _data[2].split(" ");
                obj = $s("circle")
                    .attr("cx", points[0])
                    .attr("cy", points[1])
                    .attr("r", points[2]);
                break;
            case 'ellipse':
                points = _data[2].split(" ");
                obj = $s("ellipse")
                    .attr("cx", points[0])
                    .attr("cy", points[1])
                    .attr("rx", points[2])
                    .attr("ry", points[3]);
                break;
            };
            // Define common attributes
            obj.attr("id", video.id + "_overlay_shape")
                .attr("class", "overlay_shape");
            g.append(obj);

            var update_position = function(current_time, g) {
                return;
            };

            // Create a trajectory path
            if (trajectory) {
                // Inspired by https://github.com/yairEO/pathAnimator
                var object = $s('path')
                        .attr('d', trajectory)
                        .attr('fill', 'none')
                        .attr('stroke', 'red')[0];
                if (debug) {
                    svg.append($(object));
                }
                var length = object.getTotalLength();
                update_position =  function (current_time, g) {
                    var percent = (current_time - start) / fragmentDuration;
                    var point = object.getPointAtLength(length * percent);
                    g.attr("transform", "translate(" + point.x + "," + point.y + ")");
                };
            }
            var HIDDEN = 0, SHOWN = 1;
            var state = SHOWN;
            function hide_shape() {
                if (state !== HIDDEN) {
                    svg.hide();
                    state = HIDDEN;
                }
            }
            function show_shape() {
                if (state != SHOWN) {
                    svg.show();
                    state = SHOWN;
                }
            }
            // If a trajectory is defined, its starting point may not
            // be the initialization point, so start by hiding the
            // shape
            if (trajectory) {
                hide_shape();
            }
            video.addEventListener('timeupdate', function() {
                if (video.currentTime < start || video.currentTime > end) {
                    hide_shape();
                } else {
                    if (trajectory) {
                        update_position(video.currentTime, g);
                    }
                    if (state !== SHOWN) {
                        show_shape();
                    }
                }
            });
        });
    }
})(jQuery);
<|endoftext|>


<commit_before>const {ipcMain} = require('electron');
const menubar = require('menubar');
const Keymetrics = require('keymetrics-api');
const fs = require('fs');
const open = require('open');
const path = require('path');

// Glabal var
var km;
var tokens;
var bucketId;
var servers = [];
var serversIndex = [];
var exceptions = {};
var charts = {};

// Menubar config
var mb = menubar({
  dir: path.join(__dirname, '/public'),
  width: 350,
  height: 600,
  resizable: false,
  icon: path.join(__dirname, '/public/assets/iconTemplate.png'),
  preloadWindow: true
});

// Get home directory
var getHome = () => {
  return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
};

// Read .keymetrics in home directory
var readFile = () => {
  if (!fs.existsSync(getHome() + '/.keymetrics')) {
    fs.openSync(getHome() + '/.keymetrics', 'w');
  }
  return fs.readFileSync(getHome() + '/.keymetrics').toString();
};

// Write .keymetrics in home directory
var writeFile = (tokens) => {
  var file;
  tokens = JSON.stringify(tokens);
  try {
    file = fs.writeFileSync(getHome() + '/.keymetrics', tokens);
  } catch (e) {
    file = null;
  }
  return file;
};

// Put data in array to send it in callback
var putData = (data, cb) => {
  for (var server in data.apps_server) {
    if (serversIndex.indexOf(server) === -1) {
      serversIndex.push(server);
    }
    var index = serversIndex.indexOf(server);
    servers[index] = {
      name: server,
      processes: []
    };

    var processes = Object.keys(data.apps_server[server]).sort();

    processes.forEach((process) => {
      if (!charts[`cpu-${server}-${process}`] || charts[`cpu-${server}-${process}`].length === 0) {
        charts[`cpu-${server}-${process}`] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      }
      if (charts[`cpu-${server}-${process}`] && charts[`cpu-${server}-${process}`].length > 10) {
        charts[`cpu-${server}-${process}`].shift();
      }
      charts[`cpu-${server}-${process}`].push(data.mini_metrics[server][process].cpu[0]);

      if (!charts[`mem-${server}-${process}`] || charts[`mem-${server}-${process}`].length === 0) {
        charts[`mem-${server}-${process}`] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      }
      if (charts[`mem-${server}-${process}`] && charts[`mem-${server}-${process}`].length > 10) {
        charts[`mem-${server}-${process}`].shift();
      }

      charts[`mem-${server}-${process}`].push(data.mini_metrics[server][process].mem[0]);

      servers[index].processes.push({
        status: (data.apps_server[server][process].status === 'online') ? 'online' : 'offline',
        name: process,
        probes: [
          {
            logo: 'cpu',
            name: 'CPU',
            gradient: (data.mini_metrics[server][process].cpu > 50) ? 'red' : 'green',
            value: data.mini_metrics[server][process].cpu,
            units: '%',
            graph: {
              name: `cpu-${server}-${process}`,
              values: charts[`cpu-${server}-${process}`]
            },
            url: `https://app.keymetrics.io/#/bucket/${bucketId}/apps-signs?server_name=${server}&app_name=${process}`
          },
          {
            logo: 'memory',
            name: 'MEM',
            gradient: (data.mini_metrics[server][process].mem > 1000) ? 'red' : 'green',
            value: data.mini_metrics[server][process].mem[0],
            units: 'MB',
            graph: {
              name: `mem-${server}-${process}`,
              values: charts[`mem-${server}-${process}`]
            },
            url: `https://app.keymetrics.io/#/bucket/${bucketId}/apps-signs?server_name=${server}&app_name=${process}`
          },
          {
            logo: 'bug',
            name: 'Errors',
            gradient: 'red',
            value: (exceptions[server] && exceptions[server][process]) ? exceptions[server][process] : 0,
            units: 'bug_gradient_red.svg',
            url: `https://app.keymetrics.io/#/bucket/${bucketId}/exceptions?server_name=${server}&app_name=${process}`
          }
        ]
      });
      if (data.apps_server[server][process].axm_monitor['pmx:http:latency']) {
        servers[index].processes[servers[index].processes.length - 1].probes.push({
          logo: 'world',
          name: 'HTTP avg.',
          gradient: (parseFloat(data.apps_server[server][process].axm_monitor['pmx:http:latency'].value) > 1000) ? 'red' : 'green',
          value: data.apps_server[server][process].axm_monitor['pmx:http:latency'].value,
          url: `https://app.keymetrics.io/#/bucket/${bucketId}/transactions?server_name=${server}&app_name=${process}`
        });
      }
    });
  }
  cb(servers);
};

// Put execptions in array
var putExceptions = (data) => {
  data.forEach((server) => {
    if (!exceptions[server.process.server]) {
      exceptions[server.process.server] = {};
    }
    if (!exceptions[server.process.server][server.process.name]) {
      exceptions[server.process.server][server.process.name] = 0;
    }
    exceptions[server.process.server][server.process.name] += 1;
  });
};

// Keymetrics config
var kmConfig = (tokens) => {
  km = new Keymetrics({
    token: tokens.token,
    public_key: tokens.public_key,
    realtime: true
  });
};

// Get data from bus
var kmData = () => {
  km.init((err, res) => {
    if (err) {
      return;
    }

    // Get exceptions
    km.bucket.Data.exceptionsSummary((err, body) => {
      if (err) {
        return;
      }
      exceptions = body;
    });

    km.bucket.retrieve(tokens.public_key, (err, bucket) => {
      if (err) {
        return;
      }
      bucketId = bucket._id;
    });

    // Exceptions bus
    km.bus.on('**:exception', (data) => {
      putExceptions(data);
    });

    // Data bus
    km.bus.on('data:*:status', (data) => {
      if (mb.window) {
        putData(data, (servers) => {
          mb.window.webContents.send('data', servers);
        });
      }
    });
  });
};

// Save settings (Save button on Settings UI)
ipcMain.on('saveSettings', (event, arg) => {
  writeFile(arg);
  tokens = arg;
  if (km) {
    km.close();
    km = null;
  }
  servers = [];
  kmConfig(arg);
  kmData();
  mb.window.webContents.send('tokens', tokens);
});

// Quit app (Disconnect link on Settings UI)
ipcMain.on('quit', (event, arg) => {
  if (km) {
    km.close();
    km = null;
  }
  process.exit(0);
});

// Get data when widget is open
mb.on('show', () => {
  if (tokens) {
    kmConfig(tokens);
    kmData();
  }
});

// Close km when widget is closed
mb.on('hide', () => {
  if (km) {
    km.close();
    km = null;
  }
});

// App ready
mb.on('ready', () => {
  try {
    tokens = JSON.parse(readFile());
  } catch (e) {}

  mb.showWindow();

  // DOM ready
  mb.window.webContents.on('dom-ready', () => {
    mb.window.webContents.send('tokens', tokens);
  });

  // Handle link to open external browser
  mb.window.webContents.on('new-window', (event, url) => {
    event.preventDefault();
    open(url);
  });
});
<commit_msg>Replace .close to .unregister<commit_after>const {ipcMain} = require('electron');
const menubar = require('menubar');
const Keymetrics = require('keymetrics-api');
const fs = require('fs');
const open = require('open');
const path = require('path');

// Glabal var
var km;
var tokens;
var bucketId;
var servers = [];
var serversIndex = [];
var exceptions = {};
var charts = {};

// Menubar config
var mb = menubar({
  dir: path.join(__dirname, '/public'),
  width: 350,
  height: 600,
  resizable: false,
  icon: path.join(__dirname, '/public/assets/iconTemplate.png'),
  preloadWindow: true
});

// Get home directory
var getHome = () => {
  return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
};

// Read .keymetrics in home directory
var readFile = () => {
  if (!fs.existsSync(getHome() + '/.keymetrics')) {
    fs.openSync(getHome() + '/.keymetrics', 'w');
  }
  return fs.readFileSync(getHome() + '/.keymetrics').toString();
};

// Write .keymetrics in home directory
var writeFile = (tokens) => {
  var file;
  tokens = JSON.stringify(tokens);
  try {
    file = fs.writeFileSync(getHome() + '/.keymetrics', tokens);
  } catch (e) {
    file = null;
  }
  return file;
};

// Put data in array to send it in callback
var putData = (data, cb) => {
  for (var server in data.apps_server) {
    if (serversIndex.indexOf(server) === -1) {
      serversIndex.push(server);
    }
    var index = serversIndex.indexOf(server);
    servers[index] = {
      name: server,
      processes: []
    };

    var processes = Object.keys(data.apps_server[server]).sort();

    processes.forEach((process) => {
      if (!charts[`cpu-${server}-${process}`] || charts[`cpu-${server}-${process}`].length === 0) {
        charts[`cpu-${server}-${process}`] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      }
      if (charts[`cpu-${server}-${process}`] && charts[`cpu-${server}-${process}`].length > 10) {
        charts[`cpu-${server}-${process}`].shift();
      }
      charts[`cpu-${server}-${process}`].push(data.mini_metrics[server][process].cpu[0]);

      if (!charts[`mem-${server}-${process}`] || charts[`mem-${server}-${process}`].length === 0) {
        charts[`mem-${server}-${process}`] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      }
      if (charts[`mem-${server}-${process}`] && charts[`mem-${server}-${process}`].length > 10) {
        charts[`mem-${server}-${process}`].shift();
      }

      charts[`mem-${server}-${process}`].push(data.mini_metrics[server][process].mem[0]);

      servers[index].processes.push({
        status: (data.apps_server[server][process].status === 'online') ? 'online' : 'offline',
        name: process,
        probes: [
          {
            logo: 'cpu',
            name: 'CPU',
            gradient: (data.mini_metrics[server][process].cpu > 50) ? 'red' : 'green',
            value: data.mini_metrics[server][process].cpu,
            units: '%',
            graph: {
              name: `cpu-${server}-${process}`,
              values: charts[`cpu-${server}-${process}`]
            },
            url: `https://app.keymetrics.io/#/bucket/${bucketId}/apps-signs?server_name=${server}&app_name=${process}`
          },
          {
            logo: 'memory',
            name: 'MEM',
            gradient: (data.mini_metrics[server][process].mem > 1000) ? 'red' : 'green',
            value: data.mini_metrics[server][process].mem[0],
            units: 'MB',
            graph: {
              name: `mem-${server}-${process}`,
              values: charts[`mem-${server}-${process}`]
            },
            url: `https://app.keymetrics.io/#/bucket/${bucketId}/apps-signs?server_name=${server}&app_name=${process}`
          },
          {
            logo: 'bug',
            name: 'Errors',
            gradient: 'red',
            value: (exceptions[server] && exceptions[server][process]) ? exceptions[server][process] : 0,
            units: 'bug_gradient_red.svg',
            url: `https://app.keymetrics.io/#/bucket/${bucketId}/exceptions?server_name=${server}&app_name=${process}`
          }
        ]
      });
      if (data.apps_server[server][process].axm_monitor['pmx:http:latency']) {
        servers[index].processes[servers[index].processes.length - 1].probes.push({
          logo: 'world',
          name: 'HTTP avg.',
          gradient: (parseFloat(data.apps_server[server][process].axm_monitor['pmx:http:latency'].value) > 1000) ? 'red' : 'green',
          value: data.apps_server[server][process].axm_monitor['pmx:http:latency'].value,
          url: `https://app.keymetrics.io/#/bucket/${bucketId}/transactions?server_name=${server}&app_name=${process}`
        });
      }
    });
  }
  cb(servers);
};

// Put execptions in array
var putExceptions = (data) => {
  data.forEach((server) => {
    if (!exceptions[server.process.server]) {
      exceptions[server.process.server] = {};
    }
    if (!exceptions[server.process.server][server.process.name]) {
      exceptions[server.process.server][server.process.name] = 0;
    }
    exceptions[server.process.server][server.process.name] += 1;
  });
};

// Keymetrics config
var kmConfig = (tokens) => {
  km = new Keymetrics({
    token: tokens.token,
    public_key: tokens.public_key,
    realtime: true
  });
};

// Get data from bus
var kmData = () => {
  km.init((err, res) => {
    if (err) {
      return;
    }

    // Get exceptions
    km.bucket.Data.exceptionsSummary((err, body) => {
      if (err) {
        return;
      }
      exceptions = body;
    });

    km.bucket.retrieve(tokens.public_key, (err, bucket) => {
      if (err) {
        return;
      }
      bucketId = bucket._id;
    });

    // Exceptions bus
    km.bus.on('**:exception', (data) => {
      putExceptions(data);
    });

    // Data bus
    km.bus.on('data:*:status', (data) => {
      if (mb.window) {
        putData(data, (servers) => {
          mb.window.webContents.send('data', servers);
        });
      }
    });
  });
};

// Save settings (Save button on Settings UI)
ipcMain.on('saveSettings', (event, arg) => {
  writeFile(arg);
  tokens = arg;
  if (km) {
    km.close();
    km = null;
  }
  servers = [];
  kmConfig(arg);
  kmData();
  mb.window.webContents.send('tokens', tokens);
});

// Quit app (Disconnect link on Settings UI)
ipcMain.on('quit', (event, arg) => {
  if (km) {
    km.close();
    km = null;
  }
  process.exit(0);
});

var showed = false;

// Get data when widget is open
mb.on('show', () => {
  if (km && !showed) {
    showed = true;
    km.realtime.init({
      public_id: tokens.public_key,
      endpoint: km.bucket.current_raw.node_cache.endpoints.web
    });
  } else {
    kmConfig(tokens);
    kmData();
  }
});

// Close km when widget is closed
mb.on('hide', () => {
  if (km && showed) {
    showed = false;
    km.realtime.unregister();
  }
});

// App ready
mb.on('ready', () => {
  try {
    tokens = JSON.parse(readFile());
  } catch (e) {}

  mb.showWindow();

  // DOM ready
  mb.window.webContents.on('dom-ready', () => {
    mb.window.webContents.send('tokens', tokens);
  });

  // Handle link to open external browser
  mb.window.webContents.on('new-window', (event, url) => {
    event.preventDefault();
    open(url);
  });
});
<|endoftext|>


<commit_before>/*jslint vars: true */
/*global define, $, brackets, window, console */

define(function (require, exports, module) {

  var CommandManager       = brackets.getModule('command/CommandManager'),
      Commands             = brackets.getModule('command/Commands'),
      Menus                = brackets.getModule('command/Menus'),
      DocumentManager      = brackets.getModule('document/DocumentManager'),
      PreferencesManager   = brackets.getModule('preferences/PreferencesManager'),
      ExtensionUtils       = brackets.getModule( 'utils/ExtensionUtils' ),
      UseStrictStrings     = require('modules/strings'),
      UseStrictCommands    = require('modules/commands'),
      UseStrictPreferences = require('modules/preferences'),
      Helpers              = require('modules/helpers');

  var preferences = PreferencesManager.getExtensionPrefs('use-strict-js');

  setup();

  function setup() {
    $(DocumentManager).on('documentSaved', onDocumentSaved);

    CommandManager.register(
      UseStrictStrings.CMD_ENABLE_STRICT,
      UseStrictCommands.ENABLE_STRICT,
      processDocument
    );

    CommandManager.register(
      UseStrictStrings.CMD_ENABLE_STRICT_ON_SAVE,
      UseStrictCommands.ENABLE_STRICT_ON_SAVE,
      toggleStrict
    );

    var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
    menu.addMenuDivider();
    menu.addMenuItem(UseStrictCommands.ENABLE_STRICT, 'Ctrl-Shift-J');
    menu.addMenuItem(UseStrictCommands.ENABLE_STRICT_ON_SAVE);

    setupPreferences();
  }

  function setupPreferences() {
    var preference = UseStrictPreferences.ENABLE_STRICT_ON_SAVE;
    preferences.definePreference(preference.id, preference.type, preference.initial);
    preferences.save();

    preferences.on('change', function() {
      var enableStrictOnSave = preferences.get(preference.id);
      var menuItem = CommandManager.get(UseStrictCommands.ENABLE_STRICT_ON_SAVE);
      menuItem.setChecked(enableStrictOnSave);
    });
  }

  function toggleStrict() {
    var enableStrictOnSave = !preferences.get(UseStrictPreferences.ENABLE_STRICT_ON_SAVE.id);
    preferences.set(UseStrictPreferences.ENABLE_STRICT_ON_SAVE.id, enableStrictOnSave);
    preferences.save();
  }

  function onDocumentSaved() {
    var document = DocumentManager.getCurrentDocument();
    var enableStrictOnSave = preferences.get(UseStrictPreferences.ENABLE_STRICT_ON_SAVE.id);

    if (enableStrictOnSave && Helpers.isLanguage(document, ['javascript', 'unknown'])) {
      processDocument(document);
    }
  }

  function processDocument(document) {
    document = document || DocumentManager.getCurrentDocument();

    var isStrict = Helpers.isStrict(document);
    Helpers.log('Is Strict: ' + isStrict);
    if (isStrict) {
      return;
    }

    var isNodeJS = Helpers.isNodeJS(document);
    Helpers.log('Is Node.JS file: ' + isNodeJS);

    var insertionLineIndex = 0,
        useStrictStatement = "'use strict';\n",
        iterator = isNodeJS ? nodeJSIterator : defaultIterator,
        lines = document.getText().split('\n');

    lines.some(iterator);

    Helpers.log('Inserting at line index: ' + insertionLineIndex);
    document.replaceRange(useStrictStatement, { line: insertionLineIndex, ch: 0 });
    if (!document.isUntitled()) {
      CommandManager.execute(Commands.FILE_SAVE, { doc: document });
    }

    function nodeJSIterator(line, index) {
      if (line.search(/(^\s*?(\/|\*)|\*\/)/m) === -1 && line.length !== 0) {
        useStrictStatement = useStrictStatement + '\n';
        insertionLineIndex = index;
        return true;
      }
    }

    function defaultIterator(line, index) {
      if (line.search(/{$/) !== -1) {
        var spaceUnits = PreferencesManager.get('spaceUnits');
        useStrictStatement = Helpers.getPaddedString(spaceUnits) + useStrictStatement;
        insertionLineIndex = index + 1;
        return true;
      }
    }
  }
});<commit_msg>Added strict statement to JS files.<commit_after>/*jslint vars: true */
/*global define, $, brackets, window, console */

define(function (require, exports, module) {
  'use strict';

  var CommandManager       = brackets.getModule('command/CommandManager'),
      Commands             = brackets.getModule('command/Commands'),
      Menus                = brackets.getModule('command/Menus'),
      DocumentManager      = brackets.getModule('document/DocumentManager'),
      PreferencesManager   = brackets.getModule('preferences/PreferencesManager'),
      ExtensionUtils       = brackets.getModule( 'utils/ExtensionUtils' ),
      UseStrictStrings     = require('modules/strings'),
      UseStrictCommands    = require('modules/commands'),
      UseStrictPreferences = require('modules/preferences'),
      Helpers              = require('modules/helpers');

  var preferences = PreferencesManager.getExtensionPrefs('use-strict-js');

  setup();

  function setup() {
    $(DocumentManager).on('documentSaved', onDocumentSaved);

    CommandManager.register(
      UseStrictStrings.CMD_ENABLE_STRICT,
      UseStrictCommands.ENABLE_STRICT,
      processDocument
    );

    CommandManager.register(
      UseStrictStrings.CMD_ENABLE_STRICT_ON_SAVE,
      UseStrictCommands.ENABLE_STRICT_ON_SAVE,
      toggleStrict
    );

    var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
    menu.addMenuDivider();
    menu.addMenuItem(UseStrictCommands.ENABLE_STRICT, 'Ctrl-Shift-J');
    menu.addMenuItem(UseStrictCommands.ENABLE_STRICT_ON_SAVE);

    setupPreferences();
  }

  function setupPreferences() {
    var preference = UseStrictPreferences.ENABLE_STRICT_ON_SAVE;
    preferences.definePreference(preference.id, preference.type, preference.initial);
    preferences.save();

    preferences.on('change', function() {
      var enableStrictOnSave = preferences.get(preference.id);
      var menuItem = CommandManager.get(UseStrictCommands.ENABLE_STRICT_ON_SAVE);
      menuItem.setChecked(enableStrictOnSave);
    });
  }

  function toggleStrict() {
    var enableStrictOnSave = !preferences.get(UseStrictPreferences.ENABLE_STRICT_ON_SAVE.id);
    preferences.set(UseStrictPreferences.ENABLE_STRICT_ON_SAVE.id, enableStrictOnSave);
    preferences.save();
  }

  function onDocumentSaved() {
    var document = DocumentManager.getCurrentDocument();
    var enableStrictOnSave = preferences.get(UseStrictPreferences.ENABLE_STRICT_ON_SAVE.id);

    if (enableStrictOnSave && Helpers.isLanguage(document, ['javascript', 'unknown'])) {
      processDocument(document);
    }
  }

  function processDocument(document) {
    document = document || DocumentManager.getCurrentDocument();

    var isStrict = Helpers.isStrict(document);
    Helpers.log('Is Strict: ' + isStrict);
    if (isStrict) {
      return;
    }

    var isNodeJS = Helpers.isNodeJS(document);
    Helpers.log('Is Node.JS file: ' + isNodeJS);

    var insertionLineIndex = 0,
        useStrictStatement = "'use strict';\n",
        iterator = isNodeJS ? nodeJSIterator : defaultIterator,
        lines = document.getText().split('\n');

    lines.some(iterator);

    Helpers.log('Inserting at line index: ' + insertionLineIndex);
    document.replaceRange(useStrictStatement, { line: insertionLineIndex, ch: 0 });
    if (!document.isUntitled()) {
      CommandManager.execute(Commands.FILE_SAVE, { doc: document });
    }

    function nodeJSIterator(line, index) {
      if (line.search(/(^\s*?(\/|\*)|\*\/)/m) === -1 && line.length !== 0) {
        useStrictStatement = useStrictStatement + '\n';
        insertionLineIndex = index;
        return true;
      }
    }

    function defaultIterator(line, index) {
      if (line.search(/{$/) !== -1) {
        var spaceUnits = PreferencesManager.get('spaceUnits');
        useStrictStatement = Helpers.getPaddedString(spaceUnits) + useStrictStatement;
        insertionLineIndex = index + 1;
        return true;
      }
    }
  }
});<|endoftext|>


<commit_before>/// <reference path="~/phaser.js" />

// Global objects
var zombie;

var balloon;

var player;

var torso;

var shotgun;

var temp;

// Global helper members
var weights = [0.01, 0.03, 0.07, 0.3, 0.59];

// bool to check if zombie has any balloons left
var hasBallon;

// bool to check if zombie has reached the Man's cloud
var atCloud;

// Initialize Phaser, and create a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'gameDiv');

// Create our 'main' state that will contain the game
var mainState = {

    preload: function ()
    {
        // This function will be executed at the beginning
        // That's where we load the game's assets

        // Change the background color of the game
        game.stage.backgroundColor = '#71c5cf';

        // Load the image of Cloud
        game.load.image('cloud', 'assets/cloud.png');

        // Load the player sprite
        game.load.image('man', 'assets/man.png');

        // Load the zombie sprite
        game.load.image('zombie', 'assets/zombie.png');

        // Load the Red Balloon sprite
        game.load.image('redBalloon', 'assets/redBalloon.png');
    },

    // This function is called after the preload function
    // Here we set up the game, display sprites, etc.
    create: function ()
    {
        // Set the physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        /*
        Cloud Object
        */
        this.cloud = this.game.add.sprite(-100, 200, 'cloud');

        game.physics.arcade.enable(this.cloud);

        this.cloud.body.immovable = true;

        // PLAYER
        // Display the player on the screen
        this.man = this.game.add.sprite(100, 210, 'man');

        // Add gravity to the man to make it fall
        game.physics.arcade.enable(this.man);

        //this.man.body.gravity.y = 1000;

        // Call the 'shoot' function when the spacekey is hit
        var spaceKey =
            this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        spaceKey.onDown.add(this.shoot, this);

        // Main Holder Sprite :: ZOMBIE
        zombie = game.add.group();

        // Torso
        zombie.torso = game.add.sprite(0, 0, 'zombie');
        zombie.torso.anchor.setTo(0.5);
        zombie.addChild(zombie.torso);

        game.physics.arcade.enable(zombie.torso);

        //  Balloon
        zombie.balloon = game.add.sprite(0, -100, 'redBalloon');
        zombie.balloon.anchor.setTo(0.15, 0.5);
        zombie.addChild(zombie.balloon);

        this.balloons = game.add.group();
        this.balloons.enableBody = true;
        this.balloons.createMultiple(100, 'redBalloon');

        // Zombie :: PROPERTIES
        this.zombies = game.add.group();
        this.zombies.enableBody = true; // Add physics to the group
        //this.zombies.createMultiple(100, 'zombie');
        //this.zombies.createMultiple(100, 'redBalloon');
        this.zombies.add(zombie);

        // Set the position of the zombies group
        //this.zombies.setAll('zombie.body.x', 400);
        //this.zombies.setAll('zombie.body.y', 0);

        // Add timer :: call addRowOfPipes() every 1.5sec
        this.timer = game.time.events.loop(3500, this.addZombieHorde, this);
//        this.addZombieHorde;

        // Add timer :: Increase stats every 1.5sec
        //this.gameplayTimer = game.time.events.loop(10000, this.increaseStats, this);

        /*
        Player Score :: Label
        */

        // Create the Score object
        this.score = 0;

        this.labelScore = game.add.text(20, 20, "0", {
            font:
                "30px Arial", fill: "#ffffff" });
    },

    update: function ()
    {
        // This function is called 60 times per second
        // It contains the game's logic

        //TODO: Fix this to move the zombie left and fall onto the cloud
        // If the bird is out of the world (too high or too low), call the
        //'restartGame' function
        //if (this.zombie.inWorld == false)
        //    this.restartGame();

        // call restartGame() each time the bird collides with a pipe
        game.physics.arcade.overlap(this.man, this.pipes, this.restartGame,
            null, this);
    },

    // TODO: Create shotgun
    // TODO: Create pivot on shotgun
    // TODO: Create projectile
    // TODO: Make the projectile shoot from Shotgun
    //Make the player shoot
    shoot: function () {
        // Add a vertical velocity to the bird
        this.man.body.velocity.y = -350;
    },

    // Restart the game
    restartGame: function ()
    {
        // Start the 'main'state, which restarts the game
        game.state.start('main');
    },

    addOneZombie: function (x, y)
    {
        // Try putting the number of random number of zombies to output
        // as the condition in a for loop ~
        // Problem is setAll() i believe, that is why I am not getting my
        // Zombies to continue being spawned, but rather, they are spawn
        // -ing all ontop of each other
        var z = this.zombies;
        z.setAll('visible',true);
        //z.reset(x, y);
        z.setAll('x',x);
        z.setAll('y',y);

        /*
        this.zombies.forEach
        (
            function(zombie)
            {
                zombie.forEach
                (
                    function()
                    {
                        this.x = x; this.y = y;
                    }
                )
            }
        ); */
        //zombie.torso.reset(x, y);
        //zombie.xy(100,100);
        // Get the first dead zombie of our group
        //this.zombie = this.zombies.getFirstDead();

        // Set the new position of the pipe
        //zombie.torso.body.x = game.world.randomX;
        //zombie.torso.body.y = game.world.randomY;
        //zombie.torso.reset(x, y);
        //zombie.balloon.reset(x, y);
        //this.zombies.zombie.x = game.world.randomX;
        //this.zombies.zombie.y = game.world.randomY;

        // TEMP make zombies float
        //this.currentZombie.x = game.world.randomX;
        //this.currentZombie.y = game.world.randomY;

        //this.zombie.body.velocity.y = -20;

        // Set the gravity for the zombie
        //zombie.body.gravity.y = 1000;

        // Kill the zombie when it's no longer visible
        //torso.checkWorldBounds = true;
        //torso.outOfBoundsKill = true;
    },

    addZombieHorde: function ()
    {
        var numberOfZombies = [5, 4, 3, 2, 1];

        var weighedList = [];
        var counter = 0;

        // loop over weights
        for (i = 0; i < 5; i++)
        {
            var amount = weights[i] * 100;

            // Push Current PLACE into array proper amount
            for (var j = 0; j < amount; j++)
            {
                // Current PLACE :: Use i counter
                counter++;
                weighedList[counter] = numberOfZombies[i];
            }
        }

        // Pick number of zombies to spawn
        var R_Index = Math.floor( Math.random() * (100 - 0 + 1) ) + 0;

        // Get RandomNumber of zombies
        R_NumberOfZombies = weighedList[R_Index];
        temp = R_NumberOfZombies;

        for (var i = 0; i < R_NumberOfZombies; i++)
        {
            var xCoord = Math.floor(Math.random() * 300) + 150;
            var yCoord = Math.floor(Math.random() * 50) + 420;

            this.addOneZombie(xCoord, yCoord + 10);
        }

        // Increment the score by 1 ea time new pipes are created
        this.score += 1;

        this.labelScore.text = this.score;
    },

    addOneBalloon: function ()
    {
        this.currentBalloon = this.balloons.getFirstDead();

        currentBalloon.x = game.world.randomX;
        currentBalloon.y = game.world.randomY;

        currentBalloon.checkWorldBounds = true;
        currentBalloon.outOfBoundsKill = true;
    },

    addZombieHorde: function ()
    {
        var numberOfZombies = [5, 4, 3, 2, 1];

        var weighedList = [];
        var counter = 0;

        // loop over weights
        for (i = 0; i < 5; i++)
        {
            var amount = weights[i] * 100;

            // Push Current PLACE into array proper amount
            for (var j = 0; j < amount; j++)
            {
                // Current PLACE :: Use i counter
                counter++;
                weighedList[counter] = numberOfZombies[i];
            }
        }

        // Pick number of zombies to spawn
        var R_Index = Math.floor( Math.random() * (100 - 0 + 1) ) + 0;

        // Get RandomNumber of zombies
        R_NumberOfZombies = weighedList[R_Index];

        for (var i = 0; i < R_NumberOfZombies; i++)
        {
            var xCoord = Math.floor(Math.random() * 300) + 150;
            var yCoord = Math.floor(Math.random() * 50) + 420;

            this.addOneZombie(xCoord, yCoord + 10);
        }

        // Increment the score by 1 ea time new pipes are created
        this.score += 1;

        this.labelScore.text = this.score;
    },

    increaseStats: function()
    {
        console.log("increaseStats called~");

        //weights = [0.025, 0.1, 0.15, 0.225, 0.5];
        for (var i = 0; i < weights.length; i++)
        {
            // 5th is still greater than 4th
            if (weights[4] >= 29)
            {
                // Take 5 away from 5th Index
                weights[4] -= 5;

                // Take from the last, give to second to last
                weights[3] += 5;
            }
            // 4th is still greater than 3rd
            /*
            else if (weights[2] < 30)
            {
                weights[3] -= 5;
                weights[2] += 5;
            }
            else if (weights[1] < 60)
            {
                weights[3] -= 5;
                weights[2] += 5;
            }*/
        }
    },
};

// Add and start the 'main' state to start the game
game.state.add('main', mainState);
game.state.start('main');
<commit_msg>I have a lot of issues getting the balloons and zombies to spawn togeteher. I do have the balloons and zombie torsos in different groups added to a single main group, however, I don't know if that is right. This is a 'it's ok to break it' commit.<commit_after>/// <reference path="~/phaser.js" />

// Global objects
var zombie;

var balloon;

var player;

var torso;

var shotgun;

var temp;

// Global helper members
var weights = [0.01, 0.03, 0.07, 0.3, 0.59];

// bool to check if zombie has any balloons left
var hasBallon;

// bool to check if zombie has reached the Man's cloud
var atCloud;

// Initialize Phaser, and create a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'gameDiv');

// Create our 'main' state that will contain the game
var mainState = {

    preload: function ()
    {
        // This function will be executed at the beginning
        // That's where we load the game's assets

        // Change the background color of the game
        game.stage.backgroundColor = '#71c5cf';

        // Load the image of Cloud
        game.load.image('cloud', 'assets/cloud.png');

        // Load the player sprite
        game.load.image('man', 'assets/man.png');

        // Load the zombie sprite
        game.load.image('zombie', 'assets/zombie.png');

        // Load the Red Balloon sprite
        game.load.image('redBalloon', 'assets/redBalloon.png');
    },

    // This function is called after the preload function
    // Here we set up the game, display sprites, etc.
    create: function ()
    {
        // Set the physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        /*
        Cloud Object
        */
        this.cloud = this.game.add.sprite(-100, 200, 'cloud');

        game.physics.arcade.enable(this.cloud);

        this.cloud.body.immovable = true;

        // PLAYER
        // Display the player on the screen
        this.man = this.game.add.sprite(100, 210, 'man');

        // Add gravity to the man to make it fall
        game.physics.arcade.enable(this.man);

        // Call the 'shoot' function when the spacekey is hit
        var spaceKey =
            this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        spaceKey.onDown.add(this.shoot, this);

        // Main Holder Sprite :: ZOMBIE
        this.zombie = game.add.group();

        // Torso
        this.zombie.torso = game.add.sprite(0, 0, 'zombie');
        this.zombie.torso.anchor.setTo(0.5);
        this.zombie.addChild(this.zombie.torso);

        game.physics.arcade.enable(this.zombie.torso);

        //  Balloon
        this.zombie.balloon = game.add.sprite(0, -100, 'redBalloon');
        this.zombie.balloon.anchor.setTo(0.15, 0.5);
        this.zombie.addChild(this.zombie.balloon);

        /*
        Zombie Container
        */
        this.grpZombie = game.add.group();
        this.grpZombie.enableBody = true; // Add physics to the group

        this.grpZombie.createMultiple(100, 'zombie');

        this.grpZombie.add(this.zombie.torso);

        /*
        Balloon Container
        */
        this.grpBalloon = game.add.group();
        this.grpBalloon.enableBody = true;

        this.grpBalloon.createMultiple(100, 'redBalloon');

        this.grpBalloon.add(this.zombie.balloon);

        /*
        Main Container
        */
        this.grpMain = game.add.group();
        this.grpMain.enableBody = true;

        this.grpMain.add(this.grpZombie);
        this.grpMain.add(this.grpBalloon);

        // Add timer :: call addRowOfPipes() every 1.5sec
        this.timer = game.time.events.loop(3500, this.addZombieHorde, this);

        // Add timer :: Increase stats every 1.5sec
        //this.gameplayTimer = game.time.events.loop(10000, this.increaseStats, this);

        /*
        Player Score :: Label
        */

        // Create the Score object
        this.score = 0;

        this.labelScore = game.add.text(20, 20, "0", {
            font:
                "30px Arial", fill: "#ffffff" });
    },

    update: function ()
    {
        // This function is called 60 times per second
        // It contains the game's logic

        //TODO: Fix this to move the zombie left and fall onto the cloud
        // If the bird is out of the world (too high or too low), call the
        //'restartGame' function
        //if (this.zombie.inWorld == false)
        //    this.restartGame();

        // call restartGame() each time the bird collides with a pipe
        game.physics.arcade.overlap(this.man, this.pipes, this.restartGame,
            null, this);
    },

    // TODO: Create shotgun
    // TODO: Create pivot on shotgun
    // TODO: Create projectile
    // TODO: Make the projectile shoot from Shotgun
    //Make the player shoot
    shoot: function () {
        // Add a vertical velocity to the bird
        this.man.body.velocity.y = -350;
    },

    // Restart the game
    restartGame: function ()
    {
        // Start the 'main'state, which restarts the game
        game.state.start('main');
    },

    addOneZombie: function (x, y)
    {
        this.zombie = this.grpZombie.getFirstDead();

        this.zombie.reset(x, y);

        this.zombie.body.velocity.y = -20;

        this.zombie.checkWorldBounds = true;
        this.zombie.outOfBoundsKill = true;
    },

    addZombieHorde: function ()
    {
        var numberOfZombies = [5, 4, 3, 2, 1];

        var weighedList = [];
        var counter = 0;

        // loop over weights
        for (i = 0; i < 5; i++)
        {
            var amount = weights[i] * 100;

            // Push Current PLACE into array proper amount
            for (var j = 0; j < amount; j++)
            {
                // Current PLACE :: Use i counter
                counter++;
                weighedList[counter] = numberOfZombies[i];
            }
        }

        // Pick number of zombies to spawn
        var R_Index = Math.floor( Math.random() * (100 - 0 + 1) ) + 0;

        // Get RandomNumber of zombies
        R_NumberOfZombies = weighedList[R_Index];
        temp = R_NumberOfZombies;

        for (var i = 0; i < R_NumberOfZombies; i++)
        {
            var xCoord = Math.floor(Math.random() * 300) + 150;
            var yCoord = Math.floor(Math.random() * 50) + 420;

            this.addOneZombie(xCoord, yCoord + 10);
            this.addOneBalloon(xCoord + 20, yCoord + 100);
        }

        // Increment the score by 1 ea time new pipes are created
        this.score += 1;

        this.labelScore.text = this.score;
    },

    addOneBalloon: function (x, y)
    {
        this.balloon = this.grpBalloon.getFirstDead();

        this.balloon.reset(x, y);

        this.balloon.body.velocity.y = -20;

        this.balloon.checkWorldBounds = true;
        this.balloon.outOfBoundsKill = true;
    },

    increaseStats: function()
    {
        console.log("increaseStats called~");

        //weights = [0.025, 0.1, 0.15, 0.225, 0.5];
        for (var i = 0; i < weights.length; i++)
        {
            // 5th is still greater than 4th
            if (weights[4] >= 29)
            {
                // Take 5 away from 5th Index
                weights[4] -= 5;

                // Take from the last, give to second to last
                weights[3] += 5;
            }
            // 4th is still greater than 3rd
            /*
            else if (weights[2] < 30)
            {
                weights[3] -= 5;
                weights[2] += 5;
            }
            else if (weights[1] < 60)
            {
                weights[3] -= 5;
                weights[2] += 5;
            }*/
        }
    },
};

// Add and start the 'main' state to start the game
game.state.add('main', mainState);
game.state.start('main');
<|endoftext|>