<commit_before>describe("Helper.Models.WebApp", function() {
    beforeEach(function() {
        BCAPI.Helper.Test.runTestServer();

        var done = false;

        // afterEach is not executed if the spec fails. So we have to clean-up data first
        runs(function() {
            var webApp = new BCAPI.Models.WebApp.App({name: "FirstWebAppFromApi"});
            webApp.destroy().always(function() { done = true; });
        });

        waitsFor(function() {
            return done;
        }, 'Delete WebApp if it exists', 60 * 1000);

        var sync = Backbone.sync;
        spyOn(Backbone, "sync").andCallFake(function(method, model, options) {

            // Prevent jQuery from failing on empty response
            // Cannot use "text", as it will not parse JSON even when needed
            options.dataType = null;
            options.contentType = 'application/json';

            return sync.apply(this, arguments);
        });
    });

    it("Create, List, Read, Delete", function() {
        var model,
            collection,
            saved = false,
            modelFetched = false,
            collectionFetched = false,
            deleted = false,
            notFound = false;

        runs(function() {
            model = new BCAPI.Models.WebApp.App({name: "FirstWebAppFromApi"});
            model.save().done(function() { saved = true; });
        });

        waitsFor(function() {
            return saved;
        }, 'Create model', 60 * 1000);

        runs(function() {
            expect(model.get('id')).toBeUndefined();

            collection = new BCAPI.Models.WebApp.AppCollection();
            collection.fetch().done(function() { collectionFetched = true });
        });

        waitsFor(function() {
            return collectionFetched;
        }, 'List collection', 1000);

        runs(function() {
            console.log(collection);
            expect(collection.models.length).toBeGreaterThan(0);

            model.fetch().done(function() { modelFetched = true });
        });

        waitsFor(function() {
            return modelFetched;
        }, 'Read model', 1000);

        runs(function() {
            expect(model.get('id')).toBeDefined(); // check that attributes have been updated

            model.destroy().done(function() { deleted = true });
        });

        waitsFor(function() {
            return deleted;
        }, 'Delete model', 1000);

        runs(function() {
            model.fetch().fail(function() { notFound = true });
        });

        waitsFor(function() {
            return notFound;
        }, 'Model does not exist anymore', 1000);
    });

    afterEach(function() {

    });
});
<commit_msg>added license header<commit_after>/*
*
* Copyright (c) 2012-2014 Adobe Systems Incorporated. All rights reserved.

* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
describe("Helper.Models.WebApp", function() {
    beforeEach(function() {
        BCAPI.Helper.Test.runTestServer();

        var done = false;

        // afterEach is not executed if the spec fails. So we have to clean-up data first
        runs(function() {
            var webApp = new BCAPI.Models.WebApp.App({name: "FirstWebAppFromApi"});
            webApp.destroy().always(function() { done = true; });
        });

        waitsFor(function() {
            return done;
        }, 'Delete WebApp if it exists', 60 * 1000);

        var sync = Backbone.sync;
        spyOn(Backbone, "sync").andCallFake(function(method, model, options) {

            // Prevent jQuery from failing on empty response
            // Cannot use "text", as it will not parse JSON even when needed
            options.dataType = null;
            options.contentType = 'application/json';

            return sync.apply(this, arguments);
        });
    });

    it("Create, List, Read, Delete", function() {
        var model,
            collection,
            saved = false,
            modelFetched = false,
            collectionFetched = false,
            deleted = false,
            notFound = false;

        runs(function() {
            model = new BCAPI.Models.WebApp.App({name: "FirstWebAppFromApi"});
            model.save().done(function() { saved = true; });
        });

        waitsFor(function() {
            return saved;
        }, 'Create model', 60 * 1000);

        runs(function() {
            expect(model.get('id')).toBeUndefined();

            collection = new BCAPI.Models.WebApp.AppCollection();
            collection.fetch().done(function() { collectionFetched = true });
        });

        waitsFor(function() {
            return collectionFetched;
        }, 'List collection', 1000);

        runs(function() {
            console.log(collection);
            expect(collection.models.length).toBeGreaterThan(0);

            model.fetch().done(function() { modelFetched = true });
        });

        waitsFor(function() {
            return modelFetched;
        }, 'Read model', 1000);

        runs(function() {
            expect(model.get('id')).toBeDefined(); // check that attributes have been updated

            model.destroy().done(function() { deleted = true });
        });

        waitsFor(function() {
            return deleted;
        }, 'Delete model', 1000);

        runs(function() {
            model.fetch().fail(function() { notFound = true });
        });

        waitsFor(function() {
            return notFound;
        }, 'Model does not exist anymore', 1000);
    });

    afterEach(function() {

    });
});
<|endoftext|>


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

goog.provide('org.apache.flex.core.ViewBase');

goog.require('org.apache.flex.core.UIBase');
goog.require('org.apache.flex.core.ValuesManager');
goog.require('org.apache.flex.events.Event');
goog.require('org.apache.flex.events.ValueChangeEvent');
goog.require('org.apache.flex.utils.MXMLDataInterpreter');

/**
 * @constructor
 * @extends {org.apache.flex.core.UIBase}
 */
org.apache.flex.core.ViewBase = function() {
  goog.base(this);

  /**
   * @private
   * @type {Array}
   */
  this.states_ = null;

  /**
   * @private
   * @type {Array}
   */
  this.transitions_ = null;

  /**
   * @private
   * @type {string}
   */
  this.currentState_ = null;

};
goog.inherits(org.apache.flex.core.ViewBase, org.apache.flex.core.UIBase);

/**
 * @expose
 * @type {Object}
 */
org.apache.flex.core.ViewBase.prototype.applicationModel = null;

/**
 * @expose
 * @type {Array}
 */
org.apache.flex.core.ViewBase.prototype.MXMLProperties = null;

/**
 * @expose
 * @type {Array}
 */
org.apache.flex.core.ViewBase.prototype.MXMLDescriptor = null;

/**
 */
org.apache.flex.core.ViewBase.prototype.addedToParent = function() {

  //goog.base(this,'addedToParent');

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLProperties(this,
      this.get_MXMLProperties());

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLInstances(this,
      this, this.get_MXMLDescriptor());

  this.dispatchEvent(new org.apache.flex.events.Event('initComplete'));
};

/**
 * @expose
 * @return {Object} The application model.
 */
org.apache.flex.core.ViewBase.prototype.get_applicationModel = function() {
  return this.applicationModel;
};

/**
 * @expose
 * @return {Array} The array of State objects.
 */
org.apache.flex.core.ViewBase.prototype.get_states = function() {
  return this.states_;
};

/**
 * @expose
 * @param {Array} value The array of State objects.
 */
org.apache.flex.core.ViewBase.prototype.set_states = function(value) {
  this.states_ = value;

  var impl = org.apache.flex.core.ValuesManager.valuesImpl.
      getValue(this, 'iStatesImpl');
  // TODO: (aharui) check if bead already exists
  this.addBead(new impl());
};

/**
 * @expose
 * @param {string} state The name of the state.
 * @return {boolean} True if state in states array.
 */
org.apache.flex.core.ViewBase.prototype.hasState = function(state) {
  for (var p in this.states_)
  {
    var s = states_[p];
    if (s.name == state)
      return true;
  }
  return false;
};

/**
 * @expose
 * @return {string} The name of the current state.
 */
org.apache.flex.core.ViewBase.prototype.get_currentState = function() {
  return this.currentState_;
};

/**
 * @expose
 * @param {string} value The name of the current state.
 */
org.apache.flex.core.ViewBase.prototype.set_currentState = function(value) {
  var event = new org.apache.flex.events.ValueChangeEvent(
      'currentStateChanged', this.currentState_, value);
  this.currentState_ = value;
  this.dispatchEvent(event);
};

/**
 * @expose
 * @return {Array} The array of transitions.
 */
org.apache.flex.core.ViewBase.prototype.get_transitions = function() {
  return this.transitions_;
};

/**
 * @expose
 * @param {Array} value The array of transitions.
 */
org.apache.flex.core.ViewBase.prototype.set_transitions = function(value) {
  this.transitions_ = value;
};

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

goog.provide('org.apache.flex.core.ViewBase');

goog.require('org.apache.flex.core.UIBase');
goog.require('org.apache.flex.core.ValuesManager');
goog.require('org.apache.flex.events.Event');
goog.require('org.apache.flex.events.ValueChangeEvent');
goog.require('org.apache.flex.utils.MXMLDataInterpreter');

/**
 * @constructor
 * @extends {org.apache.flex.core.UIBase}
 */
org.apache.flex.core.ViewBase = function() {
  goog.base(this);

  /**
   * @private
   * @type {Array}
   */
  this.states_ = null;

  /**
   * @private
   * @type {Array}
   */
  this.transitions_ = null;

  /**
   * @private
   * @type {string}
   */
  this.currentState_ = null;

};
goog.inherits(org.apache.flex.core.ViewBase, org.apache.flex.core.UIBase);

/**
 * @expose
 * @type {Object}
 */
org.apache.flex.core.ViewBase.prototype.applicationModel = null;

/**
 * @expose
 * @type {Array}
 */
org.apache.flex.core.ViewBase.prototype.MXMLProperties = null;

/**
 * @expose
 * @type {Array}
 */
org.apache.flex.core.ViewBase.prototype.MXMLDescriptor = null;

/**
 */
org.apache.flex.core.ViewBase.prototype.addedToParent = function() {

  //goog.base(this,'addedToParent');

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLProperties(this,
      this.get_MXMLProperties());

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLInstances(this,
      this, this.get_MXMLDescriptor());

  this.dispatchEvent(new org.apache.flex.events.Event('initComplete'));
};

/**
 * @expose
 * @return {Object} The application model.
 */
org.apache.flex.core.ViewBase.prototype.get_applicationModel = function() {
  return this.applicationModel;
};

/**
 * @expose
 * @return {Array} The array of State objects.
 */
org.apache.flex.core.ViewBase.prototype.get_states = function() {
  return this.states_;
};

/**
 * @expose
 * @param {Array} value The array of State objects.
 */
org.apache.flex.core.ViewBase.prototype.set_states = function(value) {
  this.states_ = value;

  var impl = org.apache.flex.core.ValuesManager.valuesImpl.
      getValue(this, 'iStatesImpl');
  // TODO: (aharui) check if bead already exists
  this.addBead(new impl());
};

/**
 * @expose
 * @param {string} state The name of the state.
 * @return {boolean} True if state in states array.
 */
org.apache.flex.core.ViewBase.prototype.hasState = function(state) {
  for (var p in this.states_)
  {
    var s = this.states_[p];
    if (s.name == state)
      return true;
  }
  return false;
};

/**
 * @expose
 * @return {string} The name of the current state.
 */
org.apache.flex.core.ViewBase.prototype.get_currentState = function() {
  return this.currentState_;
};

/**
 * @expose
 * @param {string} value The name of the current state.
 */
org.apache.flex.core.ViewBase.prototype.set_currentState = function(value) {
  var event = new org.apache.flex.events.ValueChangeEvent(
      'currentStateChanged', this.currentState_, value);
  this.currentState_ = value;
  this.dispatchEvent(event);
};

/**
 * @expose
 * @return {Array} The array of transitions.
 */
org.apache.flex.core.ViewBase.prototype.get_transitions = function() {
  return this.transitions_;
};

/**
 * @expose
 * @param {Array} value The array of transitions.
 */
org.apache.flex.core.ViewBase.prototype.set_transitions = function(value) {
  this.transitions_ = value;
};

<|endoftext|>


<commit_before>'use strict';

var extend = require('cloneextend').extend;

/**
 * Represents a strategy that extends the configuration.
 *
 * @class
 */
function ExtendConfigStrategy (extendWith) {
  this.extendWith = extendWith;
}

ExtendConfigStrategy.prototype.process = function (config, callback) {
  extend(config, this.extendWith);

  // TODO: FIX HACK! Resolve this in a more generic/re-usable way, perhaps
  // using a different object extension library.
  if(this.extendWith.cacheOptions && this.extendWith.cacheOptions.client){
    config.cacheOptions.client = this.extendWith.cacheOptions.client;
  }

  callback(null, config);
};

module.exports = ExtendConfigStrategy;
<commit_msg>Fix: don’t look for cache options if config is null<commit_after>'use strict';

var extend = require('cloneextend').extend;

/**
 * Represents a strategy that extends the configuration.
 *
 * @class
 */
function ExtendConfigStrategy (extendWith) {
  this.extendWith = extendWith;
}

ExtendConfigStrategy.prototype.process = function (config, callback) {
  extend(config, this.extendWith);

  // TODO: FIX HACK! Resolve this in a more generic/re-usable way, perhaps
  // using a different object extension library.
  if(this.extendWith && this.extendWith.cacheOptions && this.extendWith.cacheOptions.client){
    config.cacheOptions.client = this.extendWith.cacheOptions.client;
  }

  callback(null, config);
};

module.exports = ExtendConfigStrategy;
<|endoftext|>


<commit_before>/*jshint browser: true */
/*jshint unused: false */
/*global Backbone, arangoHelper, $, _, window, templateEngine, AmCharts*/

(function () {
  "use strict";

  window.DemoView = Backbone.View.extend({

    //MAP SPECIFIC VARIABLES
    // svg path for target icon
    MAPtarget: (
      "M9,0C4.029,0,0,4.029,0,9s4.029,9,9,9s9-4.029,9-9S13.971,0,9,0z M9,"
      + "15.93 c-3.83,0-6.93-3.1-6.93-6.93S5.17,2.07,9,2.07s6.93,3.1,6.93,"
      + "6.93S12.83,15.93,9,15.93 M12.5,9c0,1.933-1.567,3.5-3.5,3.5S5.5,"
      + "10.933,5.5,9S7.067,5.5,9,5.5 S12.5,7.067,12.5,9z"
    ),
    MAPicon: (
      "M23.963,20.834L17.5,9.64c-0.825-1.429-2.175-1.429-3,0L8.037,20.834c-0.825,"
      + "1.429-0.15,2.598,1.5,2.598h12.926C24.113,23.432,24.788,22.263,23.963,20.834z"
    ),
    MAPplaneicon: (
      "M19.671,8.11l-2.777,2.777l-3.837-0.861c0.362-0.505,0.916-1.683,"
      + "0.464-2.135c-0.518-0.517-1.979,0.278-2.305,0.604l-0.913,0.913L7.614,8.804l-2.021,"
      + "2.021l2.232,1.061l-0.082,0.082l1.701,1.701l0.688-0.687l3.164,1.504L9.571,"
      + "18.21H6.413l-1.137,1.138l3.6,0.948l1.83,1.83l0.947,"
      + "3.598l1.137-1.137V21.43l3.725-3.725l1.504,3.164l-0.687,0.687l1.702,"
      + "1.701l0.081-0.081l1.062,2.231l2.02-2.02l-0.604-2.689l0.912-0.912c0.326-0.326,"
      + "1.121-1.789,0.604-2.306c-0.452-0.452-1.63,0.101-2.135,"
      + "0.464l-0.861-3.838l2.777-2.777c0.947-0.947,3.599-4.862,2.62-5.839C24.533,"
      + "4.512,20.618,7.163,19.671,8.11z"
    ),
    //ICON FROM http://raphaeljs.com/icons/#plane
    MAPcolor: "black",

    lineColors: [
      'rgb(255,255,229)',
      'rgb(255,247,188)',
      'rgb(254,227,145)',
      'rgb(254,196,79)',
      'rgb(254,153,41)',
      'rgb(236,112,20)',
      'rgb(204,76,2)',
      'rgb(153,52,4)',
      'rgb(102,37,6)'
    ],

    keyToLongLat: {},

    //QUERIES SECTION
    queries: [
      {
        name: "All Flights from SFO",
        value: "here is the place of the actual query statement"
      },
      {
        name: "All Flights from JFK",
        value: "here is the place of the actual query statement"
      },
      {
        name: "All Flights from DFW",
        value: "here is the place of the actual query statement"
      },
      {
        name: "All Flights from ATL",
        value: "here is the place of the actual query statement"
      },
      {
        name: "All Flights from CWA",
        value: "here is the place of the actual query statement"
      }
    ],

    el: '#content',

    initialize: function () {
      this.airportCollection = new window.Airports();
      window.HASS = this; // <--- BITTE ?!? ;)
    },

    events: {
      "change #flightQuerySelect" : "runSelectedQuery"
    },

    template: templateEngine.createTemplate("demoView.ejs"),

    render: function () {
      $(this.el).html(this.template.render({}));
      //TODO: this.renderMap([]);
      this.renderAvailableQueries();

      var callback = function() {

        var airport, airports = [];

        this.airportCollection.each(function(model) {
          airport = model.toJSON();
          airports.push(airport);
        });
        var preparedData = this.prepareData(airports);
        this.renderMap(preparedData);
        // this.renderDummy();

      }.bind(this);

      this.airportCollection.getAirports(callback);

      return this;
    },

    renderAvailableQueries: function() {
      var position = 0;
      _.each(this.queries, function(query) {
        $('#flightQuerySelect').append('<option position="' + position + '">' + query.name + '</option>');
        position++;
      });
    },

    runSelectedQuery: function() {
      //TODO: RUN SELECTED QUERY IF USER SELECTS QUERY

      var currentQueryPos = $( "#flightQuerySelect option:selected" ).attr('position');
      if (currentQueryPos === "0") {
        this.loadAirportData("SFO");
      }
      if (currentQueryPos === "1") {
        this.loadAirportData("JFK");
      }
      if (currentQueryPos === "2") {
        this.loadAirportData("DFW");
      }
      if (currentQueryPos === "3") {
        this.loadAirportData("ATL");
      }
      if (currentQueryPos === "4") {
        this.loadAirportData("CWA");
      }
    },

    loadAirportData: function(airport) {
      var self = this;
      this.airportCollection.getFlightsForAirport(airport, function(list) {

        self.removeFlightLines(false);

        var i = 0;
        for (i = 0; i < list.length; ++i) {
          self.addFlightLine(
            airport,
            list[i].Dest,
            list[i].count,
            self.calculateFlightColor(list.length, i),
            self.calculateFlightWidth(list.length, i)
          );
        }
        self.map.validateData();
      });
    },

    calculateFlightWidth: function(length, pos) {
      var intervallWidth = length/2;
      return Math.floor(pos/intervallWidth) + 2;
    },

    calculateFlightColor: function(length, pos) {
      var intervallColor = length/this.lineColors.length;
      return this.lineColors[Math.floor(pos/intervallColor)];
    },

    prepareData: function (data) {

      var self = this, imageData = [];

      _.each(data, function(airport) {
        imageData.push({
          id: airport._key,
          latitude: airport.Latitude,
          longitude: airport.Longitude,
          svgPath: self.MAPtarget,
          color: "#222222",
          scale: 0.5,
          selectedScale: 2.5,
          title: airport.City + " [" + airport._key + "]
" + airport.Name,
          rollOverColor: "#ff8f35",
        });
        self.keyToLongLat[airport._key] = {
          lon: airport.Longitude,
          lat: airport.Latitude
        };
      });
      imageData.push({
        color: "#FF0000",
        lines: [{
          latitudes: [ 51.5002, 50.4422 ],
          longitudes: [ -0.1262, 30.5367 ]
        }]
      });
      return imageData;
    },

    createFlightEntry: function(from, to, weight, lineColor, lineWidth) {
      return {
        longitudes: [
          this.keyToLongLat[from].lon,
          this.keyToLongLat[to].lon,
        ],
        latitudes: [
          this.keyToLongLat[from].lat,
          this.keyToLongLat[to].lat
        ],
        title: from + " - " + to + "
" + weight,
        color: lineColor,
        thickness: lineWidth
      };
    },

    renderMap: function(imageData) {

      var self = this;
      self.lines = [];

      AmCharts.theme = AmCharts.themes.light;
      self.map = AmCharts.makeChart("demo-mapdiv", {
        type: "map",
        dragMap: true,
        creditsPosition: "bottom-left",
        pathToImages: "img/ammap/",
        dataProvider: {
          map: "usa2High",
          lines: self.lines,
          images: imageData,
          getAreasFromMap: true
        },
      	balloon: {
          adjustBorderColor: true,
          balloonColor: "#ffffff",
      		color: "#000000",
      		cornerRadius: 5,
      		fillColor: "#ffffff",
          fillAlpha: 0.75,
          borderThickness: 1.5,
          borderColor: "#88A049",
          borderAlpha: 0.4,
          shadowAlpha: 0,
          fontSize: 10,
          verticalPadding: 3,
          horizontalPadding: 6
      	},
        areasSettings: {
          autoZoom: false,
          balloonText: "",
          selectedColor: self.MAPcolor
        },
        linesSettings: {
          color: "#ff8f35", // 7629C4
          alpha: 0.75,
          thickness: 2
        },
        linesAboveImages: true
      });
    },

    removeFlightLines: function(shouldRender) {
      this.lines.length = 0;

      if (shouldRender) {
        this.map.validateData();
      }
    },

    addFlightLines: function(lines) {
      //TODO: lines = array, values: from, to, count, lineColor, lineWidth
      _.each(lines, function(line) {
        addFlightLine(line.from, line.to, line.count, line.lineColor, line.lineWidth, false);
      });
    },

    addFlightLine: function(from, to, count, lineColor, lineWidth) {
      console.log("Adding", from, to, count);
      this.lines.push(this.createFlightEntry(from, to, count, lineColor, lineWidth));
    }

  });
}());
<commit_msg>added click event function for map object<commit_after>/*jshint browser: true */
/*jshint unused: false */
/*global Backbone, arangoHelper, $, _, window, templateEngine, AmCharts*/

(function () {
  "use strict";

  window.DemoView = Backbone.View.extend({

    //MAP SPECIFIC VARIABLES
    // svg path for target icon
    MAPtarget: (
      "M9,0C4.029,0,0,4.029,0,9s4.029,9,9,9s9-4.029,9-9S13.971,0,9,0z M9,"
      + "15.93 c-3.83,0-6.93-3.1-6.93-6.93S5.17,2.07,9,2.07s6.93,3.1,6.93,"
      + "6.93S12.83,15.93,9,15.93 M12.5,9c0,1.933-1.567,3.5-3.5,3.5S5.5,"
      + "10.933,5.5,9S7.067,5.5,9,5.5 S12.5,7.067,12.5,9z"
    ),
    MAPicon: (
      "M23.963,20.834L17.5,9.64c-0.825-1.429-2.175-1.429-3,0L8.037,20.834c-0.825,"
      + "1.429-0.15,2.598,1.5,2.598h12.926C24.113,23.432,24.788,22.263,23.963,20.834z"
    ),
    MAPplaneicon: (
      "M19.671,8.11l-2.777,2.777l-3.837-0.861c0.362-0.505,0.916-1.683,"
      + "0.464-2.135c-0.518-0.517-1.979,0.278-2.305,0.604l-0.913,0.913L7.614,8.804l-2.021,"
      + "2.021l2.232,1.061l-0.082,0.082l1.701,1.701l0.688-0.687l3.164,1.504L9.571,"
      + "18.21H6.413l-1.137,1.138l3.6,0.948l1.83,1.83l0.947,"
      + "3.598l1.137-1.137V21.43l3.725-3.725l1.504,3.164l-0.687,0.687l1.702,"
      + "1.701l0.081-0.081l1.062,2.231l2.02-2.02l-0.604-2.689l0.912-0.912c0.326-0.326,"
      + "1.121-1.789,0.604-2.306c-0.452-0.452-1.63,0.101-2.135,"
      + "0.464l-0.861-3.838l2.777-2.777c0.947-0.947,3.599-4.862,2.62-5.839C24.533,"
      + "4.512,20.618,7.163,19.671,8.11z"
    ),
    //ICON FROM http://raphaeljs.com/icons/#plane
    MAPcolor: "black",

    lineColors: [
      'rgb(255,255,229)',
      'rgb(255,247,188)',
      'rgb(254,227,145)',
      'rgb(254,196,79)',
      'rgb(254,153,41)',
      'rgb(236,112,20)',
      'rgb(204,76,2)',
      'rgb(153,52,4)',
      'rgb(102,37,6)'
    ],

    keyToLongLat: {},

    //QUERIES SECTION
    queries: [
      {
        name: "All Flights from SFO",
        value: "here is the place of the actual query statement"
      },
      {
        name: "All Flights from JFK",
        value: "here is the place of the actual query statement"
      },
      {
        name: "All Flights from DFW",
        value: "here is the place of the actual query statement"
      },
      {
        name: "All Flights from ATL",
        value: "here is the place of the actual query statement"
      },
      {
        name: "All Flights from CWA",
        value: "here is the place of the actual query statement"
      }
    ],

    el: '#content',

    initialize: function () {
      this.airportCollection = new window.Airports();
      window.HASS = this; // <--- BITTE ?!? ;)
    },

    events: {
      "change #flightQuerySelect" : "runSelectedQuery"
    },

    template: templateEngine.createTemplate("demoView.ejs"),

    render: function () {
      $(this.el).html(this.template.render({}));
      //TODO: this.renderMap([]);
      this.renderAvailableQueries();

      var callback = function() {

        var airport, airports = [];

        this.airportCollection.each(function(model) {
          airport = model.toJSON();
          airports.push(airport);
        });
        var preparedData = this.prepareData(airports);
        this.renderMap(preparedData);
        // this.renderDummy();

      }.bind(this);

      this.airportCollection.getAirports(callback);

      return this;
    },

    renderAvailableQueries: function() {
      var position = 0;
      _.each(this.queries, function(query) {
        $('#flightQuerySelect').append('<option position="' + position + '">' + query.name + '</option>');
        position++;
      });
    },

    runSelectedQuery: function() {
      //TODO: RUN SELECTED QUERY IF USER SELECTS QUERY

      var currentQueryPos = $( "#flightQuerySelect option:selected" ).attr('position');
      if (currentQueryPos === "0") {
        this.loadAirportData("SFO");
      }
      if (currentQueryPos === "1") {
        this.loadAirportData("JFK");
      }
      if (currentQueryPos === "2") {
        this.loadAirportData("DFW");
      }
      if (currentQueryPos === "3") {
        this.loadAirportData("ATL");
      }
      if (currentQueryPos === "4") {
        this.loadAirportData("CWA");
      }
    },

    loadAirportData: function(airport) {
      var self = this;
      this.airportCollection.getFlightsForAirport(airport, function(list) {

        self.removeFlightLines(false);

        var i = 0;
        for (i = 0; i < list.length; ++i) {
          self.addFlightLine(
            airport,
            list[i].Dest,
            list[i].count,
            self.calculateFlightColor(list.length, i),
            self.calculateFlightWidth(list.length, i)
          );
        }
        self.map.validateData();
      });
    },

    calculateFlightWidth: function(length, pos) {
      var intervallWidth = length/2;
      return Math.floor(pos/intervallWidth) + 2;
    },

    calculateFlightColor: function(length, pos) {
      var intervallColor = length/this.lineColors.length;
      return this.lineColors[Math.floor(pos/intervallColor)];
    },

    prepareData: function (data) {

      var self = this, imageData = [];

      _.each(data, function(airport) {
        imageData.push({
          id: airport._key,
          latitude: airport.Latitude,
          longitude: airport.Longitude,
          svgPath: self.MAPtarget,
          color: "#222222",
          scale: 0.5,
          selectedScale: 2.5,
          title: airport.City + " [" + airport._key + "]
" + airport.Name,
          rollOverColor: "#ff8f35",
        });
        self.keyToLongLat[airport._key] = {
          lon: airport.Longitude,
          lat: airport.Latitude
        };
      });
      imageData.push({
        color: "#FF0000",
        lines: [{
          latitudes: [ 51.5002, 50.4422 ],
          longitudes: [ -0.1262, 30.5367 ]
        }]
      });
      return imageData;
    },

    createFlightEntry: function(from, to, weight, lineColor, lineWidth) {
      return {
        longitudes: [
          this.keyToLongLat[from].lon,
          this.keyToLongLat[to].lon,
        ],
        latitudes: [
          this.keyToLongLat[from].lat,
          this.keyToLongLat[to].lat
        ],
        title: from + " - " + to + "
" + weight,
        color: lineColor,
        thickness: lineWidth
      };
    },

    renderMap: function(imageData) {

      var self = this;
      self.lines = [];

      AmCharts.theme = AmCharts.themes.light;
      self.map = AmCharts.makeChart("demo-mapdiv", {
        type: "map",
        dragMap: true,
        creditsPosition: "bottom-left",
        pathToImages: "img/ammap/",
        dataProvider: {
          map: "usa2High",
          lines: self.lines,
          images: imageData,
          getAreasFromMap: true
        },
        clickMapObject: function(mapObject){
          console.log(mapObject);
        },
      	balloon: {
          adjustBorderColor: true,
          balloonColor: "#ffffff",
      		color: "#000000",
      		cornerRadius: 5,
      		fillColor: "#ffffff",
          fillAlpha: 0.75,
          borderThickness: 1.5,
          borderColor: "#88A049",
          borderAlpha: 0.4,
          shadowAlpha: 0,
          fontSize: 10,
          verticalPadding: 3,
          horizontalPadding: 6
      	},
        areasSettings: {
          autoZoom: false,
          balloonText: "",
          selectedColor: self.MAPcolor
        },
        linesSettings: {
          color: "#ff8f35", // 7629C4
          alpha: 0.75,
          thickness: 2
        },
        linesAboveImages: true
      });
    },

    removeFlightLines: function(shouldRender) {
      this.lines.length = 0;

      if (shouldRender) {
        this.map.validateData();
      }
    },

    addFlightLines: function(lines) {
      //TODO: lines = array, values: from, to, count, lineColor, lineWidth
      _.each(lines, function(line) {
        addFlightLine(line.from, line.to, line.count, line.lineColor, line.lineWidth, false);
      });
    },

    addFlightLine: function(from, to, count, lineColor, lineWidth) {
      console.log("Adding", from, to, count);
      this.lines.push(this.createFlightEntry(from, to, count, lineColor, lineWidth));
    }

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


<commit_before>Imcms.define("imcms-rest-api", ["imcms", "jquery", "imcms-ajax-request-data-decorator"], function (Imcms, $, decorate) {

    var API_PREFIX = "/api";

    function ajax(data, callback) {
        return $.ajax({
            url: Imcms.contextPath + API_PREFIX + this.url,
            type: this.type,
            data: decorate(data),
            contentType: "application/json",
            success: callback
        });
    }

    function post(path) {
        return ajax.bind({url: path, type: "POST"});
    }

    function get(path) {
        return ajax.bind({url: path, type: "GET"});
    }

    function put(path) {
        return ajax.bind({url: path, type: "PUT"});
    }

    function remove(path) {
        return ajax.bind({url: path, type: "DELETE"});
    }

    var API = function (url) {
        this.create = post(url);
        this.read = get(url);
        this.update = put(url);
        this.remove = remove(url);
    };

    return {

        API: API,

        create: function (path, data, callback) {
            post(path)(data, callback);
        },

        read: function (path, data, callback) {
            get(path)(data, callback);
        },

        update: function (path, data, callback) {
            put(path)(data, callback);
        },

        remove: function (path, data, callback) {
            remove(path)(data, callback);
        }

    }
});<commit_msg>IMCMS-233 - Apply new UI to the admin panel and editors: - Cleaned ajax config.<commit_after>Imcms.define("imcms-rest-api", ["imcms", "jquery", "imcms-ajax-request-data-decorator"], function (Imcms, $, decorate) {

    var API_PREFIX = "/api";

    function ajax(data, callback) {
        return $.ajax({
            url: Imcms.contextPath + API_PREFIX + this.url,
            type: this.type,
            data: decorate(data),
            success: callback
        });
    }

    function post(path) {
        return ajax.bind({url: path, type: "POST"});
    }

    function get(path) {
        return ajax.bind({url: path, type: "GET"});
    }

    function put(path) {
        return ajax.bind({url: path, type: "PUT"});
    }

    function remove(path) {
        return ajax.bind({url: path, type: "DELETE"});
    }

    var API = function (url) {
        this.create = post(url);
        this.read = get(url);
        this.update = put(url);
        this.remove = remove(url);
    };

    return {

        API: API,

        create: function (path, data, callback) {
            post(path)(data, callback);
        },

        read: function (path, data, callback) {
            get(path)(data, callback);
        },

        update: function (path, data, callback) {
            put(path)(data, callback);
        },

        remove: function (path, data, callback) {
            remove(path)(data, callback);
        }

    }
});<|endoftext|>


<commit_before>import Element from '../../Element';
import runloop from '../../../../global/runloop';
import { toArray } from '../../../../utils/array';

function valueContains ( selectValue, optionValue ) {
	let i = selectValue.length;
	while ( i-- ) {
		if ( selectValue[i] == optionValue ) return true;
	}
}

export default class Select extends Element {
	constructor ( options ) {
		super( options );
		this.options = [];
	}

	render ( target, occupants ) {
		super.render( target, occupants );
		this.sync();

		const node = this.node;

		let i = node.options.length;
		while ( i-- ) {
			node.options[i].defaultSelected = node.options[i].selected;
		}

		this.rendered = true;
	}

	sync () {
		const selectNode = this.node;

		if ( !selectNode ) return;

		const options = toArray( selectNode.options );

		const selectValue = this.getAttribute( 'value' );
		const isMultiple = this.getAttribute( 'multiple' );

		// If the <select> has a specified value, that should override
		// these options
		if ( selectValue !== undefined ) {
			let optionWasSelected;

			options.forEach( o => {
				const optionValue = o._ractive ? o._ractive.value : o.value;
				const shouldSelect = isMultiple ? valueContains( selectValue, optionValue ) : selectValue == optionValue;

				if ( shouldSelect ) {
					optionWasSelected = true;
				}

				o.selected = shouldSelect;
			});

			if ( !optionWasSelected && !isMultiple ) {
				if ( options[0] ) {
					options[0].selected = true;
				}

				if ( this.binding ) {
					this.binding.forceUpdate();
				}
			}
		}

		// Otherwise the value should be initialised according to which
		// <option> element is selected, if twoway binding is in effect
		else if ( this.binding ) {
			this.binding.forceUpdate();
		}
	}

	update () {
		super.update();
		this.sync();
	}
}
<commit_msg>prune unneeded import<commit_after>import Element from '../../Element';
import { toArray } from '../../../../utils/array';

function valueContains ( selectValue, optionValue ) {
	let i = selectValue.length;
	while ( i-- ) {
		if ( selectValue[i] == optionValue ) return true;
	}
}

export default class Select extends Element {
	constructor ( options ) {
		super( options );
		this.options = [];
	}

	render ( target, occupants ) {
		super.render( target, occupants );
		this.sync();

		const node = this.node;

		let i = node.options.length;
		while ( i-- ) {
			node.options[i].defaultSelected = node.options[i].selected;
		}

		this.rendered = true;
	}

	sync () {
		const selectNode = this.node;

		if ( !selectNode ) return;

		const options = toArray( selectNode.options );

		const selectValue = this.getAttribute( 'value' );
		const isMultiple = this.getAttribute( 'multiple' );

		// If the <select> has a specified value, that should override
		// these options
		if ( selectValue !== undefined ) {
			let optionWasSelected;

			options.forEach( o => {
				const optionValue = o._ractive ? o._ractive.value : o.value;
				const shouldSelect = isMultiple ? valueContains( selectValue, optionValue ) : selectValue == optionValue;

				if ( shouldSelect ) {
					optionWasSelected = true;
				}

				o.selected = shouldSelect;
			});

			if ( !optionWasSelected && !isMultiple ) {
				if ( options[0] ) {
					options[0].selected = true;
				}

				if ( this.binding ) {
					this.binding.forceUpdate();
				}
			}
		}

		// Otherwise the value should be initialised according to which
		// <option> element is selected, if twoway binding is in effect
		else if ( this.binding ) {
			this.binding.forceUpdate();
		}
	}

	update () {
		super.update();
		this.sync();
	}
}
<|endoftext|>


<commit_before>JSJaCHPC_NKEYS = 10; // number of keys to generate

function JSJaCHttpPollingConnection(oDbg) {
	this.base = JSJaCConnection;
	this.base(oDbg);

	this.keys = null;
	this.sendQueue = new Array();

	this.connect = JSJaCHPCConnect;
	this.disconnect = JSJaCHPCDisconnect;
	this._prepareResponse = JSJaCHPCPrepareResponse;
	this._getRequestString = JSJaCHPCGetRequestString;
	this._setupRequest = JSJaCHPCSetupRequest;
}

function JSJaCHPCKeys(oDbg) {
	var seed = Math.random();

	this.k = new Array();
	this.k[0] = this.username+seed;
	this.oDbg = oDbg;

	for (var i=1; i<JSJaCHPC_NKEYS; i++) {
		this.k[i] = b64_sha1(this.k[i-1]);
		if (this.oDbg)
			oDbg.log(i+": "+this.k[i],4);
	}

	this.indexAt = JSJaCHPC_NKEYS-1;
	this.getKey = function() { return this.k[this.indexAt--]; };
	this.lastKey = function() { return (this.indexAt == 0); };
}

function JSJaCHPCSetupRequest(async) {
 	var req = XmlHttp.create();

	req.open("POST",this.http_base,async);

	req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	return req;
}

function JSJaCHPCGetRequestString(aJSJaCPacket) {
	var reqstr = this.sid+';'+this.keys.getKey();
	if (this.keys.lastKey()) {
		this.keys = new JSJaCHPCKeys(this.oDbg);
		reqstr += ';'+this.keys.getKey();
	}
	reqstr += ',';
	if (aJSJaCPacket)
		reqstr += aJSJaCPacket.getDoc().xml;
	return reqstr;
}

function JSJaCHPCPrepareResponse() {
	var response = XmlDocument.create();
	response.loadXML(""+this.req.responseText+"");
	return response;
}

function JSJaCHPCConnect(http_base,server,username,resource,pass) {
	// initial request to get sid and streamid

	this.http_base = http_base || '/';
	this.server = server || 'localhost';
	this.username = username;
	this.resource = resource;
	this.pass = pass;

	this.keys = new JSJaCHPCKeys(this.oDbg); // generate first set of keys
	key = this.keys.getKey();

	this.req = XmlHttp.create();

	this.req.open("POST",this.http_base,false);
	this.req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	this.oDbg.log("0;"+key+",<stream:stream to='"+this.server+"' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>",4);
	this.req.send("0;"+key+",<stream:stream to='"+this.server+"' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>");

	this.oDbg.log(this.req.responseText,4);

	// extract session ID
	var aPList = this.req.getResponseHeader('Set-Cookie');
	aPList = aPList.split(";");
	for (var i=0;i<aPList.length;i++) {
		aArg = aPList[i].split("=");
		if (aArg[0] == 'ID')
			this.sid = aArg[1];
	}
	this.oDbg.log("got sid: "+this.sid,2);
	// extract stream id used for non-SASL authentication
	if (this.req.responseText.match(/id='(.+?)'/))
			this.streamid = RegExp.$1;
	this.oDbg.log("got streamid: "+this.streamid,2);

	this._connected = true;
	this._doAuth();
}

function JSJaCHPCDisconnect() {
	this.req = XmlHttp.create();
	this.req.open("POST",this.http_base,false);
	this.req.send(this.sid+";"+this.keys.getKey()+",</stream:stream>");
	this.oDbg.log("Disconnected: "+this.req.responseText,2);
	this._connected = false;
	this.handleEvent('ondisconnect');
}
<commit_msg>disconnect on invalid response clear timeout on disconnect<commit_after>JSJaCHPC_NKEYS = 10; // number of keys to generate

function JSJaCHttpPollingConnection(oDbg) {
	this.base = JSJaCConnection;
	this.base(oDbg);

	this.keys = null;
	this.sendQueue = new Array();

	this.connect = JSJaCHPCConnect;
	this.disconnect = JSJaCHPCDisconnect;
	this._prepareResponse = JSJaCHPCPrepareResponse;
	this._getRequestString = JSJaCHPCGetRequestString;
	this._setupRequest = JSJaCHPCSetupRequest;
}

function JSJaCHPCKeys(oDbg) {
	var seed = Math.random();

	this.k = new Array();
	this.k[0] = this.username+seed;
	this.oDbg = oDbg;

	for (var i=1; i<JSJaCHPC_NKEYS; i++) {
		this.k[i] = b64_sha1(this.k[i-1]);
		if (this.oDbg)
			oDbg.log(i+": "+this.k[i],4);
	}

	this.indexAt = JSJaCHPC_NKEYS-1;
	this.getKey = function() { return this.k[this.indexAt--]; };
	this.lastKey = function() { return (this.indexAt == 0); };
}

function JSJaCHPCSetupRequest(async) {
 	var req = XmlHttp.create();

	req.open("POST",this.http_base,async);

	req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	return req;
}

function JSJaCHPCGetRequestString(aJSJaCPacket) {
	var reqstr = this.sid+';'+this.keys.getKey();
	if (this.keys.lastKey()) {
		this.keys = new JSJaCHPCKeys(this.oDbg);
		reqstr += ';'+this.keys.getKey();
	}
	reqstr += ',';
	if (aJSJaCPacket)
		reqstr += aJSJaCPacket.getDoc().xml;
	return reqstr;
}

function JSJaCHPCPrepareResponse() {
	// handle error
	if (!this.req.responseXML && this.req.responseText != '') {
		this.oDbg.log("invalid response (can't parse):" + this.req.responseText,1);
		clearTimeout(this.timeout); // remove timer
		this._connected = false;
		this.oDbg.log("Disconnected.",1);
		this.handleEvent('ondisconnect');
		return null;
	}

	var response = XmlDocument.create();

	response.loadXML(""+this.req.responseText+"");
	return response;
}

function JSJaCHPCConnect(http_base,server,username,resource,pass) {
	// initial request to get sid and streamid

	this.http_base = http_base || '/';
	this.server = server || 'localhost';
	this.username = username;
	this.resource = resource;
	this.pass = pass;

	this.keys = new JSJaCHPCKeys(this.oDbg); // generate first set of keys
	key = this.keys.getKey();

	this.req = XmlHttp.create();

	this.req.open("POST",this.http_base,false);
	this.req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	this.oDbg.log("0;"+key+",<stream:stream to='"+this.server+"' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>",4);
	this.req.send("0;"+key+",<stream:stream to='"+this.server+"' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>");

	this.oDbg.log(this.req.responseText,4);

	// extract session ID
	var aPList = this.req.getResponseHeader('Set-Cookie');
	aPList = aPList.split(";");
	for (var i=0;i<aPList.length;i++) {
		aArg = aPList[i].split("=");
		if (aArg[0] == 'ID')
			this.sid = aArg[1];
	}
	this.oDbg.log("got sid: "+this.sid,2);
	// extract stream id used for non-SASL authentication
	if (this.req.responseText.match(/id='(.+?)'/))
			this.streamid = RegExp.$1;
	this.oDbg.log("got streamid: "+this.streamid,2);

	this._connected = true;
	this._doAuth();
}

function JSJaCHPCDisconnect() {
	clearTimeout(this.timeout); // remove timer
	this.req = XmlHttp.create();
	this.req.open("POST",this.http_base,false);
	this.req.send(this.sid+";"+this.keys.getKey()+",</stream:stream>");
	this.oDbg.log("Disconnected: "+this.req.responseText,2);
	this._connected = false;
	this.handleEvent('ondisconnect');
}
<|endoftext|>


<commit_before>function getCount() {
	setInterval(function() {
		//http://107.170.149.67/reps/count
     $.getJSON("http://uclaradio.com/analytics/getCount", function(response) {
      console.log(response);
      $('#currentListeners').html(response);
     }).fail()
   }, 5000);

}

$(document).ready(function(){
	getCount();
	console.log('get');
})<commit_msg>faster response<commit_after>function getCount() {
	setInterval(function() {
		//http://107.170.149.67/reps/count
     $.getJSON("http://uclaradio.com/analytics/getCount", function(response) {
      console.log(response);
      $('#currentListeners').html(response);
     }).fail()
   }, 1000);

}

$(document).ready(function(){
	getCount();
	console.log('get');
})<|endoftext|>


<commit_before>var state = { };

const setAppState = newState => {
  console.log("Pre merge app state is", state, newState);
  state = { ...state, ...newState };
  console.log("App state is", state);
};

const getAppState = () => {
  return state;
};

export {
  getAppState,
  setAppState,
};
<commit_msg>Remove logging statements from global state.<commit_after>var state = { };

const setAppState = newState => {
  state = { ...state, ...newState };
};

const getAppState = () => {
  return state;
};

export {
  getAppState,
  setAppState,
};
<|endoftext|>


<commit_before>(function(){

var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// Global Crypto object
var Crypto = window.Crypto = {};

// Crypto utilities
var util = Crypto.util = {

	// Bit-wise rotate left
	rotl: function (n, b) {
		return (n << b) | (n >>> (32 - b));
	},

	// Bit-wise rotate right
	rotr: function (n, b) {
		return (n << (32 - b)) | (n >>> b);
	},

	// Swap big-endian to little-endian and vice versa
	endian: function (n) {

		// If number given, swap endian
		if (n.constructor == Number) {
			return util.rotl(n,  8) & 0x00FF00FF |
			       util.rotl(n, 24) & 0xFF00FF00;
		}

		// Else, assume array and swap all items
		for (var i = 0; i < n.length; i++)
			n[i] = util.endian(n[i]);
		return n;

	},

	// Generate an array of any length of random bytes
	randomBytes: function (n) {
		for (var bytes = []; n > 0; n--)
			bytes.push(Math.floor(Math.random() * 256));
		return bytes;
	},

	// Convert a byte array to big-endian 32-bits words
	bytesToWords: function (bytes) {
		for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
			words[b >>> 5] |= bytes[i] << (24 - b % 32);
		return words;
	},

	// Convert big-endian 32-bit words to a byte array
	wordsToBytes: function (words) {
		for (var bytes = [], b = 0; b < words.length * 32; b += 8)
			bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
		return bytes;
	},

	// Convert a byte array to a hex string
	bytesToHex: function (bytes) {
		for (var hex = [], i = 0; i < bytes.length; i++) {
			hex.push((bytes[i] >>> 4).toString(16));
			hex.push((bytes[i] & 0xF).toString(16));
		}
		return hex.join("");
	},

	// Convert a hex string to a byte array
	hexToBytes: function (hex) {
		for (var bytes = [], c = 0; c < hex.length; c += 2)
			bytes.push(parseInt(hex.substr(c, 2), 16));
		return bytes;
	},

	// Convert a byte array to a base-64 string
	bytesToBase64: function (bytes) {

		// Use browser-native function if it exists
		if (typeof btoa == "function") return btoa(Binary.bytesToString(bytes));

		for(var base64 = [], i = 0; i < bytes.length; i += 3) {
			var triplet = bytes[i] << 16;
			if (i + 1 < bytes.length) triplet |= bytes[i + 1] << 8;
			if (i + 2 < bytes.length) triplet |= bytes[i + 2];
			for(var j = 0; j < 4; j++)
				base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));
		}

		// Add padding
		while (base64.length % 4 != 0) base64.push("=");

		return base64.join("");

	},

	// Convert a base-64 string to a byte array
	base64ToBytes: function (base64) {

		// Use browser-native function if it exists
		if (typeof atob == "function") return Binary.stringToBytes(atob(base64));

		// Remove non-base-64 characters
		base64 = base64.replace(/[^A-Z0-9+\/]/ig, "");

		for (var bytes = [], i = 0; i < base64.length; i++) {
			switch (i % 4) {
				case 1:
					bytes.push((base64map.indexOf(base64.charAt(i - 1)) << 2) |
					           (base64map.indexOf(base64.charAt(i)) >>> 4));
					break;
				case 2:
					bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0xF) << 4) |
					           (base64map.indexOf(base64.charAt(i)) >>> 2));
					break;
				case 3:
					bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0x3) << 6) |
					           (base64map.indexOf(base64.charAt(i))));
					break;
			}
		}

		return bytes;

	}

};

// Crypto mode namespace
Crypto.mode = {};

// Crypto character encodings
var charenc = Crypto.charenc = {};

// UTF-8 encoding
var UTF8 = charenc.UTF8 = {

	// Convert a string to a byte array
	stringToBytes: function (str) {
		return Binary.stringToBytes(unescape(encodeURIComponent(str)));
	},

	// Convert a byte array to a string
	bytesToString: function (bytes) {
		return decodeURIComponent(escape(Binary.bytesToString(bytes)));
	}

};

// Binary encoding
var Binary = charenc.Binary = {

	// Convert a string to a byte array
	stringToBytes: function (str) {
		for (var bytes = [], i = 0; i < str.length; i++)
			bytes.push(str.charCodeAt(i));
		return bytes;
	},

	// Convert a byte array to a string
	bytesToString: function (bytes) {
		for (var str = [], i = 0; i < bytes.length; i++)
			str.push(String.fromCharCode(bytes[i]));
		return str.join("");
	}

};

})();
<commit_msg>Fixed base64 padding.<commit_after>(function(){

var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// Global Crypto object
var Crypto = window.Crypto = {};

// Crypto utilities
var util = Crypto.util = {

	// Bit-wise rotate left
	rotl: function (n, b) {
		return (n << b) | (n >>> (32 - b));
	},

	// Bit-wise rotate right
	rotr: function (n, b) {
		return (n << (32 - b)) | (n >>> b);
	},

	// Swap big-endian to little-endian and vice versa
	endian: function (n) {

		// If number given, swap endian
		if (n.constructor == Number) {
			return util.rotl(n,  8) & 0x00FF00FF |
			       util.rotl(n, 24) & 0xFF00FF00;
		}

		// Else, assume array and swap all items
		for (var i = 0; i < n.length; i++)
			n[i] = util.endian(n[i]);
		return n;

	},

	// Generate an array of any length of random bytes
	randomBytes: function (n) {
		for (var bytes = []; n > 0; n--)
			bytes.push(Math.floor(Math.random() * 256));
		return bytes;
	},

	// Convert a byte array to big-endian 32-bits words
	bytesToWords: function (bytes) {
		for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
			words[b >>> 5] |= bytes[i] << (24 - b % 32);
		return words;
	},

	// Convert big-endian 32-bit words to a byte array
	wordsToBytes: function (words) {
		for (var bytes = [], b = 0; b < words.length * 32; b += 8)
			bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
		return bytes;
	},

	// Convert a byte array to a hex string
	bytesToHex: function (bytes) {
		for (var hex = [], i = 0; i < bytes.length; i++) {
			hex.push((bytes[i] >>> 4).toString(16));
			hex.push((bytes[i] & 0xF).toString(16));
		}
		return hex.join("");
	},

	// Convert a hex string to a byte array
	hexToBytes: function (hex) {
		for (var bytes = [], c = 0; c < hex.length; c += 2)
			bytes.push(parseInt(hex.substr(c, 2), 16));
		return bytes;
	},

	// Convert a byte array to a base-64 string
	bytesToBase64: function (bytes) {

		// Use browser-native function if it exists
		if (typeof btoa == "function") return btoa(Binary.bytesToString(bytes));

		for(var base64 = [], i = 0; i < bytes.length; i += 3) {
			var triplet = bytes[i] << 16;
			if (i + 1 < bytes.length) triplet |= bytes[i + 1] << 8;
			if (i + 2 < bytes.length) triplet |= bytes[i + 2];
			for(var j = 0; j < 4; j++) {
				if (i * 8 + j * 6 <= bytes.length * 8)
					base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));
				else base64.push("=");
			}
		}

		return base64.join("");

	},

	// Convert a base-64 string to a byte array
	base64ToBytes: function (base64) {

		// Use browser-native function if it exists
		if (typeof atob == "function") return Binary.stringToBytes(atob(base64));

		// Remove non-base-64 characters
		base64 = base64.replace(/[^A-Z0-9+\/]/ig, "");

		for (var bytes = [], i = 0; i < base64.length; i++) {
			switch (i % 4) {
				case 1:
					bytes.push((base64map.indexOf(base64.charAt(i - 1)) << 2) |
					           (base64map.indexOf(base64.charAt(i)) >>> 4));
					break;
				case 2:
					bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0xF) << 4) |
					           (base64map.indexOf(base64.charAt(i)) >>> 2));
					break;
				case 3:
					bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0x3) << 6) |
					           (base64map.indexOf(base64.charAt(i))));
					break;
			}
		}

		return bytes;

	}

};

// Crypto mode namespace
Crypto.mode = {};

// Crypto character encodings
var charenc = Crypto.charenc = {};

// UTF-8 encoding
var UTF8 = charenc.UTF8 = {

	// Convert a string to a byte array
	stringToBytes: function (str) {
		return Binary.stringToBytes(unescape(encodeURIComponent(str)));
	},

	// Convert a byte array to a string
	bytesToString: function (bytes) {
		return decodeURIComponent(escape(Binary.bytesToString(bytes)));
	}

};

// Binary encoding
var Binary = charenc.Binary = {

	// Convert a string to a byte array
	stringToBytes: function (str) {
		for (var bytes = [], i = 0; i < str.length; i++)
			bytes.push(str.charCodeAt(i));
		return bytes;
	},

	// Convert a byte array to a string
	bytesToString: function (bytes) {
		for (var str = [], i = 0; i < bytes.length; i++)
			str.push(String.fromCharCode(bytes[i]));
		return str.join("");
	}

};

})();
<|endoftext|>


<commit_before>// March 2012, Franziska Hinkelmann, Mike Stillman, and Lars Kastner
//
// This is server-side JavaScript, intended to be run with Node.js.
// This file defines a Node.js server for serving 'tryM2'.
//   run
//      node m2server.js
// in a terminal in this directory.
// Then in a browser, use:
//      http://localhost:8000/
// Required Node.js libraries: cookies.  Install via:
//   npm install cookies, or sudo npm install -g cookies
// Required on path: M2

//
// A message on / : possibly creates a cookie, and serves back index.html
//   and related js/css/png files
// A POST message on /chat: input should be Macaulay2 commands to perform.
// A message on /chat: start an event emitter, which will return the output of
// the M2 process.

var http = require('http');  // NodeJS HTTP server API
var Cookies = require("cookies");

// The HTML file for the chat client. Used below.
var clientui = require('fs').readFileSync("index.html");
var totalUsers = 0;

// An array of Client objects.  Each has an M2 process, and a response object
// It is possible that this.m2 is not defined, and/or that this.eventStream is not
// defined.
var clients = {};

function Client(m2process, resp) {
    this.m2 = m2process;
    this.eventStream = resp;
}

startUser = function(cookies) {
    totalUsers = totalUsers + 1;
    var clientID = Math.random()*1000000;
    clientID = Math.floor(clientID);
    clientID = "user" + clientID.toString(10);
    cookies.set( "tryM2", clientID, { httpOnly: false } );
    clients[clientID] = new Client();
    return clientID;
}

startM2Process = function() {
    var spawn = require('child_process').spawn;
    console.log("spawning...");
    var m2 = spawn('M2');
    //var m2 = spawn('sudo', ['../sandbox/sandbox', '../../sandbox-dir', 'bin/M2', '-q', '-e', 'limitResources()']);
    //var m2 = spawn('../sandbox/sandbox', ['../../sandbox-dir', 'bin/M2', '-q', '-e', 'limitResources()']);
    m2.running = true;
    m2.stdout.setEncoding("utf8");
    m2.stderr.setEncoding("utf8");
    console.log('Spawned m2 pid: ' + m2.pid);
    m2.on('exit', function(code, signal) {
        m2.running = false;
        console.log("M2 exited");
    });
    return m2;
};

// can only be called when client.eventStream is set
// if client.m2 is not null, kill it, then start a new process
// attach M2 output to client.eventStream
startM2 = function(client) {
    if (client.m2) {
        client.m2.kill();
        console.log("In startM2(), killed M2 with PID " + client.m2.pid);
    }
    // client is an object of type Client
    client.m2 = startM2Process();
    console.log("starting sending M2 output to eventStream");
    var ondata = function(data) {
        //console.log('ondata: ' + data);
        message = 'data: ' + data.replace(/\n/g, '\ndata: ') + "\r\n\r\n";
        if (!client.eventStream) { // fatal error, should not happen
            console.log("Error: No event stream in Start M2");
            throw "Error: No client.eventStream in Start M2";
        }
        client.eventStream.write(message);
    };
    client.m2.stdout.on('data', ondata);
    client.m2.stderr.on('data', ondata);

};

getCurrentClientID = function(cookies) {
    var clientID = cookies.get("tryM2");
    //console.log("Client has cookie value: " + clientID);

    // Start new user for users coming with invalid, i.e., old, cookie
    if (!clients[clientID]) {
        console.log("startUser");
        clientID = startUser(cookies);
    }
    return clientID;
};

var stats = function(response) {
    // to do: authorization
     response.writeHead(200, {"Content-Type": "text/html"});
     var currentUsers = 0;
     for( var c in clients) {
         if(clients.hasOwnProperty(c))
                 currentUsers = currentUsers + 1;
     }
     response.write('<link rel="stylesheet" href="m2.css" type="text/css" media="screen">' );
     response.write('
Macaulay2 User Statistics
');
     response.write("There are currently " + currentUsers + " users using M2.
" );
     response.write("In total, there were " + totalUsers + " users since the server started.
");
     response.write("Enjoy M2!");
     response.end();
}

// Send a comment to the clients every 20 seconds so they don't
// close the connection and then reconnect
setInterval(function() {
    for (var prop in clients) {
        if (clients.hasOwnProperty(prop)
            && clients[prop]
            && clients[prop].eventStream) {
            clients[prop].eventStream.write(":ping\n");
        }
    }
}, 20000);

loadFile = function(url, response) {
    var filename = "";
    console.log("User requested: " + url.pathname);
    // If the request was for "/", send index.html
    if (url.pathname === "/" ) {
        filename = __dirname + "/index.html";
    }
    else {
        filename = __dirname + url.pathname;
    }

    filename = require('path').normalize(filename);
    if (filename.indexOf(__dirname) != 0 ) {
        console.log( "requested file, " + filename + " is not in " + __dirname);
        response.writeHead(404,{"Content-Type": "text/html"});
        response.write( '
Page not found. Return to TryM2
');
        response.end();
        return;
    }
    console.log("We are trying to serve: " + filename);

    var ext = require('path').extname(filename);
    var contentType = "text/html";
    if ( /\.css|\.png|\.html|\.js/.test(ext)) {
        switch(ext) {
        case ".css":
            contentType = 'text/css';
            break;
        }
        if ( require('path').existsSync(filename)) {
            data = require('fs').readFileSync(filename);
            response.writeHead(200, {"Content-Type": contentType});
            response.write(data);
        }
        else {
            console.error("There was an error opening the file:");
            console.log(err);
            response.writeHead(404,{"Content-Type": "text/html"});
            response.write( '
Page not found. Return to TryM2
');
        }
        response.end();
        return;
    }
    // send css files requested by index.html
    response.writeHead(404,{"Content-Type": "text/html"});
    response.write( '
Page not found. Return to TryM2
');
    response.end();
}

// Client starts eventStream to obtain M2 output and start M2
startSource = function(clientID, request, response) {
    response.writeHead(200, {'Content-Type': "text/event-stream" });
    if (!clients[clientID].eventStream) {
        clients[clientID].eventStream = response;
        startM2(clients[clientID]);
    }

    // If the client closes the connection, remove client from the list of active clients
    request.connection.on("end", function() {
        console.log("close connection: clients[" + clientID + "]");
        if( clients[clientID] && clients[clientID].m2) {
            clients[clientID].m2.kill();
            clients[clientID].m2 = null;
        }
        delete clients[clientID];
        response.end();
    });
};

chatAction = function(clientID, request, response) {
    request.setEncoding("utf8");
    var body = "";
    // When we get a chunk of data, add it to the body
    request.on("data", function(chunk) { body += chunk; });

    // Send input to M2 when we have received the complete body
    request.on("end", function() {
        if(!clients[clientID].m2) {
            console.log("No M2 object for client " + clientID + ", starting M2.");
            startM2(clients[clientID]);
        }
        if (!clients[clientID].m2.running) {
            console.log("No running M2 for client " + clientID + ", waiting for user to send /restart.");
            response.writeHead(200);
            response.end();
            return;
        }
        try {
            //console.log("Send M2 input: " + body);
            clients[clientID].m2.stdin.write(body);
        }
        catch (err) {
            throw ("Internal error: nothing to write to?!");
            // send error back to user, user needs to start eventStream and resend 'body'
            //response.writeHead(200, {
            //  'notEventSourceError': 'No socket for client...' });
            //response.end();
            return;
        }
        response.writeHead(200);
        response.end();
    });
};

restartAction = function(clientID, request, response) {
    console.log("received: /restart from " + clientID);
    startM2(clients[clientID]);
    response.writeHead(200);
    response.end();
};

interruptAction = function(clientID, request, response)  {
    console.log("received: /interrupt from " + clientID);
    if (clients[clientID] && clients[clientID].m2) {
        clients[clientID].m2.kill('SIGINT');
    }
    response.writeHead(200);
    response.end();
};

// server reacts to these requests
var actions = [];
actions['/chat'] = chatAction;
actions['/restart'] = restartAction;
actions['/interrupt'] = interruptAction;
actions['/'] = false;
actions['/startSourceEvent'] = startSource;
actions['/admin'] = false;

// Create a new server
var server = new http.Server();
// When the server gets a new request, run this function
server.on("request", function (request, response) {
    //console.log( "got on");
    var url = require('url').parse(request.url);

    if (url.pathname === "/admin") {
        stats(response);
        return;
    }

    if (url.pathname === "/"  || actions[url.pathname] == undefined ) {
        loadFile (url, response);
        return;
    }

    var cookies = new Cookies(request, response);
    var clientID = getCurrentClientID(cookies);

    if(url.pathname == '/startSourceEvent') {
        actions[url.pathname](clientID, request, response);
        return;
    }

    if (!clients[clientID].eventStream ) {
         console.log("Send notEventSourceError back to user.");
         response.writeHead(200, {'notEventSourceError': 'No socket for client...' });
         response.end();
         return;
    }

    actions[url.pathname](clientID, request, response);
});

// Run the server on port 8000. Connect to http://localhost:8000/ to use it.
console.log("Listening on port 8000...");
server.listen(8000);
<commit_msg>clean up toturial, lesson 3<commit_after>// March 2012, Franziska Hinkelmann, Mike Stillman, and Lars Kastner
//
// This is server-side JavaScript, intended to be run with Node.js.
// This file defines a Node.js server for serving 'tryM2'.
//   run
//      node m2server.js
// in a terminal in this directory.
// Then in a browser, use:
//      http://localhost:8000/
// Required Node.js libraries: cookies.  Install via:
//   npm install cookies, or sudo npm install -g cookies
// Required on path: M2

//
// A message on / : possibly creates a cookie, and serves back index.html
//   and related js/css/png files
// A POST message on /chat: input should be Macaulay2 commands to perform.
// A message on /chat: start an event emitter, which will return the output of
// the M2 process.

var http = require('http');  // NodeJS HTTP server API
var Cookies = require("cookies");

// The HTML file for the chat client. Used below.
var clientui = require('fs').readFileSync("index.html");
var totalUsers = 0;

// An array of Client objects.  Each has an M2 process, and a response object
// It is possible that this.m2 is not defined, and/or that this.eventStream is not
// defined.
var clients = {};

function Client(m2process, resp) {
    this.m2 = m2process;
    this.eventStream = resp;
}

startUser = function(cookies) {
    totalUsers = totalUsers + 1;
    var clientID = Math.random()*1000000;
    clientID = Math.floor(clientID);
    clientID = "user" + clientID.toString(10);
    cookies.set( "tryM2", clientID, { httpOnly: false } );
    clients[clientID] = new Client();
    return clientID;
}

startM2Process = function() {
    var spawn = require('child_process').spawn;
    console.log("spawning...");
    //var m2 = spawn('M2');
    //var m2 = spawn('sudo', ['../sandbox/sandbox', '../../sandbox-dir', 'bin/M2', '-q', '-e', 'limitResources()']);
    var m2 = spawn('../sandbox/sandbox', ['../../sandbox-dir', 'bin/M2', '-q', '-e', 'limitResources()']);
    m2.running = true;
    m2.stdout.setEncoding("utf8");
    m2.stderr.setEncoding("utf8");
    console.log('Spawned m2 pid: ' + m2.pid);
    m2.on('exit', function(code, signal) {
        m2.running = false;
        console.log("M2 exited");
    });
    return m2;
};

// can only be called when client.eventStream is set
// if client.m2 is not null, kill it, then start a new process
// attach M2 output to client.eventStream
startM2 = function(client) {
    if (client.m2) {
        client.m2.kill();
        console.log("In startM2(), killed M2 with PID " + client.m2.pid);
    }
    // client is an object of type Client
    client.m2 = startM2Process();
    console.log("starting sending M2 output to eventStream");
    var ondata = function(data) {
        //console.log('ondata: ' + data);
        message = 'data: ' + data.replace(/\n/g, '\ndata: ') + "\r\n\r\n";
        if (!client.eventStream) { // fatal error, should not happen
            console.log("Error: No event stream in Start M2");
            throw "Error: No client.eventStream in Start M2";
        }
        client.eventStream.write(message);
    };
    client.m2.stdout.on('data', ondata);
    client.m2.stderr.on('data', ondata);

};

getCurrentClientID = function(cookies) {
    var clientID = cookies.get("tryM2");
    //console.log("Client has cookie value: " + clientID);

    // Start new user for users coming with invalid, i.e., old, cookie
    if (!clients[clientID]) {
        console.log("startUser");
        clientID = startUser(cookies);
    }
    return clientID;
};

var stats = function(response) {
    // to do: authorization
     response.writeHead(200, {"Content-Type": "text/html"});
     var currentUsers = 0;
     for( var c in clients) {
         if(clients.hasOwnProperty(c))
                 currentUsers = currentUsers + 1;
     }
     response.write('<link rel="stylesheet" href="m2.css" type="text/css" media="screen">' );
     response.write('
Macaulay2 User Statistics
');
     response.write("There are currently " + currentUsers + " users using M2.
" );
     response.write("In total, there were " + totalUsers + " users since the server started.
");
     response.write("Enjoy M2!");
     response.end();
}

// Send a comment to the clients every 20 seconds so they don't
// close the connection and then reconnect
setInterval(function() {
    for (var prop in clients) {
        if (clients.hasOwnProperty(prop)
            && clients[prop]
            && clients[prop].eventStream) {
            clients[prop].eventStream.write(":ping\n");
        }
    }
}, 20000);

loadFile = function(url, response) {
    var filename = "";
    console.log("User requested: " + url.pathname);
    // If the request was for "/", send index.html
    if (url.pathname === "/" ) {
        filename = __dirname + "/index.html";
    }
    else {
        filename = __dirname + url.pathname;
    }

    filename = require('path').normalize(filename);
    if (filename.indexOf(__dirname) != 0 ) {
        console.log( "requested file, " + filename + " is not in " + __dirname);
        response.writeHead(404,{"Content-Type": "text/html"});
        response.write( '
Page not found. Return to TryM2
');
        response.end();
        return;
    }
    console.log("We are trying to serve: " + filename);

    var ext = require('path').extname(filename);
    var contentType = "text/html";
    if ( /\.css|\.png|\.html|\.js/.test(ext)) {
        switch(ext) {
        case ".css":
            contentType = 'text/css';
            break;
        }
        if ( require('path').existsSync(filename)) {
            data = require('fs').readFileSync(filename);
            response.writeHead(200, {"Content-Type": contentType});
            response.write(data);
        }
        else {
            console.error("There was an error opening the file:");
            console.log(err);
            response.writeHead(404,{"Content-Type": "text/html"});
            response.write( '
Page not found. Return to TryM2
');
        }
        response.end();
        return;
    }
    // send css files requested by index.html
    response.writeHead(404,{"Content-Type": "text/html"});
    response.write( '
Page not found. Return to TryM2
');
    response.end();
}

// Client starts eventStream to obtain M2 output and start M2
startSource = function(clientID, request, response) {
    response.writeHead(200, {'Content-Type': "text/event-stream" });
    if (!clients[clientID].eventStream) {
        clients[clientID].eventStream = response;
        startM2(clients[clientID]);
    }

    // If the client closes the connection, remove client from the list of active clients
    request.connection.on("end", function() {
        console.log("close connection: clients[" + clientID + "]");
        if( clients[clientID] && clients[clientID].m2) {
            clients[clientID].m2.kill();
            clients[clientID].m2 = null;
        }
        delete clients[clientID];
        response.end();
    });
};

chatAction = function(clientID, request, response) {
    request.setEncoding("utf8");
    var body = "";
    // When we get a chunk of data, add it to the body
    request.on("data", function(chunk) { body += chunk; });

    // Send input to M2 when we have received the complete body
    request.on("end", function() {
        if(!clients[clientID].m2) {
            console.log("No M2 object for client " + clientID + ", starting M2.");
            startM2(clients[clientID]);
        }
        if (!clients[clientID].m2.running) {
            console.log("No running M2 for client " + clientID + ", waiting for user to send /restart.");
            response.writeHead(200);
            response.end();
            return;
        }
        try {
            //console.log("Send M2 input: " + body);
            clients[clientID].m2.stdin.write(body);
        }
        catch (err) {
            throw ("Internal error: nothing to write to?!");
            // send error back to user, user needs to start eventStream and resend 'body'
            //response.writeHead(200, {
            //  'notEventSourceError': 'No socket for client...' });
            //response.end();
            return;
        }
        response.writeHead(200);
        response.end();
    });
};

restartAction = function(clientID, request, response) {
    console.log("received: /restart from " + clientID);
    startM2(clients[clientID]);
    response.writeHead(200);
    response.end();
};

interruptAction = function(clientID, request, response)  {
    console.log("received: /interrupt from " + clientID);
    if (clients[clientID] && clients[clientID].m2) {
        clients[clientID].m2.kill('SIGINT');
    }
    response.writeHead(200);
    response.end();
};

// server reacts to these requests
var actions = [];
actions['/chat'] = chatAction;
actions['/restart'] = restartAction;
actions['/interrupt'] = interruptAction;
actions['/'] = false;
actions['/startSourceEvent'] = startSource;
actions['/admin'] = false;

// Create a new server
var server = new http.Server();
// When the server gets a new request, run this function
server.on("request", function (request, response) {
    //console.log( "got on");
    var url = require('url').parse(request.url);

    if (url.pathname === "/admin") {
        stats(response);
        return;
    }

    if (url.pathname === "/"  || actions[url.pathname] == undefined ) {
        loadFile (url, response);
        return;
    }

    var cookies = new Cookies(request, response);
    var clientID = getCurrentClientID(cookies);

    if(url.pathname == '/startSourceEvent') {
        actions[url.pathname](clientID, request, response);
        return;
    }

    if (!clients[clientID].eventStream ) {
         console.log("Send notEventSourceError back to user.");
         response.writeHead(200, {'notEventSourceError': 'No socket for client...' });
         response.end();
         return;
    }

    actions[url.pathname](clientID, request, response);
});

// Run the server on port 8000. Connect to http://localhost:8000/ to use it.
console.log("Listening on port 8000...");
server.listen(8000);
<|endoftext|>


<commit_before>// @format
const path = require("path");

const babelFlowConfig = require("./babel.flow.config");
const babelTypescriptConfig = require("./babel.typescript.config");
var {
  exclude,
  mergeDefaultAliases
} = require("./packages/webpack-configurator");

module.exports = {
  title: "nteract components",
  defaultExample: false,
  sections: [
    {
      name: "Presentational Components",
      components: "packages/presentational-components/src/components/*.js"
    },
    {
      name: "Outputs",
      components: "packages/outputs/src/components/*.js"
    },
    {
      name: "Media Outputs",
      components: "packages/outputs/src/components/media/*.js",
      content: "packages/outputs/src/components/media/index.md",
      ignore: "packages/outputs/src/components/media/index.js"
    },
    {
      name: "Binder Hosts and Kernels",
      components: "packages/host-cache/src/components/*.js"
    },
    {
      name: "Directory Listing",
      components: "packages/directory-listing/src/components/*.js"
    },
    {
      name: "MarkdownRender",
      content: "packages/markdown/examples.md"
    },
    {
      name: "Maths",
      content: "packages/mathjax/examples.md"
    }
  ],
  // For overriding the components styleguidist uses
  styleguideComponents: {
    LogoRenderer: path.join(
      __dirname,
      "packages",
      "styleguide-components",
      "logo.js"
    )
  },
  compilerConfig: {
    // Allow us to use {...props}
    objectAssign: "Object.assign",
    transforms: {
      // whether template strings get transpiled (we don't want it to, so that we can use the native functionality)
      templateString: false
    }
  },
  webpackConfig: {
    node: {
      fs: "empty",
      child_process: "empty",
      net: "empty"
    },
    resolve: {
      mainFields: ["nteractDesktop", "es2015", "jsnext:main", "module", "main"],
      extensions: [".js", ".jsx", ".ts", ".tsx"],
      alias: mergeDefaultAliases()
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude,
          loader: "babel-loader",
          options: babelFlowConfig()
        },
        {
          test: /\.tsx?$/,
          exclude,
          loader: "babel-loader",
          options: babelTypescriptConfig()
        }
      ]
    }
  }
};
<commit_msg>try including mybinder components by globbing ts<commit_after>// @format
const path = require("path");

const babelFlowConfig = require("./babel.flow.config");
const babelTypescriptConfig = require("./babel.typescript.config");
var {
  exclude,
  mergeDefaultAliases
} = require("./packages/webpack-configurator");

module.exports = {
  title: "nteract components",
  defaultExample: false,
  sections: [
    {
      name: "Presentational Components",
      components: "packages/presentational-components/src/components/*.js"
    },
    {
      name: "Outputs",
      components: "packages/outputs/src/components/*.js"
    },
    {
      name: "Media Outputs",
      components: "packages/outputs/src/components/media/*.js",
      content: "packages/outputs/src/components/media/index.md",
      ignore: "packages/outputs/src/components/media/index.js"
    },
    {
      name: "Binder Hosts and Kernels",
      components: "packages/host-cache/src/components/*.ts"
    },
    {
      name: "Directory Listing",
      components: "packages/directory-listing/src/components/*.js"
    },
    {
      name: "MarkdownRender",
      content: "packages/markdown/examples.md"
    },
    {
      name: "Maths",
      content: "packages/mathjax/examples.md"
    }
  ],
  // For overriding the components styleguidist uses
  styleguideComponents: {
    LogoRenderer: path.join(
      __dirname,
      "packages",
      "styleguide-components",
      "logo.js"
    )
  },
  compilerConfig: {
    // Allow us to use {...props}
    objectAssign: "Object.assign",
    transforms: {
      // whether template strings get transpiled (we don't want it to, so that we can use the native functionality)
      templateString: false
    }
  },
  webpackConfig: {
    node: {
      fs: "empty",
      child_process: "empty",
      net: "empty"
    },
    resolve: {
      mainFields: ["nteractDesktop", "es2015", "jsnext:main", "module", "main"],
      extensions: [".js", ".jsx", ".ts", ".tsx"],
      alias: mergeDefaultAliases()
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude,
          loader: "babel-loader",
          options: babelFlowConfig()
        },
        {
          test: /\.tsx?$/,
          exclude,
          loader: "babel-loader",
          options: babelTypescriptConfig()
        }
      ]
    }
  }
};
<|endoftext|>


<commit_before>/* global on:false, getSetItems:false */

export class Overlay {
  close() {
    getSetItems('Overlay.close', {
      collectionArray: ['processing'],
      callback: (v, finalSetAttrs) => {
        finalSetAttrs.processing = false;
      },
    });
  }
  setup() {
    on('change:close_overlay', () => {
      this.close();
    });
  }
}
<commit_msg>add utility<commit_after>/* global on:false, getSetItems:false */

import { getSetItems } from './../../scripts/utilities';

export class Overlay {
  close() {
    getSetItems('Overlay.close', {
      collectionArray: ['processing'],
      callback: (v, finalSetAttrs) => {
        finalSetAttrs.processing = false;
      },
    });
  }
  setup() {
    on('change:close_overlay', () => {
      this.close();
    });
  }
}
<|endoftext|>


<commit_before>var path = require('path');
var loaderUtils = require('loader-utils');
var steed = require('steed');

function resolveImageSrc(loaderContext, image, callback) {
  var dirname = path.dirname(loaderContext.resourcePath);

  // Resolve the image filename relative to the manifest file
  loaderContext.resolve(dirname, image.src, function(err, filename) {
    if (err) {
      return callback(err);
    }

    // Ensure Webpack knows that the image is a dependency of the manifest
    loaderContext.dependency && loaderContext.dependency(filename);

    // Asynchronously pass the image through the loader pipeline
    loaderContext.loadModule(filename, function(err, source, map, module) {
      if (err) {
        return callback(err);
      }

      // Update the image src property to match the generated filename
      // Is it always the first key in the assets object?
      image.src = Object.keys(module.assets)[0];

      callback(null, image);
    });
  });
}

function resolveImages(loaderContext, manifest, key, callback) {
  if (!Array.isArray(manifest[key])) {
    return callback(null);
  }

  steed.map(manifest[key], resolveImageSrc.bind(null, loaderContext), function(err, images) {
    if (err) {
      return callback(err);
    }

    manifest[key] = images;

    callback(null);
  });
}

module.exports = function(source) {
  var manifest = JSON.parse(source);

  var loaderContext = this;
  var callback = loaderContext.async();

  steed.parallel([
    resolveImages.bind(null, loaderContext, manifest, 'splash_screens'),
    resolveImages.bind(null, loaderContext, manifest, 'icons')
  ], function(err) {
    if (err) {
      return callback(err);
    }

    callback(null, JSON.stringify(manifest, null, 2));
  });
};
<commit_msg>Replace incorrect usage of map with each<commit_after>var path = require('path');
var loaderUtils = require('loader-utils');
var steed = require('steed');

function resolveImageSrc(loaderContext, image, callback) {
  var dirname = path.dirname(loaderContext.resourcePath);

  // Resolve the image filename relative to the manifest file
  loaderContext.resolve(dirname, image.src, function(err, filename) {
    if (err) {
      return callback(err);
    }

    // Ensure Webpack knows that the image is a dependency of the manifest
    loaderContext.dependency && loaderContext.dependency(filename);

    // Asynchronously pass the image through the loader pipeline
    loaderContext.loadModule(filename, function(err, source, map, module) {
      if (err) {
        return callback(err);
      }

      // Update the image src property to match the generated filename
      // Is it always the first key in the assets object?
      image.src = Object.keys(module.assets)[0];

      callback(null);
    });
  });
}

function resolveImages(loaderContext, manifest, key, callback) {
  if (!Array.isArray(manifest[key])) {
    return callback(null);
  }

  steed.each(manifest[key], resolveImageSrc.bind(null, loaderContext), function(err) {
    if (err) {
      return callback(err);
    }

    callback(null);
  });
}

module.exports = function(source) {
  var manifest = JSON.parse(source);

  var loaderContext = this;
  var callback = loaderContext.async();

  steed.parallel([
    resolveImages.bind(null, loaderContext, manifest, 'splash_screens'),
    resolveImages.bind(null, loaderContext, manifest, 'icons')
  ], function(err) {
    if (err) {
      return callback(err);
    }

    callback(null, JSON.stringify(manifest, null, 2));
  });
};
<|endoftext|>