<commit_before>(function( $ ){
  'use strict';
var element;
var methods = {
  setup   : function(options){
    element = this; // set element for build_containers()
    if (options.url !== undefined)
      methods.process_from_url(options);
    else
      methods.process(options);
  },
  process : function(options){
    var self = methods;

    pivot.init(options);

    if (options.skipBuildContainers === undefined || options.skipBuildContainers === false) self.build_containers();

    self.build_toggle_fields('#row-label-fields',     pivot.fields().rowLabelable, 'row-labelable');
    self.build_toggle_fields('#column-label-fields',  pivot.fields().columnLabelable, 'column-labelable');
    self.build_toggle_fields('#summary-fields', pivot.fields().summarizable,  'summary');

    methods.build_filter_list();

    $('.row-labelable').change(function(event) {
      self.update_label_fields('row');
    });

    $('.column-labelable').change(function(event) {
      self.update_label_fields('column');
    });

    $('.summary').change(function(event) {
      self.update_summary_fields();
    });

    methods.update_results();
  },
  process_from_url : function(options){
    $.ajax({
      url: options.url,
      dataType: "text",
      accepts: "text/csv",
      success: function(data, status){
        options['csv'] = data
        methods.process(options)
      }
    });
  },
  build_containers : function(){

    var containers = '
' +
                     '
' +
                     '
Filter Fields
' +
                     '

' +
                     '
' +
                     '
' +
                     '
Label Fields
' +
                     '

' +
                     '
' +
                     '
' +
                     '
Summary Fields
' +
                     '

' +
                     '
' +
                     '
';
    element.append(containers);
  },
  // Filters
  build_filter_list : function(){
    var select = '<select>'
    select += '<option></option>'
    $.each(pivot.fields().filterable, function(index, field){
      select += '<option>' + field.name + '</option>';
    })
    select += '</select>'
    $('#filter-list').empty().append(select);
    // show pre-defined filters (from init)
    $.each(pivot.filters().all(), function(fieldName, restriction){
      methods.build_filter_field(fieldName, restriction);
    });

    $('#filter-list select').change(function(){
      methods.build_filter_field($(this).val());
    })
  },
  build_filter_field : function(fieldName, selectedValue) {
    var remove_filter,
        snip,
        orderedValues = [],
        field = pivot.fields().get(fieldName);

    remove_filter = ' (X)'
    snip          = '' + field.name + remove_filter + '' +
                    '<select class="filter span3" data-field="' + field.name + '">' +
                    '<option></option>';

    for (var value in field.values){
      orderedValues.push(value);
    };

    orderedValues = orderedValues.sort();
    jQuery.each(orderedValues, function(index, value){
      var selected = "";
      if (value === selectedValue) selected = 'selected="selected"';
      snip += '<option value="' + value + '" ' + selected + '>' + field.values[value].displayValue + '</option>';
    });
    snip += '</select>'

    $('#filter-list').append('

'+ snip + '
');

    // Update field listener
    $('.filter').on('change', function(event) {
      methods.update_filtered_rows();
    });
    // remove_filter listener
    $('.remove-filter-field').click(function(){
      $(this).parents('div').first().remove();
      methods.update_filtered_rows();
    })
  },
  update_filtered_rows :  function(){
    var restrictions = {};

    $('.filter').each(function(index){
      if ($(this).val() != '')
        restrictions[$(this).attr('data-field')] = $(this).val();
    });
    pivot.filters().set(restrictions);
    methods.update_results();
  },

  //toggles

  build_toggle_fields : function(div, fields, klass){
    $(div).empty();
    $.each(fields, function(index, field){
      $(div).append('' +
                    '<input type="checkbox" class="' + klass + '" ' +
                      'data-field="' + field.name + '" ' +
                    '> ' + field.name +
                    '');
    });

    var displayFields;
    if (klass === 'row-labelable')
      displayFields = pivot.display().rowLabels().get
    else if (klass === 'column-labelable')
      displayFields = pivot.display().columnLabels().get
    else
      displayFields = pivot.display().summaries().get

    for (var fieldName in displayFields) {
      var elem = $(div + ' input[data-field=' + fieldName +']');
      elem.prop("checked", true);
      methods.orderChecked(div, elem);
    };

    // order listener
    $(div + ' input').on("click", function(){
      if (this.checked) {
        methods.orderChecked(div, this);
      } else {
        var field = $(this).parent().detach()[0];
        $(div).append( field );
      };
    });
  },
  orderChecked : function(parent, elem){
    var last_checked = $(parent + ' input:checked');     // last changed field (lcf)
    var field        = $(elem).parent().detach()[0]; // pluck item from div
    var children     = $(parent).children();

    //subtract 1 because clicked field is already checked insert plucked item into div at index
    if ((last_checked.length-1) === 0)
      $(parent).prepend( field );
    else if (children.length < last_checked.length)
      $(parent).append( field );
    else
      $(children[last_checked.length-1]).before( field );
  },
  update_results : function(){
    var results = pivot.results(),
        columns = [],
        snip    = '',
        fieldName;

    for (fieldName in pivot.display().rowLabels().get){
      columns.push(fieldName);
    };

    for (fieldName in pivot.display().columnLabels().get){
      columns.push(fieldName);
    };

    for (fieldName in pivot.display().summaries().get){
      columns.push(fieldName);
    };

    var result_table = $('#results'),
        result_rows;
    result_table.empty();

    snip += '

';

    $.each(columns, function(index, fieldName){
      snip += '' + fieldName + '	';
    });
    snip += '

';
    result_table.append(snip);

    result_rows = $('#result-rows');

    $.each(pivot.results(),function(index, row){
      snip = '
';
      $.each(columns, function(index, fieldName){
        snip += '' + row[fieldName] + '	';
      });
      snip += '
';

      result_rows.append(snip);
    });
  },
  update_label_fields :  function(type){
    var display_fields = [];

    $('.' + type + '-labelable:checked').each(function(index){
        display_fields.push($(this).attr('data-field'));
    });

    pivot.display()[type + 'Labels']().set(display_fields);

    methods.update_results();
  },
  update_summary_fields : function(){
    var summary_fields = [];

    $('.summary:checked').each(function(index){
        summary_fields.push($(this).attr('data-field'));
    });

    pivot.display().summaries().set(summary_fields);

    methods.update_results();
  }
};

  $.fn.pivot_display = function( method ) {
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + '  doesn\'t exists');
    }
  };

})( jQuery );<commit_msg>Display filtered/labeled/summarized field summary above results table if #pivot-detail is defined.<commit_after>(function( $ ){
  'use strict';
var element;
var resultsTitle;
var methods = {
  setup   : function(options){
    element = this; // set element for build_containers()
    if (options.url !== undefined)
      methods.process_from_url(options);
    else
      methods.process(options);
  },
  process : function(options){
    var self = methods;

    pivot.init(options);

    resultsTitle = options.resultsTitle;

    if (options.skipBuildContainers === undefined || options.skipBuildContainers === false) self.build_containers();

    self.build_toggle_fields('#row-label-fields',     pivot.fields().rowLabelable, 'row-labelable');
    self.build_toggle_fields('#column-label-fields',  pivot.fields().columnLabelable, 'column-labelable');
    self.build_toggle_fields('#summary-fields', pivot.fields().summarizable,  'summary');

    methods.build_filter_list();

    $('.row-labelable').change(function(event) {
      self.update_label_fields('row');
    });

    $('.column-labelable').change(function(event) {
      self.update_label_fields('column');
    });

    $('.summary').change(function(event) {
      self.update_summary_fields();
    });

    methods.update_results();
  },
  process_from_url : function(options){
    $.ajax({
      url: options.url,
      dataType: "text",
      accepts: "text/csv",
      success: function(data, status){
        options['csv'] = data
        methods.process(options)
      }
    });
  },
  build_containers : function(){

    var containers = '
' +
                     '
' +
                     '
Filter Fields
' +
                     '

' +
                     '
' +
                     '
' +
                     '
Label Fields
' +
                     '

' +
                     '
' +
                     '
' +
                     '
Summary Fields
' +
                     '

' +
                     '
' +
                     '
';
    element.append(containers);
  },
  // Filters
  build_filter_list : function(){
    var select = '<select>'
    select += '<option></option>'
    $.each(pivot.fields().filterable, function(index, field){
      select += '<option>' + field.name + '</option>';
    })
    select += '</select>'
    $('#filter-list').empty().append(select);
    // show pre-defined filters (from init)
    $.each(pivot.filters().all(), function(fieldName, restriction){
      methods.build_filter_field(fieldName, restriction);
    });

    $('#filter-list select').change(function(){
      methods.build_filter_field($(this).val());
    })
  },
  build_filter_field : function(fieldName, selectedValue) {
    var remove_filter,
        snip,
        orderedValues = [],
        field = pivot.fields().get(fieldName);

    remove_filter = ' (X)'
    snip          = '' + field.name + remove_filter + '' +
                    '<select class="filter span3" data-field="' + field.name + '">' +
                    '<option></option>';

    for (var value in field.values){
      orderedValues.push(value);
    };

    orderedValues = orderedValues.sort();
    jQuery.each(orderedValues, function(index, value){
      var selected = "";
      if (value === selectedValue) selected = 'selected="selected"';
      snip += '<option value="' + value + '" ' + selected + '>' + field.values[value].displayValue + '</option>';
    });
    snip += '</select>'

    $('#filter-list').append('

'+ snip + '
');

    // Update field listener
    $('.filter').on('change', function(event) {
      methods.update_filtered_rows();
    });
    // remove_filter listener
    $('.remove-filter-field').click(function(){
      $(this).parents('div').first().remove();
      methods.update_filtered_rows();
    })
  },
  update_filtered_rows :  function(){
    var restrictions = {};

    $('.filter').each(function(index){
      if ($(this).val() != '')
        restrictions[$(this).attr('data-field')] = $(this).val();
    });
    pivot.filters().set(restrictions);
    methods.update_results();
  },

  //toggles

  build_toggle_fields : function(div, fields, klass){
    $(div).empty();
    $.each(fields, function(index, field){
      $(div).append('' +
                    '<input type="checkbox" class="' + klass + '" ' +
                      'data-field="' + field.name + '" ' +
                    '> ' + field.name +
                    '');
    });

    var displayFields;
    if (klass === 'row-labelable')
      displayFields = pivot.display().rowLabels().get
    else if (klass === 'column-labelable')
      displayFields = pivot.display().columnLabels().get
    else
      displayFields = pivot.display().summaries().get

    for (var fieldName in displayFields) {
      var elem = $(div + ' input[data-field=' + fieldName +']');
      elem.prop("checked", true);
      methods.orderChecked(div, elem);
    };

    // order listener
    $(div + ' input').on("click", function(){
      if (this.checked) {
        methods.orderChecked(div, this);
      } else {
        var field = $(this).parent().detach()[0];
        $(div).append( field );
      };
    });
  },
  orderChecked : function(parent, elem){
    var last_checked = $(parent + ' input:checked');     // last changed field (lcf)
    var field        = $(elem).parent().detach()[0]; // pluck item from div
    var children     = $(parent).children();

    //subtract 1 because clicked field is already checked insert plucked item into div at index
    if ((last_checked.length-1) === 0)
      $(parent).prepend( field );
    else if (children.length < last_checked.length)
      $(parent).append( field );
    else
      $(children[last_checked.length-1]).before( field );
  },
  update_result_details : function(){
    var snip = '';
    if ($('#pivot-detail').length !== 0)
      snip += 'Filters: '    + pivot.utils().objectKeys( pivot.filters().all() ) + "
" +
              'Row Labels: ' + pivot.config().rowLabels  + "
" +
              'Summaries: '  + pivot.config().summaries ;
      $('#pivot-detail').html(snip);
  },
  update_results : function(){
    var results = pivot.results(),
        columns = [],
        snip    = '',
        fieldName;

    for (fieldName in pivot.display().rowLabels().get){
      columns.push(fieldName);
    };

    for (fieldName in pivot.display().columnLabels().get){
      columns.push(fieldName);
    };

    for (fieldName in pivot.display().summaries().get){
      columns.push(fieldName);
    };

    var result_table = $('#results'),
        result_rows;
    result_table.empty();

    snip += '

';

    $.each(columns, function(index, fieldName){
      snip += '' + fieldName + '	';
    });
    snip += '

';
    result_table.append(snip);

    result_rows = $('#result-rows');

    $.each(pivot.results(),function(index, row){
      snip = '
';
      $.each(columns, function(index, fieldName){
        snip += '' + row[fieldName] + '	';
      });
      snip += '
';

      result_rows.append(snip);
    });
    methods.update_result_details();
  },
  update_label_fields :  function(type){
    var display_fields = [];

    $('.' + type + '-labelable:checked').each(function(index){
        display_fields.push($(this).attr('data-field'));
    });

    pivot.display()[type + 'Labels']().set(display_fields);

    methods.update_results();
  },
  update_summary_fields : function(){
    var summary_fields = [];

    $('.summary:checked').each(function(index){
        summary_fields.push($(this).attr('data-field'));
    });

    pivot.display().summaries().set(summary_fields);

    methods.update_results();
  }
};

  $.fn.pivot_display = function( method ) {
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + '  doesn\'t exists');
    }
  };

})( jQuery );<|endoftext|>


<commit_before>import App from "../app.js";
import { pubsub } from "../helpers/subscriptionManager.js";
import * as Classes from "../classes";
import uuid from "uuid";

function addAspects(template, sim) {
  // Duplicate all of the other stuff attached to the simulator too.
  [
    "assetObjects",
    "systems",
    "decks",
    "rooms",
    "crew",
    "teams",
    "inventory",
    "dockingPorts"
  ].forEach(aspect => {
    const filterAspect = App[aspect].filter(
      a => a.simulatorId === template.simulatorId
    );
    filterAspect.forEach(a => {
      const newAspect = Object.assign({}, a);
      newAspect.id = null;
      newAspect.simulatorId = sim.id;
      // Rooms need to reference their deck
      if (aspect === "rooms") {
        const oldDeck = App.decks.find(d => d.id === newAspect.deckId);
        const deck = App.decks.find(
          d =>
            d &&
            oldDeck &&
            d.simulatorId === sim.id &&
            d.number === oldDeck.number
        );
        newAspect.deckId = deck.id;
      }
      if (aspect === "inventory") {
        // Inventory needs to reference the correct room
        const rooms = Object.keys(newAspect.roomCount);
        const newRoomCount = {};
        rooms.forEach(room => {
          const oldRoom = App.rooms.find(r => r.id === room);
          const oldDeck = App.decks.find(d => d.id === oldRoom.deckId);
          const deck = App.decks.find(
            d =>
              d &&
              oldDeck &&
              d.simulatorId === sim.id &&
              d.number === oldDeck.number
          );
          const newRoom = App.rooms.find(
            r =>
              r.name === oldRoom.name &&
              r.simulatorId === sim.id &&
              r.deckId === deck.id
          ).id;
          newRoomCount[newRoom] = newAspect.roomCount[room];
        });
        newAspect.roomCount = newRoomCount;
      }
      if (aspect === "systems") {
        // Create a new isochip for that system, if one exists
        const isochip = App.isochips.find(i => i.system === a.id);
        // Override the system ID
        newAspect.id = uuid.v4();
        if (isochip) {
          isochip.id = uuid.v4();
          isochip.system = newAspect.id;
          isochip.simulatorId = sim.id;
          App.isochips.push(new Classes.Isochip(isochip));
        }
        if (newAspect.power && newAspect.power.powerLevels.length) {
          newAspect.power.power = newAspect.power.powerLevels[0];
        }
        if (newAspect.power && !newAspect.power.powerLevels.length) {
          newAspect.power.power = 0;
        }
      }
      App[aspect].push(new Classes[newAspect.class](newAspect));
    });
  });
}
// Flight
App.on("startFlight", ({ id, name, simulators }) => {
  // Loop through all of the simulators
  const simIds = simulators.map(s => {
    const template = Object.assign(
      {},
      App.simulators.find(sim => sim.id === s.simulatorId)
    );
    template.id = null;
    const sim = new Classes.Simulator(template);
    sim.template = false;
    sim.templateId = s.simulatorId;
    sim.mission = s.missionId;
    const stationSet = App.stationSets.find(ss => ss.id === s.stationSet);
    sim.stations = stationSet.stations;
    sim.stationSet = stationSet.id;
    App.simulators.push(sim);
    addAspects(s, sim);
    return sim.id;
  });
  App.flights.push(new Classes.Flight({ id, name, simulators: simIds }));
  pubsub.publish("flightsUpdate", App.flights);
});

App.on("deleteFlight", ({ flightId }) => {
  const aspectList = [
    "assetObjects",
    "systems",
    "decks",
    "rooms",
    "crew",
    "teams",
    "inventory",
    "dockingPorts",
    "isochips",
    "coreFeed",
    "viewscreens",
    "messages"
  ];
  const flight = App.flights.find(f => f.id === flightId);
  // We need to remove all reference to this flight.
  // Loop over the simulators
  // Reset the clients
  App.clients
    .concat()
    .filter(c => c.flightId === flightId)
    .forEach(c => c.setFlight(null));
  flight.simulators.forEach(simId => {
    // Remove all of the systems, inventory, crew, etc.
    aspectList.forEach(aspect => {
      App[aspect] = App[aspect].filter(a => a.simulatorId !== simId);
    });
    App.simulators = App.simulators.filter(s => s.id !== simId);
  });
  App.flights = App.flights.filter(f => f.id !== flightId);
  pubsub.publish("flightsUpdate", App.flights);
  pubsub.publish("clientChanged", App.clients);
});

App.on("resetFlight", ({ flightId }) => {
  const aspectList = [
    "assetObjects",
    "systems",
    "decks",
    "rooms",
    "crew",
    "teams",
    "inventory",
    "dockingPorts",
    "isochips",
    "coreFeed",
    "viewscreens",
    "messages"
  ];
  const flight = App.flights.find(f => f.id === flightId);

  // Log out the clients
  App.clients
    .concat()
    .filter(c => c.flightId === flightId)
    .forEach(c => {
      c.setTraining(false);
      c.logout();
      c.setOfflineState(null);
    });

  // Create new simulators, then delete the old ones
  flight.simulators.forEach(simId => {
    const sim = App.simulators.find(s => s.id === simId);
    const tempId = sim.templateId;
    // Remove all of the systems, inventory, crew, etc.
    aspectList.forEach(aspect => {
      App[aspect] = App[aspect].filter(a => a.simulatorId !== simId);
    });
    App.simulators = App.simulators.filter(s => s.id !== simId);

    // Create new simulators based on the template
    const template = Object.assign(
      {},
      App.simulators.find(tempSim => tempSim.id === tempId)
    );
    template.id = sim.id;
    const newSim = new Classes.Simulator(template);
    newSim.template = false;
    newSim.templateId = tempId;
    newSim.mission = sim.missionId;
    newSim.stations = sim.stations;
    newSim.stationSet = sim.stationSet;
    App.simulators.push(newSim);
    addAspects({ simulatorId: tempId }, newSim);
    pubsub.publish("flightsUpdate", App.flights);
    pubsub.publish("clientChanged", App.clients);
  });
});
App.on("pauseFlight", () => {});
App.on("resumeFlight", () => {});
<commit_msg>Logout when flight is deleted<commit_after>import App from "../app.js";
import { pubsub } from "../helpers/subscriptionManager.js";
import * as Classes from "../classes";
import uuid from "uuid";

function addAspects(template, sim) {
  // Duplicate all of the other stuff attached to the simulator too.
  [
    "assetObjects",
    "systems",
    "decks",
    "rooms",
    "crew",
    "teams",
    "inventory",
    "dockingPorts"
  ].forEach(aspect => {
    const filterAspect = App[aspect].filter(
      a => a.simulatorId === template.simulatorId
    );
    filterAspect.forEach(a => {
      const newAspect = Object.assign({}, a);
      newAspect.id = null;
      newAspect.simulatorId = sim.id;
      // Rooms need to reference their deck
      if (aspect === "rooms") {
        const oldDeck = App.decks.find(d => d.id === newAspect.deckId);
        const deck = App.decks.find(
          d =>
            d &&
            oldDeck &&
            d.simulatorId === sim.id &&
            d.number === oldDeck.number
        );
        newAspect.deckId = deck.id;
      }
      if (aspect === "inventory") {
        // Inventory needs to reference the correct room
        const rooms = Object.keys(newAspect.roomCount);
        const newRoomCount = {};
        rooms.forEach(room => {
          const oldRoom = App.rooms.find(r => r.id === room);
          const oldDeck = App.decks.find(d => d.id === oldRoom.deckId);
          const deck = App.decks.find(
            d =>
              d &&
              oldDeck &&
              d.simulatorId === sim.id &&
              d.number === oldDeck.number
          );
          const newRoom = App.rooms.find(
            r =>
              r.name === oldRoom.name &&
              r.simulatorId === sim.id &&
              r.deckId === deck.id
          ).id;
          newRoomCount[newRoom] = newAspect.roomCount[room];
        });
        newAspect.roomCount = newRoomCount;
      }
      if (aspect === "systems") {
        // Create a new isochip for that system, if one exists
        const isochip = App.isochips.find(i => i.system === a.id);
        // Override the system ID
        newAspect.id = uuid.v4();
        if (isochip) {
          isochip.id = uuid.v4();
          isochip.system = newAspect.id;
          isochip.simulatorId = sim.id;
          App.isochips.push(new Classes.Isochip(isochip));
        }
        if (newAspect.power && newAspect.power.powerLevels.length) {
          newAspect.power.power = newAspect.power.powerLevels[0];
        }
        if (newAspect.power && !newAspect.power.powerLevels.length) {
          newAspect.power.power = 0;
        }
      }
      App[aspect].push(new Classes[newAspect.class](newAspect));
    });
  });
}
// Flight
App.on("startFlight", ({ id, name, simulators }) => {
  // Loop through all of the simulators
  const simIds = simulators.map(s => {
    const template = Object.assign(
      {},
      App.simulators.find(sim => sim.id === s.simulatorId)
    );
    template.id = null;
    const sim = new Classes.Simulator(template);
    sim.template = false;
    sim.templateId = s.simulatorId;
    sim.mission = s.missionId;
    const stationSet = App.stationSets.find(ss => ss.id === s.stationSet);
    sim.stations = stationSet.stations;
    sim.stationSet = stationSet.id;
    App.simulators.push(sim);
    addAspects(s, sim);
    return sim.id;
  });
  App.flights.push(new Classes.Flight({ id, name, simulators: simIds }));
  pubsub.publish("flightsUpdate", App.flights);
});

App.on("deleteFlight", ({ flightId }) => {
  const aspectList = [
    "assetObjects",
    "systems",
    "decks",
    "rooms",
    "crew",
    "teams",
    "inventory",
    "dockingPorts",
    "isochips",
    "coreFeed",
    "viewscreens",
    "messages"
  ];
  const flight = App.flights.find(f => f.id === flightId);
  // We need to remove all reference to this flight.
  // Loop over the simulators
  // Reset the clients
  App.clients
    .concat()
    .filter(c => c.flightId === flightId)
    .forEach(c => {
      c.setTraining(false);
      c.logout();
      c.setOfflineState(null);
    });
  flight.simulators.forEach(simId => {
    // Remove all of the systems, inventory, crew, etc.
    aspectList.forEach(aspect => {
      App[aspect] = App[aspect].filter(a => a.simulatorId !== simId);
    });
    App.simulators = App.simulators.filter(s => s.id !== simId);
  });
  App.flights = App.flights.filter(f => f.id !== flightId);
  pubsub.publish("flightsUpdate", App.flights);
  pubsub.publish("clientChanged", App.clients);
});

App.on("resetFlight", ({ flightId }) => {
  const aspectList = [
    "assetObjects",
    "systems",
    "decks",
    "rooms",
    "crew",
    "teams",
    "inventory",
    "dockingPorts",
    "isochips",
    "coreFeed",
    "viewscreens",
    "messages"
  ];
  const flight = App.flights.find(f => f.id === flightId);

  // Log out the clients
  App.clients
    .concat()
    .filter(c => c.flightId === flightId)
    .forEach(c => {
      c.setTraining(false);
      c.logout();
      c.setOfflineState(null);
    });

  // Create new simulators, then delete the old ones
  flight.simulators.forEach(simId => {
    const sim = App.simulators.find(s => s.id === simId);
    const tempId = sim.templateId;
    // Remove all of the systems, inventory, crew, etc.
    aspectList.forEach(aspect => {
      App[aspect] = App[aspect].filter(a => a.simulatorId !== simId);
    });
    App.simulators = App.simulators.filter(s => s.id !== simId);

    // Create new simulators based on the template
    const template = Object.assign(
      {},
      App.simulators.find(tempSim => tempSim.id === tempId)
    );
    template.id = sim.id;
    const newSim = new Classes.Simulator(template);
    newSim.template = false;
    newSim.templateId = tempId;
    newSim.mission = sim.missionId;
    newSim.stations = sim.stations;
    newSim.stationSet = sim.stationSet;
    App.simulators.push(newSim);
    addAspects({ simulatorId: tempId }, newSim);
    pubsub.publish("flightsUpdate", App.flights);
    pubsub.publish("clientChanged", App.clients);
  });
});
App.on("pauseFlight", () => {});
App.on("resumeFlight", () => {});
<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter, Match } from 'react-router'
import Landing from './Landing'
import Search from './Search'
import Details from './Details'
import preload from '../public/data.json'
import '../public/normalize.css'
import '../public/style.css'

const App = React.createClass({
  render () {
    return (
      <BrowserRouter>

          <Match exactly pattern='/' component={Landing} />
          <Match
            pattern='/search'
            component={(props) => <Search shows={preload.shows} {...props} />}

          />
          <Match
            pattern='/details/:id'
            component={(props) => {
              const shows = preload.shows.filter((show) => props.params.id === show.imdbID)
              return
            }}
          />

      </BrowserRouter>
    )
  }
})

render(<App />, document.getElementById('app'))
<commit_msg>Wrap everything under BrowserRouter with Provider and add the redux store as prop<commit_after>import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter, Match } from 'react-router'
import { Provider } from 'react-redux'
import store from './store'
import Landing from './Landing'
import Search from './Search'
import Details from './Details'
import preload from '../public/data.json'
import '../public/normalize.css'
import '../public/style.css'

const App = React.createClass({
  render () {
    return (
      <BrowserRouter>
        <Provider store={store}>

            <Match exactly pattern='/' component={Landing} />
            <Match
              pattern='/search'
              component={(props) => <Search shows={preload.shows} {...props} />}

            />
            <Match
              pattern='/details/:id'
              component={(props) => {
                const shows = preload.shows.filter((show) => props.params.id === show.imdbID)
                return
              }}
            />

        </Provider>
      </BrowserRouter>
    )
  }
})

render(<App />, document.getElementById('app'))
<|endoftext|>


<commit_before>hx.config(['$router'], function($router) {
    ko.utils.registerEventHandler(document, 'click', function(event) {
        var element = event.target;

        do {
            if(element.tagName === 'A') {
                var match = ko.utils.domData.get(element, '__matchedRoute');

                if(match) {
                    $router.navigateTo(match.route.name, match.parameters);

                    if (event.preventDefault)
                        event.preventDefault();
                    else
                        event.returnValue = false;

                    return;
                }
            }

            element = element.parentNode;
        } while(element);
    });

    /**
     * @bindingHandler navigate
     *
     * The navigate binding handler provides inter-page navigation. This binding
     * handler will typically be applied to an `a` tag, although can be applied to
     * any element as it will handle the click event on the element, it does not
     * depend on the browsers built-in linking functionality.
     *
     * The binding handler takes a single parameter, the name of the route that
     * should be navigated to, being a named route that has been registered in the
     * global $router module.
     *
     * If the route requires parameters then they can be provided by using the
     * `parameters` binding handler, which accepts an object of parameters to
     * be used to generate the URL and when navigating.
     *
     * @example
     *
     * View User 4"
     */
    koBindingHandlers.navigate = {
        init: function(element, valueAccessor) {
            var routeName = ko.utils.unwrapObservable(valueAccessor());

            $router.current.subscribe(function(current) {
                ko.utils.toggleDomNodeCssClass(element, 'active', current.route.name === routeName);
            })
        },

        update: function(element, valueAccessor, allBindingsAccessor) {
            var routeName = ko.utils.unwrapObservable(valueAccessor()),
                parameters = allBindingsAccessor()['parameters'];
                match = $router.buildMatchedRoute(routeName, parameters);

            if(match) {
                element.setAttribute('href', match.url);

                ko.dependencyDetection.ignore(function() {
                    match.authorise()
                         .fail(function() {
                            element.style.display = "none";
                        })
                });
            } else {
                element.setAttribute('href', '#');
            }

            ko.utils.domData.set(element, '__matchedRoute', match);
        }
    }
});<commit_msg>Fix global variable leak<commit_after>hx.config(['$router'], function($router) {
    ko.utils.registerEventHandler(document, 'click', function(event) {
        var element = event.target;

        do {
            if(element.tagName === 'A') {
                var match = ko.utils.domData.get(element, '__matchedRoute');

                if(match) {
                    $router.navigateTo(match.route.name, match.parameters);

                    if (event.preventDefault)
                        event.preventDefault();
                    else
                        event.returnValue = false;

                    return;
                }
            }

            element = element.parentNode;
        } while(element);
    });

    /**
     * @bindingHandler navigate
     *
     * The navigate binding handler provides inter-page navigation. This binding
     * handler will typically be applied to an `a` tag, although can be applied to
     * any element as it will handle the click event on the element, it does not
     * depend on the browsers built-in linking functionality.
     *
     * The binding handler takes a single parameter, the name of the route that
     * should be navigated to, being a named route that has been registered in the
     * global $router module.
     *
     * If the route requires parameters then they can be provided by using the
     * `parameters` binding handler, which accepts an object of parameters to
     * be used to generate the URL and when navigating.
     *
     * @example
     *
     * View User 4"
     */
    koBindingHandlers.navigate = {
        init: function(element, valueAccessor) {
            var routeName = ko.utils.unwrapObservable(valueAccessor());

            $router.current.subscribe(function(current) {
                ko.utils.toggleDomNodeCssClass(element, 'active', current.route.name === routeName);
            })
        },

        update: function(element, valueAccessor, allBindingsAccessor) {
            var routeName = ko.utils.unwrapObservable(valueAccessor()),
                parameters = allBindingsAccessor()['parameters'],
                match = $router.buildMatchedRoute(routeName, parameters);

            if(match) {
                element.setAttribute('href', match.url);

                ko.dependencyDetection.ignore(function() {
                    match.authorise()
                         .fail(function() {
                            element.style.display = "none";
                        })
                });
            } else {
                element.setAttribute('href', '#');
            }

            ko.utils.domData.set(element, '__matchedRoute', match);
        }
    }
});<|endoftext|>


<commit_before>const path = require("path");
const os = require("os");
const md5File = require("md5-file");
const fs = require("fs-extra");

const S3Source = require("../../../src/sources/s3");
const S3Client = require("../../../src/sources/s3/s3Client");
const config = require("./__fixtures__/s3.json");
const configWithPrefix = require("./__fixtures__/s3WithPrefix.json");
const packageSettings = require("../../../package.json");
const noop = require("../../../src/utils/noop");

const tmpDir = path.join(os.tmpdir(), `./${packageSettings.name}-test`);
const cacheFixture = path.join(__dirname, "./__fixtures__/cache");
const testBucketPath = path.join(__dirname, "./__fixtures__/test-bucket");
const latestFilePath = "latest.txt";
const latestFooFilePath = "foo/foo-latest.txt";
const latestBarFilePath = "bar/bar-latest.txt";

const isSameFile = (file1, file2) =>
  Promise.all([md5File(file1), md5File(file2)]).then(
    (hashes) => hashes[0] === hashes[1],
  );

describe("s3 test", function () {
  beforeEach(() => {
    fs.removeSync(`${tmpDir}/`);
  });

  beforeAll(async () => {
    const s3Client = new S3Client(config);
    await s3Client.upload(
      latestFilePath,
      path.join(testBucketPath, latestFilePath),
    );
    await s3Client.upload(
      latestFooFilePath,
      path.join(testBucketPath, latestFooFilePath),
    );
    await s3Client.upload(
      latestBarFilePath,
      path.join(testBucketPath, latestBarFilePath),
    );
  });

  it("downloads latest file", async () => {
    const s3Source = new S3Source(config, tmpDir, noop);
    const file = await s3Source.downloadLatestFile();
    const isSame = await isSameFile(
      file,
      path.join(testBucketPath, latestFilePath),
    );
    expect(isSame).toBe(true);
  });

  it("downloads latest file with prefix", async () => {
    const s3Source = new S3Source(configWithPrefix, tmpDir, noop);
    const file = await s3Source.downloadLatestFile();
    const isSame = await isSameFile(
      file,
      path.join(testBucketPath, latestBarFilePath),
    );
    expect(isSame).toBe(true);
  });

  it("uses cached file", async () => {
    await fs.copy(cacheFixture, path.join(tmpDir, "/cache/s3"));
    const s3Source = new S3Source(config, tmpDir, noop);
    const dest = await s3Source.downloadLatestFile();
    const fileExists = await fs.pathExists(dest);
    expect(fileExists).toBe(true);
  });

  it("cleans old cache", async () => {
    await fs.copy(cacheFixture, path.join(tmpDir, "/cache/s3"));
    const s3Source = new S3Source(configWithPrefix, tmpDir, noop);
    await s3Source.downloadLatestFile();
    const fileExists = await fs.pathExists(
      path.join(tmpDir, "/cache/s3/cached.txt"),
    );
    expect(fileExists).toBe(false);
  });
});
<commit_msg>Fix s3 tests<commit_after>const path = require("path");
const os = require("os");
const md5File = require("md5-file");
const fs = require("fs-extra");

const S3Source = require("../../../src/sources/s3");
const S3Client = require("../../../src/sources/s3/s3Client");
const config = require("./__fixtures__/s3.json");
const configWithPrefix = require("./__fixtures__/s3WithPrefix.json");
const packageSettings = require("../../../package.json");
const noop = require("../../../src/utils/noop");

const tmpDir = path.join(os.tmpdir(), `./${packageSettings.name}-test`);
const cacheFixture = path.join(__dirname, "./__fixtures__/cache");
const testBucketPath = path.join(__dirname, "./__fixtures__/test-bucket");
const latestFilePath = "latest.txt";
const latestFooFilePath = "foo/foo-latest.txt";
const latestBarFilePath = "bar/bar-latest.txt";

const isSameFile = (file1, file2) =>
  Promise.all([md5File(file1), md5File(file2)]).then(
    (hashes) => hashes[0] === hashes[1],
  );

const delay = (time) =>
  new Promise((resolve) => {
    setTimeout(resolve, time);
  });

describe("s3 test", function () {
  beforeEach(() => {
    fs.removeSync(`${tmpDir}/`);
  });

  beforeAll(async () => {
    const s3Client = new S3Client(config);
    await s3Client.upload(
      latestFooFilePath,
      path.join(testBucketPath, latestFooFilePath),
    );
    await s3Client.upload(
      latestBarFilePath,
      path.join(testBucketPath, latestBarFilePath),
    );

    //Upload after the others
    await delay(1500);
    await s3Client.upload(
      latestFilePath,
      path.join(testBucketPath, latestFilePath),
    );
  });

  it("downloads latest file", async () => {
    const s3Source = new S3Source(config, tmpDir, noop);
    const file = await s3Source.downloadLatestFile();
    const isSame = await isSameFile(
      file,
      path.join(testBucketPath, latestFilePath),
    );
    expect(isSame).toBe(true);
  });

  it("downloads latest file with prefix", async () => {
    const s3Source = new S3Source(configWithPrefix, tmpDir, noop);
    const file = await s3Source.downloadLatestFile();
    const isSame = await isSameFile(
      file,
      path.join(testBucketPath, latestBarFilePath),
    );
    expect(isSame).toBe(true);
  });

  it("uses cached file", async () => {
    await fs.copy(cacheFixture, path.join(tmpDir, "/cache/s3"));
    const s3Source = new S3Source(config, tmpDir, noop);
    const dest = await s3Source.downloadLatestFile();
    const fileExists = await fs.pathExists(dest);
    expect(fileExists).toBe(true);
  });

  it("cleans old cache", async () => {
    await fs.copy(cacheFixture, path.join(tmpDir, "/cache/s3"));
    const s3Source = new S3Source(configWithPrefix, tmpDir, noop);
    await s3Source.downloadLatestFile();
    const fileExists = await fs.pathExists(
      path.join(tmpDir, "/cache/s3/cached.txt"),
    );
    expect(fileExists).toBe(false);
  });
});
<|endoftext|>


<commit_before>function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest()
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.response)
                if (callback) callback(data)
            }
        }
    }
    httpRequest.open('GET', path)
    httpRequest.send()
}

var guages = []
updatePage ()

function updatePage () {
    fetchJSONFile('data.json', function(data){
        // TODO: temp fix for memory leak, need to reuse the existing elements to get them to update (and animate)
        for (i = 0; i < guages.length; i++){
                guages[i].destroy()
        }
        guages=[]

        var table  = "
"
            table += "
"
            table += "Hostname	"
            table += "CPU Load	"
            table += "RAM	"
            table += "Partitions	"
            table += "Last updated	"
            table += "
"

        for (var hostname in data) {
            table += "
"
            table += "" + hostname + "	"
            table += "<canvas id='" + hostname + "-cpu'></canvas>	"
            table += "<canvas id='" + hostname + "-ram'></canvas>	"
            table += ""
            var partitionCounter = 0
for (partition in data[hostname]["partitions"]) {
            table += "<canvas id='" + hostname + "-disk" + partitionCounter + "'></canvas>"
            partitionCounter++
}
            table += "	"
            table += "" + data[hostname]["time"] + "	"
            table += "
"
        }

        table += "
"

        document.getElementById("table").innerHTML = table

        for (var hostname in data) {
            var width = 200
            var height = 200

            try {
                var cpuLoad = (data[hostname]["cpuLoadAverage"] / data[hostname]["numberOfProcessors"]) * 100
                var cpuRadial = new RadialGauge({
                    renderTo: hostname + '-cpu',
                    width: width,
                    height: height,
                    units: 'Load Average',
                    title: "CPU",
                    value: round (data[hostname]["cpuLoadAverage"], 2),
                    minValue: 0,
                    maxValue: data[hostname]["numberOfProcessors"],
                    majorTicks: [
                        round ((data[hostname]["numberOfProcessors"] / 5) * 0, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 1, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 2, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 3, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 4, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 5, 1)
                    ],
                    highlights: [
                        { from: 0, to: data[hostname]["numberOfProcessors"]*.3, color: 'rgba(0,0,0,0)' },
                        { from: data[hostname]["numberOfProcessors"]*.3, to: data[hostname]["numberOfProcessors"]*.65, color: 'rgba(0,0,0,.05)' },
                        { from: data[hostname]["numberOfProcessors"]*.65, to: data[hostname]["numberOfProcessors"]*.85, color: 'rgba(0,0,0,.2)' },
                        { from: data[hostname]["numberOfProcessors"]*.85, to: data[hostname]["numberOfProcessors"], color: 'rgba(0,0,0,.4)' }
                    ],
                    minorTicks: 2,
                    valueBox: true
                })
                cpuRadial.draw()
                guages.push(cpuRadial);
            } catch (e) {
                console.log ("CPU Radial Guage failure: " + e)
            }

            try {
                var ramUnits = "KB" // default units for free command
                var ramTotal = data[hostname]["memoryTotal"]
                var ramUsed = data[hostname]["memoryUsed"]

                if (ramTotal / 1024 > 1) {
                    ramTotal /= 1024
                    ramUnits = "MB"
                }
                if (ramTotal / 1024 > 1) {
                    ramTotal /= 1024
                    ramUnits = "GB"
                }
                if (ramTotal / 1024 > 1) {
                    ramTotal /= 1024
                    ramUnits = "TB"
                }

                if (ramUnits == "MB") {
                    ramUsed /= 1024
                } else if (ramUnits == "GB") {
                    ramUsed /= 1024
                    ramUsed /= 1024
                } else if (ramUnits == "TB") {
                    ramUsed /= 1024
                    ramUsed /= 1024
                    ramUsed /= 1024
                }

                ramSteps = []
                ramSteps[0] = 0
                ramSteps[1] = round ((ramTotal/5) * 1, 2)
                ramSteps[2] = round ((ramTotal/5) * 2, 2)
                ramSteps[3] = round ((ramTotal/5) * 3, 2)
                ramSteps[4] = round ((ramTotal/5) * 4, 2)
                ramSteps[5] = round ((ramTotal/5) * 5, 2)

                var ramRadial = new RadialGauge({
                    renderTo: hostname + '-ram',
                    width: width,
                    height: height,
                    units: ramUnits,
                    title: "RAM",
                    value: ramUsed,
                    minValue: 0,
                    maxValue: ramTotal,
                    majorTicks: ramSteps,
                    highlights: [
                        { from: 0, to: ramTotal*.3, color: 'rgba(0,0,0,0)' },
                        { from: ramTotal*.3, to: ramTotal*.65, color: 'rgba(0,0,0,.05)' },
                        { from: ramTotal*.65, to: ramTotal*.85, color: 'rgba(0,0,0,.2)' },
                        { from: ramTotal*.85, to: ramTotal, color: 'rgba(0,0,0,.4)' }
                    ],
                    minorTicks: 2,
                    valueBox: true
                })
                ramRadial.draw()
                guages.push(ramRadial);
            } catch (e) {
                console.log ("RAM Radial Guage failure: " + e)
            }

            try {
                var partitionIndex = 0
                for (partition in data[hostname]["partitions"]) {
                    var mountAvailable = data[hostname]["partitions"][partition]["mountAvailable"]
                    var mountUsed = data[hostname]["partitions"][partition]["mountUsed"]
                    var mountTotal = data[hostname]["partitions"][partition]["mountTotal"]

                    var diskTotal = mountTotal
                    var diskUsed = mountUsed
                    var diskUnits = "KB"
                    if (diskTotal / 1024 > 1) {
                        diskTotal /= 1024
                        diskUnits = "MB"
                    }
                    if (diskTotal / 1024 > 1) {
                        diskTotal /= 1024
                        diskUnits = "GB"
                    }
                    if (diskTotal / 1024 > 1) {
                        diskTotal /= 1024
                        diskUnits = "TB"
                    }

                    if (diskUnits == "MB") {
                        diskUsed /= 1024
                    } else if (diskUnits == "GB") {
                        diskUsed /= 1024
                        diskUsed /= 1024
                    } else if (diskUnits == "TB") {
                        diskUsed /= 1024
                        diskUsed /= 1024
                        diskUsed /= 1024
                    }
                    diskSteps = []
                    diskSteps[0] = 0
                    diskSteps[1] = round ((diskTotal/5) * 1, 2)
                    diskSteps[2] = round ((diskTotal/5) * 2, 2)
                    diskSteps[3] = round ((diskTotal/5) * 3, 2)
                    diskSteps[4] = round ((diskTotal/5) * 4, 2)
                    diskSteps[5] = round ((diskTotal/5) * 5, 2)

                    var diskRadial = new LinearGauge({
                        renderTo: hostname + '-disk' + partitionIndex,
                        width: width*2,
                        height: height/2,
                        units: diskUnits,
                        title: partition,
                        value: diskUsed,
                        minValue: 0,
                        maxValue: diskTotal,
                        majorTicks: diskSteps,
                        highlights: [
                            { from: 0, to: diskTotal*.50, color: 'rgba(0,0,0,0)' },
                            { from: diskTotal*.50, to: diskTotal*.75, color: 'rgba(0,0,0,.05)' },
                            { from: diskTotal*.75, to: diskTotal*.90, color: 'rgba(0,0,0,.2)' },
                            { from: diskTotal*.90, to: diskTotal, color: 'rgba(0,0,0,.4)' }
                        ],
                        minorTicks: 2,
                        valueBox: true
                    })
                    diskRadial.draw()
                    guages.push(diskRadial);
                    partitionIndex++;
                }
            } catch (e) {
                console.log ("Disk Radial Guage failure: " + e)
            }
        }

        setTimeout( function () {
            updatePage ()
        }, 3000)
    })
}

function round(value, precision) {
    var multiplier = Math.pow(10, precision || 0);
    return Math.round(value * multiplier) / multiplier;
}
<commit_msg>add more error catching to partitions<commit_after>function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest()
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.response)
                if (callback) callback(data)
            }
        }
    }
    httpRequest.open('GET', path)
    httpRequest.send()
}

var guages = []
updatePage ()

function updatePage () {
    fetchJSONFile('data.json', function(data){
        // TODO: temp fix for memory leak, need to reuse the existing elements to get them to update (and animate)
        for (i = 0; i < guages.length; i++){
                guages[i].destroy()
        }
        guages=[]

        var table  = "
"
            table += "
"
            table += "Hostname	"
            table += "CPU Load	"
            table += "RAM	"
            table += "Partitions	"
            table += "Last updated	"
            table += "
"

        for (var hostname in data) {
            table += "
"
            table += "" + hostname + "	"
            table += "<canvas id='" + hostname + "-cpu'></canvas>	"
            table += "<canvas id='" + hostname + "-ram'></canvas>	"
            table += ""
            var partitionCounter = 0
for (partition in data[hostname]["partitions"]) {
            table += "<canvas id='" + hostname + "-disk" + partitionCounter + "'></canvas>"
            partitionCounter++
}
            table += "	"
            table += "" + data[hostname]["time"] + "	"
            table += "
"
        }

        table += "
"

        document.getElementById("table").innerHTML = table

        for (var hostname in data) {
            var width = 200
            var height = 200

            try {
                var cpuLoad = (data[hostname]["cpuLoadAverage"] / data[hostname]["numberOfProcessors"]) * 100
                var cpuRadial = new RadialGauge({
                    renderTo: hostname + '-cpu',
                    width: width,
                    height: height,
                    units: 'Load Average',
                    title: "CPU",
                    value: round (data[hostname]["cpuLoadAverage"], 2),
                    minValue: 0,
                    maxValue: data[hostname]["numberOfProcessors"],
                    majorTicks: [
                        round ((data[hostname]["numberOfProcessors"] / 5) * 0, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 1, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 2, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 3, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 4, 1),
                        round ((data[hostname]["numberOfProcessors"] / 5) * 5, 1)
                    ],
                    highlights: [
                        { from: 0, to: data[hostname]["numberOfProcessors"]*.3, color: 'rgba(0,0,0,0)' },
                        { from: data[hostname]["numberOfProcessors"]*.3, to: data[hostname]["numberOfProcessors"]*.65, color: 'rgba(0,0,0,.05)' },
                        { from: data[hostname]["numberOfProcessors"]*.65, to: data[hostname]["numberOfProcessors"]*.85, color: 'rgba(0,0,0,.2)' },
                        { from: data[hostname]["numberOfProcessors"]*.85, to: data[hostname]["numberOfProcessors"], color: 'rgba(0,0,0,.4)' }
                    ],
                    minorTicks: 2,
                    valueBox: true
                })
                cpuRadial.draw()
                guages.push(cpuRadial);
            } catch (e) {
                console.log ("CPU Radial Guage failure: " + e)
            }

            try {
                var ramUnits = "KB" // default units for free command
                var ramTotal = data[hostname]["memoryTotal"]
                var ramUsed = data[hostname]["memoryUsed"]

                if (ramTotal / 1024 > 1) {
                    ramTotal /= 1024
                    ramUnits = "MB"
                }
                if (ramTotal / 1024 > 1) {
                    ramTotal /= 1024
                    ramUnits = "GB"
                }
                if (ramTotal / 1024 > 1) {
                    ramTotal /= 1024
                    ramUnits = "TB"
                }

                if (ramUnits == "MB") {
                    ramUsed /= 1024
                } else if (ramUnits == "GB") {
                    ramUsed /= 1024
                    ramUsed /= 1024
                } else if (ramUnits == "TB") {
                    ramUsed /= 1024
                    ramUsed /= 1024
                    ramUsed /= 1024
                }

                ramSteps = []
                ramSteps[0] = 0
                ramSteps[1] = round ((ramTotal/5) * 1, 2)
                ramSteps[2] = round ((ramTotal/5) * 2, 2)
                ramSteps[3] = round ((ramTotal/5) * 3, 2)
                ramSteps[4] = round ((ramTotal/5) * 4, 2)
                ramSteps[5] = round ((ramTotal/5) * 5, 2)

                var ramRadial = new RadialGauge({
                    renderTo: hostname + '-ram',
                    width: width,
                    height: height,
                    units: ramUnits,
                    title: "RAM",
                    value: ramUsed,
                    minValue: 0,
                    maxValue: ramTotal,
                    majorTicks: ramSteps,
                    highlights: [
                        { from: 0, to: ramTotal*.3, color: 'rgba(0,0,0,0)' },
                        { from: ramTotal*.3, to: ramTotal*.65, color: 'rgba(0,0,0,.05)' },
                        { from: ramTotal*.65, to: ramTotal*.85, color: 'rgba(0,0,0,.2)' },
                        { from: ramTotal*.85, to: ramTotal, color: 'rgba(0,0,0,.4)' }
                    ],
                    minorTicks: 2,
                    valueBox: true
                })
                ramRadial.draw()
                guages.push(ramRadial);
            } catch (e) {
                console.log ("RAM Radial Guage failure: " + e)
            }

            try {
                var partitionIndex = 0
                for (partition in data[hostname]["partitions"]) {
                    try {
                        var mountAvailable = data[hostname]["partitions"][partition]["mountAvailable"]
                        var mountUsed = data[hostname]["partitions"][partition]["mountUsed"]
                        var mountTotal = data[hostname]["partitions"][partition]["mountTotal"]

                        var diskTotal = mountTotal
                        var diskUsed = mountUsed
                        var diskUnits = "KB"
                        if (diskTotal / 1024 > 1) {
                            diskTotal /= 1024
                            diskUnits = "MB"
                        }
                        if (diskTotal / 1024 > 1) {
                            diskTotal /= 1024
                            diskUnits = "GB"
                        }
                        if (diskTotal / 1024 > 1) {
                            diskTotal /= 1024
                            diskUnits = "TB"
                        }

                        if (diskUnits == "MB") {
                            diskUsed /= 1024
                        } else if (diskUnits == "GB") {
                            diskUsed /= 1024
                            diskUsed /= 1024
                        } else if (diskUnits == "TB") {
                            diskUsed /= 1024
                            diskUsed /= 1024
                            diskUsed /= 1024
                        }
                        diskSteps = []
                        diskSteps[0] = 0
                        diskSteps[1] = round ((diskTotal/5) * 1, 2)
                        diskSteps[2] = round ((diskTotal/5) * 2, 2)
                        diskSteps[3] = round ((diskTotal/5) * 3, 2)
                        diskSteps[4] = round ((diskTotal/5) * 4, 2)
                        diskSteps[5] = round ((diskTotal/5) * 5, 2)

                        var diskRadial = new LinearGauge({
                            renderTo: hostname + '-disk' + partitionIndex,
                            width: width*2,
                            height: height/2,
                            units: diskUnits,
                            title: partition,
                            value: diskUsed,
                            minValue: 0,
                            maxValue: diskTotal,
                            majorTicks: diskSteps,
                            highlights: [
                                { from: 0, to: diskTotal*.50, color: 'rgba(0,0,0,0)' },
                                { from: diskTotal*.50, to: diskTotal*.75, color: 'rgba(0,0,0,.05)' },
                                { from: diskTotal*.75, to: diskTotal*.90, color: 'rgba(0,0,0,.2)' },
                                { from: diskTotal*.90, to: diskTotal, color: 'rgba(0,0,0,.4)' }
                            ],
                            minorTicks: 2,
                            valueBox: true
                        })
                        diskRadial.draw()
                        guages.push(diskRadial);
                        partitionIndex++;
                    } catch (e) {
                        console.log ("Disk Radial Guage failure: " + e)
                    }
                }
            } catch (e) {
                console.log ("Disk Radial Guage interation failure: " + e)
            }
        }

        setTimeout( function () {
            updatePage ()
        }, 3000)
    })
}

function round(value, precision) {
    var multiplier = Math.pow(10, precision || 0);
    return Math.round(value * multiplier) / multiplier;
}
<|endoftext|>


<commit_before>
function KeyTouch(isWhite, keyIndex, velocity) {
        var _keyIndex = keyIndex;
        var _isWhite = isWhite;
        var _velocity = velocity;

        return {
            printKey: function () {
                return "note: " + _keyIndex + "
" + "isWhite: " + _isWhite +
            "
" + _velocity + "
";
            },
            setVelocity: function (velocity) {
                _velocity = velocity;
            },
            getKeyIndex: function() {
                return _keyIndex;
            }
        }
    }

var KeysLayer = {
	WHITEKEY_NUMBER : 14,
    OVERALL_BORDER : 0.02,
    BASE_NOTE_INDEX: 60,
    KEY_WIDTH : function() {
            return (1 - 2 * this.OVERALL_BORDER) / this.WHITEKEY_NUMBER;
        },
    KEYTOUCH_THRESHOLD : 0.05,
    getAllTouchedKeys: function(frame) {
        var resultList = [];
        var pointables = frame.pointables;
        for (var i = 0, pointable; pointable = pointables[i++]; ) {
            var interactionBox = frame.interactionBox;
            var normalizedPosition = interactionBox.normalizePoint(pointable.tipPosition, true);
            if (normalizedPosition[1] < 0.5 + this.KEYTOUCH_THRESHOLD &&
                normalizedPosition[1] > 0.5 - this.KEYTOUCH_THRESHOLD) {
                var key = this.findKey(normalizedPosition);

                if (key) {
                    key.setVelocity(interactionBox.normalizePoint(pointable.tipVelocity, true)[1]);
                    resultList.push(key);
                }
            }
        }
        return resultList;
    },
	findKey : function(pos) {
        var xIndex = Math.floor((pos[0] - this.OVERALL_BORDER) / this.KEY_WIDTH());
        if (pos[2] > 0.5 && xIndex >= 0 && xIndex < this.WHITEKEY_NUMBER) {
            return new KeyTouch(true, xIndex, 0);
        }

        if (pos[2] < 0.5 && xIndex >= 0 && xIndex < this.WHITEKEY_NUMBER
              && xIndex % 7 != 2 && xIndex % 7 != 6) {
            return new KeyTouch(false, xIndex, 0);
        }
    },
	PlayKeys: function(frame){
	    var pointableOutput = document.getElementById("result");
	    var pointableString = "";

	    var keyList = this.getAllTouchedKeys(frame);
	    for (var i = 0; i < keyList.length; i++) {
			piano.noteOn(0, this.BASE_NOTE_INDEX + keyList[i].getKeyIndex(), 127, 0);
	    }
	}
}<commit_msg>Only play sounds when moving<commit_after>
function KeyTouch(isWhite, keyIndex, velocity) {
        var _keyIndex = keyIndex;
        var _isWhite = isWhite;
        var _velocity = velocity;

        return {
            printKey: function () {
                return "note: " + _keyIndex + "
" + "isWhite: " + _isWhite +
            "
" + _velocity + "
";
            },
            setVelocity: function (velocity) {
                _velocity = velocity;
            },
            getKeyIndex: function() {
                return _keyIndex;
            },
            getVelocity: function() {
                return _velocity;
            }
        }
    }

var KeysLayer = {
	WHITEKEY_NUMBER : 7,
    OVERALL_BORDER : 0.02,
    BASE_NOTE_INDEX: 60,
    KEY_WIDTH : function() {
            return (1 - 2 * this.OVERALL_BORDER) / this.WHITEKEY_NUMBER;
        },
    KEYTOUCH_THRESHOLD : 0.05,
    getAllTouchedKeys: function(frame) {
        var resultList = [];
        var pointables = frame.pointables;
        for (var i = 0, pointable; pointable = pointables[i++]; ) {
            var interactionBox = frame.interactionBox;
            var normalizedPosition = interactionBox.normalizePoint(pointable.tipPosition, true);
            if (normalizedPosition[1] < 0.5 + this.KEYTOUCH_THRESHOLD &&
                normalizedPosition[1] > 0.5 - this.KEYTOUCH_THRESHOLD) {
                var key = this.findKey(normalizedPosition);

                if (key) {
                    key.setVelocity(interactionBox.normalizePoint(pointable.tipVelocity, true)[1]);
                    resultList.push(key);
                }
            }
        }
        return resultList;
    },
	findKey : function(pos) {
        var xIndex = Math.floor((pos[0] - this.OVERALL_BORDER) / this.KEY_WIDTH());
        if (pos[2] > 0.5 && xIndex >= 0 && xIndex < this.WHITEKEY_NUMBER) {
            return new KeyTouch(true, xIndex, 0);
        }

        if (pos[2] < 0.5 && xIndex >= 0 && xIndex < this.WHITEKEY_NUMBER
              && xIndex % 7 != 2 && xIndex % 7 != 6) {
            return new KeyTouch(false, xIndex, 0);
        }
    },
	PlayKeys: function(frame){
	    var pointableOutput = document.getElementById("result");
	    var pointableString = "";

	    var keyList = this.getAllTouchedKeys(frame);
	    for (var i = 0; i < keyList.length; i++) {
            if (keyList[i].getVelocity() > 0.5) {
			    piano.noteOn(0, this.BASE_NOTE_INDEX + keyList[i].getKeyIndex(), 127, 0);
            }
	    }
	}
}<|endoftext|>


<commit_before>/*

Jappix - An open social platform
These are the anonymous mode JS script for Jappix

-------------------------------------------------

License: AGPL
Authors: Valérian Saliou, Emmanuel Gil Peyrot
Last revision: 27/05/11

*/

// Connected to an anonymous session
function anonymousConnected(con) {
	logThis('Jappix (anonymous) is now connected.', 3);

	// Connected marker
	CONNECTED = true;
	CURRENT_SESSION = true;
	RECONNECT_TRY = 0;
	RECONNECT_TIMER = 0;

	// Not resumed?
	if(!RESUME) {
		// Create the app
		createTalkPage();

		// Send our first presence
		firstPresence('');

		// Set last activity stamp
		LAST_ACTIVITY = getTimeStamp();

		// Create the new groupchat
		checkChatCreate(generateXID(ANONYMOUS_ROOM, 'groupchat'), 'groupchat');

		// Remove some nasty elements for the anonymous mode
		$('.tools-mucadmin, .tools-add').remove();
	}

	// Resumed
	else {
		// Send again our presence
		presenceSend();

		// Change the title
		updateTitle();
	}

	// Remove the waiting icon
	removeGeneralWait();
}

// Disconnected from an anonymous session
function anonymousDisconnected() {
	logThis('Jappix (anonymous) is now disconnected.', 3);
}

// Logins to a anonymous account
function anonymousLogin(server) {
	try {
		// We define the http binding parameters
		oArgs = new Object();

		if(HOST_BOSH_MAIN)
			oArgs.httpbase = HOST_BOSH_MAIN;
		else
			oArgs.httpbase = HOST_BOSH;

		// We create the new http-binding connection
		con = new JSJaCHttpBindingConnection(oArgs);

		// And we handle everything that happen
		con.registerHandler('message', handleMessage);
		con.registerHandler('presence', handlePresence);
		con.registerHandler('iq', handleIQ);
		con.registerHandler('onconnect', anonymousConnected);
		con.registerHandler('onerror', handleError);
		con.registerHandler('ondisconnect', anonymousDisconnected);

		// We set the anonymous connection parameters
		oArgs = new Object();
		oArgs.domain = server;
		oArgs.authtype = 'saslanon';
		oArgs.resource = JAPPIX_RESOURCE + ' Anonymous (' + (new Date()).getTime() + ')';
		oArgs.secure = true;
		oArgs.xmllang = XML_LANG;

		// We connect !
		con.connect(oArgs);

		// Change the page title
		pageTitle('wait');
	}

	catch(e) {
		// Logs errors
		logThis('Error while anonymous loggin in: ' + e, 1);

		// Reset Jappix
		anonymousDisconnected();

		// Open an unknown error
		openThisError(2);
	}

	finally {
		return false;
	}
}

// Plugin launcher
function launchAnonymous() {
	logThis('Anonymous mode detected, connecting...', 3);

	// We add the login wait div
	showGeneralWait();

	// Get the vars
	if(LINK_VARS['r'] && (LINK_VARS['n'] !== ''))
		ANONYMOUS_ROOM = LINK_VARS['r'];

	if(LINK_VARS['n'] && (LINK_VARS['n'] !== ''))
		ANONYMOUS_NICK = LINK_VARS['n'];

	// Fire the login action
	anonymousLogin(HOST_ANONYMOUS);
}

// Launch this plugin!
$(document).ready(launchAnonymous);
<commit_msg>fixed #2629<commit_after>/*

Jappix - An open social platform
These are the anonymous mode JS script for Jappix

-------------------------------------------------

License: AGPL
Authors: Valérian Saliou, Emmanuel Gil Peyrot
Last revision: 02/10/11

*/

// Connected to an anonymous session
function anonymousConnected(con) {
	logThis('Jappix (anonymous) is now connected.', 3);

	// Connected marker
	CONNECTED = true;
	CURRENT_SESSION = true;
	RECONNECT_TRY = 0;
	RECONNECT_TIMER = 0;

	// Not resumed?
	if(!RESUME) {
		// Create the app
		createTalkPage();

		// Send our first presence
		firstPresence('');

		// Set last activity stamp
		LAST_ACTIVITY = getTimeStamp();

		// Create the new groupchat
		checkChatCreate(generateXID(ANONYMOUS_ROOM, 'groupchat'), 'groupchat');

		// Remove some nasty elements for the anonymous mode
		$('.tools-mucadmin, .tools-add').remove();
	}

	// Resumed
	else {
		// Send again our presence
		presenceSend();

		// Change the title
		updateTitle();
	}

	// Remove the waiting icon
	removeGeneralWait();
}

// Disconnected from an anonymous session
function anonymousDisconnected() {
	logThis('Jappix (anonymous) is now disconnected.', 3);
}

// Logins to a anonymous account
function anonymousLogin(server) {
	try {
		// We define the http binding parameters
		oArgs = new Object();

		if(HOST_BOSH_MAIN)
			oArgs.httpbase = HOST_BOSH_MAIN;
		else
			oArgs.httpbase = HOST_BOSH;

		// We create the new http-binding connection
		con = new JSJaCHttpBindingConnection(oArgs);

		// And we handle everything that happen
		con.registerHandler('message', handleMessage);
		con.registerHandler('presence', handlePresence);
		con.registerHandler('iq', handleIQ);
		con.registerHandler('onconnect', anonymousConnected);
		con.registerHandler('onerror', handleError);
		con.registerHandler('ondisconnect', anonymousDisconnected);

		// We set the anonymous connection parameters
		oArgs = new Object();
		oArgs.domain = server;
		oArgs.authtype = 'saslanon';
		oArgs.resource = JAPPIX_RESOURCE + ' Anonymous (' + (new Date()).getTime() + ')';
		oArgs.secure = true;
		oArgs.xmllang = XML_LANG;

		// We connect !
		con.connect(oArgs);

		// Change the page title
		pageTitle('wait');
	}

	catch(e) {
		// Logs errors
		logThis('Error while anonymous loggin in: ' + e, 1);

		// Reset Jappix
		anonymousDisconnected();

		// Open an unknown error
		openThisError(2);
	}

	finally {
		return false;
	}
}

// Plugin launcher
function launchAnonymous() {
	logThis('Anonymous mode detected, connecting...', 3);

	// We add the login wait div
	showGeneralWait();

	// Get the vars
	if(LINK_VARS['r'])
		ANONYMOUS_ROOM = LINK_VARS['r'];
	if(LINK_VARS['n'])
		ANONYMOUS_NICK = LINK_VARS['n'];

	// Fire the login action
	anonymousLogin(HOST_ANONYMOUS);
}

// Launch this plugin!
$(document).ready(launchAnonymous);
<|endoftext|>


<commit_before>'use strict';
define(
    [
        'app/config',
        'three',
        'stats',
        'app/InputHandler',
        'app/classes/Debug',
        'app/classes/Camera',
        'app/classes/GameObjectManager',
        'app/classes/Planet',
        'app/classes/Star',
        'app/classes/SpaceShip',
        'app/classes/Grid'
    ],
    function(config, THREE, Stats, InputHandler, Debug, Camera, GameObjectManager, Planet, Star, SpaceShip, Grid) {
        let stats = new Stats();
        stats.showPanel(0);
        document.body.appendChild(stats.dom);

        let scene = new THREE.Scene();

        let renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(config.canvasWidth, config.canvasHeight);
        document.getElementById('game').appendChild( renderer.domElement );

        let camera = new Camera(
            scene,
            config.camera.fov,
            config.canvasWidth / config.canvasHeight,
            0.1,
            1000,
            new THREE.Vector3(0, -465, 500),
            new THREE.Vector3(0, 0, 0)
        );

        scene.add(new THREE.AmbientLight( 0x101010 ));

        GameObjectManager.add([
            new Grid(scene, 'grid', new THREE.Vector3(0, 0, 0), 75, 75, 6, true),

            new Planet(scene,  'redPlanet',    3.301,   20, new THREE.Vector3( 0, 18, 0), true, 0xff3333),
            new Planet(scene, 'homePlanet',   48.690,  100, new THREE.Vector3(25,  0, 0), true, 0x33ff33),

            new Star(  scene,        'sol', 1.9984E8, 1400, new THREE.Vector3( 0,  0, 0),       0xffff00),

            new SpaceShip(scene, 'player', 40.0, new THREE.Vector3(0, 50, 0))
        ]);

        GameObjectManager.get('redPlanet').velocity.setX(0.2);
        GameObjectManager.get('redPlanet').velocity.setZ(0.3);

        GameObjectManager.get('homePlanet').velocity.setZ(0.03);
        GameObjectManager.get('homePlanet').velocity.setY(-0.3);

        GameObjectManager.get('player').velocity.setX(.2);
        GameObjectManager.get('player').velocity.setY(0);

        let lastFrameTime    = 0;
        let lastDeltaTValues = [];
        let smoothDeltaT     = 0;

        function update(currentFrameTime) {
            stats.begin();
            Debug.clear();

            let deltaT = currentFrameTime - lastFrameTime;
            lastFrameTime = currentFrameTime;

            // Ugly hack to prevent "jumps" when the tab lost focus
            if(deltaT > 32) deltaT = 1000/60;

            // Smooth deltaT
            while(lastDeltaTValues.length >= config.framesToSmoothDeltaT) {
                lastDeltaTValues.splice(0, 1);
            }
            lastDeltaTValues.push(deltaT);
            smoothDeltaT = lastDeltaTValues.reduce(function(prev, cur) { return prev + cur;}) / lastDeltaTValues.length;

            // Handle user input
            InputHandler.checkInput(camera);

            // Update all the objects' positions
            GameObjectManager.updatePositions(deltaT, smoothDeltaT);

            // Update all the objects
            GameObjectManager.update(deltaT, smoothDeltaT);

            // Render the scene
            renderer.render(scene, camera.camera);

            stats.end();
            requestAnimationFrame(update);
        }

        requestAnimationFrame(update);
    }
);<commit_msg>Improved grid size<commit_after>'use strict';
define(
    [
        'app/config',
        'three',
        'stats',
        'app/InputHandler',
        'app/classes/Debug',
        'app/classes/Camera',
        'app/classes/GameObjectManager',
        'app/classes/Planet',
        'app/classes/Star',
        'app/classes/SpaceShip',
        'app/classes/Grid'
    ],
    function(config, THREE, Stats, InputHandler, Debug, Camera, GameObjectManager, Planet, Star, SpaceShip, Grid) {
        let stats = new Stats();
        stats.showPanel(0);
        document.body.appendChild(stats.dom);

        let scene = new THREE.Scene();

        let renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(config.canvasWidth, config.canvasHeight);
        document.getElementById('game').appendChild( renderer.domElement );

        let camera = new Camera(
            scene,
            config.camera.fov,
            config.canvasWidth / config.canvasHeight,
            0.1,
            1000,
            new THREE.Vector3(0, -465, 500),
            new THREE.Vector3(0, 0, 0)
        );

        scene.add(new THREE.AmbientLight( 0x101010 ));

        GameObjectManager.add([
            new Grid(scene, 'grid', new THREE.Vector3(0, 0, 0), 750, 750, 60, true),

            new Planet(scene,  'redPlanet',    3.301,   20, new THREE.Vector3( 0, 18, 0), true, 0xff3333),
            new Planet(scene, 'homePlanet',   48.690,  100, new THREE.Vector3(25,  0, 0), true, 0x33ff33),

            new Star(  scene,        'sol', 1.9984E8, 1400, new THREE.Vector3( 0,  0, 0),       0xffff00),

            new SpaceShip(scene, 'player', 40.0, new THREE.Vector3(0, 50, 0))
        ]);

        GameObjectManager.get('redPlanet').velocity.setX(0.2);
        GameObjectManager.get('redPlanet').velocity.setZ(0.3);

        GameObjectManager.get('homePlanet').velocity.setZ(0.03);
        GameObjectManager.get('homePlanet').velocity.setY(-0.3);

        GameObjectManager.get('player').velocity.setX(.2);
        GameObjectManager.get('player').velocity.setY(0);

        config.maxAnisotropy = renderer.getMaxAnisotropy();

        let lastFrameTime    = 0;
        let lastDeltaTValues = [];
        let smoothDeltaT     = 0;

        function update(currentFrameTime) {
            stats.begin();
            Debug.clear();

            let deltaT = currentFrameTime - lastFrameTime;
            lastFrameTime = currentFrameTime;

            // Ugly hack to prevent "jumps" when the tab lost focus
            if(deltaT > 32) deltaT = 1000/60;

            // Smooth deltaT
            while(lastDeltaTValues.length >= config.framesToSmoothDeltaT) {
                lastDeltaTValues.splice(0, 1);
            }
            lastDeltaTValues.push(deltaT);
            smoothDeltaT = lastDeltaTValues.reduce(function(prev, cur) { return prev + cur;}) / lastDeltaTValues.length;

            // Handle user input
            InputHandler.checkInput(camera);

            // Update all the objects' positions
            GameObjectManager.updatePositions(deltaT, smoothDeltaT);

            // Update all the objects
            GameObjectManager.update(deltaT, smoothDeltaT);

            // Render the scene
            renderer.render(scene, camera.camera);

            stats.end();
            requestAnimationFrame(update);
        }

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