<commit_before>/* global console, require, __dirname, process, module */
/* jshint node: true */
/* jshint esnext: true */

"use strict";

var path = require("path");
var express = require("express");
var app = express();
var database = require("./database/database");
var Q = require("q");
var rowTransformer = require("./transformers/row-transformer");

/**
 * Initializes all the express HTTP specific routes.
 * @return {Q.Promise} Resolves on success.
 */
var initRoutes = () => {
    var deferred = Q.defer();
    var releaseDirectory = path.join(__dirname, "..");

    // NOTE this is not async function, we just use it through promise to allow clean and readable promise chain

    // creating a iterable list of static url we can safely use from the browser without express involving itself
    // with them too much
    var staticRouteMappings = [
        { directory: path.join(releaseDirectory, "client"), url: "/public" },
        { directory: path.join(releaseDirectory, "../node_modules/socket.io-client/socket.io.js"), url: "/socket.io.js" }
    ];

    // This custom variable overwrites all other port variables
    var port = process.env.DEV_PORT ? process.env.DEV_PORT : (process.env.PORT || 3000);
    app.set("port", port);

    staticRouteMappings.forEach(mapping => {
        app.use(mapping.url, express.static(mapping.directory));
    });

    // From all other routes we return index.html for now...
    app.get("*", (request, response) => {
        var indexHtml = path.join(releaseDirectory, "client", "html", "index.html");
        response.sendFile(indexHtml);
    });
    deferred.resolve(true);

    return deferred.promise;
};

/**
 * Initializes the express server itself.
 * @returns {Q.Promise} Resolves on success.
 */
var initServer = () => {
    var deferred = Q.defer();

    var server = app.listen(app.get("port"), () => {
        console.log("Node app is running at localhost:" + app.get('port'));
        deferred.resolve(server);
    });

    return deferred.promise;
};

/**
 * Initializes all the Socket.io connections and messages available in the application.
 * @returns {Q.Promise} Resolves on success.
 */
var initSockets = server => {
    var deferred = Q.defer();

    // TODO move the socket initialization into its own place
    var socket = require("socket.io");
    var io = socket(server);
    var constants = require("./utilities/constants");
    var database = require("./database/database");

    // TODO move the socket code and hooks into a separate file
    io.on(constants.events.socket.connected, socket => {
        console.log("Socket connected to server.",socket.id);

        socket.on("dash.get.dashboard", (parameters, resultHandler) => {
            console.log("Received socket get.dasboard");
            database
                .findDashboardsForEmail(parameters)
                .then(results => {
                    resultHandler(null, !results || results.length <= 0 ? [] : results);
                })
                .catch(error => {
                    resultHandler(error);
                })
                .done();
        });

        socket.on("dash.get.dashboard.components", (parameters, resultHandler) => {
            console.log("Received socket get.dasboard.components", JSON.stringify(parameters));

            if (!parameters) {
                resultHandler("No components");
                return;
            }

            database
                .findComponentsForDashboard(parameters, rowTransformer(parameters))
                .then(results => {
                    resultHandler(null, results);
                })
                .catch(error => {
                    resultHandler(error);
                })
                .done();
        });

        socket.on(constants.events.socket.disconnected, () => {
            console.log("Socket disconnected from server.", socket.id);
        });
    });

    return deferred.promise;
};

// Start the application through the Promise-chain
initRoutes()
    .then(() => database.init())
    .then(() => initServer())
    .then(server => initSockets(server))
    .catch(error => {
        console.log(error);
        process.exit(6);
    })
    .done();
<commit_msg>Added a TODO<commit_after>/* global console, require, __dirname, process, module */
/* jshint node: true */
/* jshint esnext: true */

"use strict";

var path = require("path");
var express = require("express");
var app = express();
var database = require("./database/database");
var Q = require("q");
var rowTransformer = require("./transformers/row-transformer");

/**
 * Initializes all the express HTTP specific routes.
 * @return {Q.Promise} Resolves on success.
 */
var initRoutes = () => {
    var deferred = Q.defer();
    var releaseDirectory = path.join(__dirname, "..");

    // NOTE this is not async function, we just use it through promise to allow clean and readable promise chain

    // creating a iterable list of static url we can safely use from the browser without express involving itself
    // with them too much
    var staticRouteMappings = [
        { directory: path.join(releaseDirectory, "client"), url: "/public" },
        { directory: path.join(releaseDirectory, "../node_modules/socket.io-client/socket.io.js"), url: "/socket.io.js" }
    ];

    // This custom variable overwrites all other port variables
    var port = process.env.DEV_PORT ? process.env.DEV_PORT : (process.env.PORT || 3000);
    app.set("port", port);

    staticRouteMappings.forEach(mapping => {
        app.use(mapping.url, express.static(mapping.directory));
    });

    // From all other routes we return index.html for now...
    // TODO 404 instead of serving the rough index.html and letting JS sort itself out
    app.get("*", (request, response) => {
        var indexHtml = path.join(releaseDirectory, "client", "html", "index.html");
        response.sendFile(indexHtml);
    });
    deferred.resolve(true);

    return deferred.promise;
};

/**
 * Initializes the express server itself.
 * @returns {Q.Promise} Resolves on success.
 */
var initServer = () => {
    var deferred = Q.defer();

    var server = app.listen(app.get("port"), () => {
        console.log("Node app is running at localhost:" + app.get('port'));
        deferred.resolve(server);
    });

    return deferred.promise;
};

/**
 * Initializes all the Socket.io connections and messages available in the application.
 * @returns {Q.Promise} Resolves on success.
 */
var initSockets = server => {
    var deferred = Q.defer();

    // TODO move the socket initialization into its own place
    var socket = require("socket.io");
    var io = socket(server);
    var constants = require("./utilities/constants");
    var database = require("./database/database");

    // TODO move the socket code and hooks into a separate file
    io.on(constants.events.socket.connected, socket => {
        console.log("Socket connected to server.",socket.id);

        socket.on("dash.get.dashboard", (parameters, resultHandler) => {
            console.log("Received socket get.dasboard");
            database
                .findDashboardsForEmail(parameters)
                .then(results => {
                    resultHandler(null, !results || results.length <= 0 ? [] : results);
                })
                .catch(error => {
                    resultHandler(error);
                })
                .done();
        });

        socket.on("dash.get.dashboard.components", (parameters, resultHandler) => {
            console.log("Received socket get.dasboard.components", JSON.stringify(parameters));

            if (!parameters) {
                resultHandler("No components");
                return;
            }

            database
                .findComponentsForDashboard(parameters, rowTransformer(parameters))
                .then(results => {
                    resultHandler(null, results);
                })
                .catch(error => {
                    resultHandler(error);
                })
                .done();
        });

        socket.on(constants.events.socket.disconnected, () => {
            console.log("Socket disconnected from server.", socket.id);
        });
    });

    return deferred.promise;
};

// Start the application through the Promise-chain
initRoutes()
    .then(() => database.init())
    .then(() => initServer())
    .then(server => initSockets(server))
    .catch(error => {
        console.log(error);
        process.exit(6);
    })
    .done();
<|endoftext|>


<commit_before>/**
 * Shrimp Paste
 * ------------
 * This is the jQuery variant, supporting older broweser
 * don't need no jQuery? Try the plain version!
 */

 function shrimppasteclass() {

	'use strict';

	var self = this;

	this.steps = {}

	this.createNav = function(type, parent) {
		var button = $('');
		button.attr('href', '#');
		button.addClass('ShrimpPaste-button');
		button.addClass('ShrimpPaste-button--'+type);
		button.addClass('js-'+type);
		button.text(type);
		return button;
	}

	this.handleSlideClick = function(event, direction, parent) {
		event.preventDefault();
		if(direction === 'prev') {
			if((self.steps.current + self.steps.width) <= 0){
				self.steps.current = self.steps.current + self.steps.width;
			}
		}
		else {
			if(self.steps.current - self.steps.width >= -1 * self.steps.max){
				self.steps.current = self.steps.current - self.steps.width;
			}
		}

		var slidesWrap = parent.find('.js-shrimppaste-wrap');
		slidesWrap.css('transform', 'translateX('+self.steps.current+'px)');
	}

	this.build = function (sliderEl, opts) {
		var slidesViewport = sliderEl.find('.js-shrimppaste-viewport');
		var maxWidth = Math.round(slidesViewport.width());
		var slideWidth = Math.round(maxWidth / opts.slides);
		var slides = sliderEl.find('.js-shrimppaste-item');
		var totWidth = Math.round(slideWidth * slides.length);
		var slidesWrap = sliderEl.find('.js-shrimppaste-wrap');

		// slidesViewport.style.width = slidesViewport.style.width + 1 +'px';
		slidesWrap.css('width', totWidth.toString() + 'px');
		sliderEl.addClass('is-active');
		self.steps.width = slideWidth;
		self.steps.max = totWidth - maxWidth;
		self.steps.current = 0;

		var prevButton = self.createNav('prev',sliderEl);
		var nextButton = self.createNav('next',sliderEl);
		sliderEl.append(prevButton);
		sliderEl.append(nextButton);

		nextButton.on('click', function(event){ self.handleSlideClick(event, 'next', sliderEl); });
		prevButton.on('click', function(event){ self.handleSlideClick(event, 'prev', sliderEl); });

		slides.each(function() {
			$(this).css('width', slideWidth.toString() +'px');
		});
	}

//	return shrimppasteclass;

};

window.shrimppaste = (function (window, document, undefined) {

	'use strict';

	var shrimppaste = {
		steps : {}
	}

	// Feature Test

	shrimppaste.cutsMustard = function() {
		if ( 'querySelector' in document && 'addEventListener' in window && Array.prototype.forEach ) {
			return true;
		}
		else {
			return false;
		}
	}

	shrimppaste.init = function (opts) {
		if(shrimppaste.cutsMustard) {
			$('.js-shrimppaste').each(function(){
				var shrimppasteinstance = new shrimppasteclass();
				shrimppasteinstance.build($(this), opts);
			});
		}
	}

	return shrimppaste;

})(window, document);

shrimppaste.init({ 'slides' : 4 });
<commit_msg>Port changes to in progress jQuery version.<commit_after>/**
 * Shrimp Paste
 * ------------
 * This is the jQuery variant, supporting older broweser
 * don't need no jQuery? Try the plain version!
 */

 function shrimppasteclass() {

	'use strict';

	var self = this;

	this.steps = {}

	this.createNav = function(type, parent) {
		var button = $('');
		button.attr('href', '#');
		button.addClass('ShrimpPaste-button');
		button.addClass('ShrimpPaste-button--'+type);
		button.addClass('js-'+type);
		button.text(type);
		return button;
	}

	this.setAllNavActive = function(sliderEl) {
		sliderEl.find('.js-next').removeClass('ShrimpPaste-button--inActive');
		sliderEl.find('.js-prev').removeClass('ShrimpPaste-button--inActive');
	}

	this.setNavInactive =  function(event) {
		var button = $(event.target);
		button.addClass('ShrimpPaste-button--inActive');
	}

	this.handleSlideClick = function(event, direction, parent) {
		event.preventDefault();

		self.setAllNavActive(parent);

		if(direction === 'prev') {
			// Check if current step is possible
			if((self.steps.current + self.steps.width) <= 0){
				self.steps.current = self.steps.current + self.steps.width;

				// Check if *next* step is even possible
				if((self.steps.current + self.steps.width) > 0){
					self.setNavInactive(event);
				}
			}
			else {
				// Current step not possible, keep button inactive
				self.setNavInactive(event);
			}
		}
		else {
			// Check if current step is possible
			if(self.steps.current - self.steps.width >= -1 * self.steps.max){
				self.steps.current = self.steps.current - self.steps.width;

				// Check if *next* step is even possible
				if(self.steps.current - self.steps.width <= -1 * self.steps.max){
					self.setNavInactive(event);
				}
			}
			else {
				// Current step not possible, keep button inactive
				self.setNavInactive(event);
			}
		}

		var slidesWrap = parent.find('.js-shrimppaste-wrap');
		slidesWrap.css('transform', 'translateX('+self.steps.current+'px)');
	}

	this.build = function (sliderEl, opts) {
		var slidesViewport = sliderEl.find('.js-shrimppaste-viewport');
		var maxWidth = Math.round(slidesViewport.width());
		var slideWidth = Math.round(maxWidth / opts.slides);
		var slides = sliderEl.find('.js-shrimppaste-item');
		var totWidth = Math.round(slideWidth * slides.length);
		var slidesWrap = sliderEl.find('.js-shrimppaste-wrap');

		slidesWrap.css('width', totWidth.toString() + 'px');
		sliderEl.addClass('is-active');
		self.steps.width = slideWidth;
		self.steps.max = totWidth - maxWidth;
		self.steps.current = 0;

		if(self.steps.max > slideWidth) {
			var prevButton = self.createNav('prev',sliderEl);
			var nextButton = self.createNav('next',sliderEl);
			sliderEl.append(prevButton);
			sliderEl.append(nextButton);

			nextButton.on('click', function(event){ self.handleSlideClick(event, 'next', sliderEl); });
			prevButton.on('click', function(event){ self.handleSlideClick(event, 'prev', sliderEl); });
		}

		slides.each(function() {
			$(this).css('width', slideWidth.toString() +'px');
		});
	}

};

window.shrimppaste = (function (window, document, undefined) {

	'use strict';

	var shrimppaste = {
		steps : {}
	}

	// Feature Test

	shrimppaste.cutsMustard = function() {
		if ( 'querySelector' in document && 'addEventListener' in window && Array.prototype.forEach ) {
			return true;
		}
		else {
			return false;
		}
	}

	shrimppaste.init = function (opts) {
		if(shrimppaste.cutsMustard) {
			$('.js-shrimppaste').each(function(){
				var shrimppasteinstance = new shrimppasteclass();
				shrimppasteinstance.build($(this), opts);
			});
		}
	}

	return shrimppaste;

})(window, document);

shrimppaste.init({ 'slides' : 4 });
<|endoftext|>


<commit_before><commit_msg>add parameter 'serial' for auto-update to not work parallelly<commit_after><|endoftext|>


<commit_before>import React from 'react';
import TestUtils from 'react/lib/ReactTestUtils';
import Dropdown from './dropdown';
import ImmutableHelper from './../../utils/helpers/immutable'

describe("Dropdown", () => {
  let instance, instanceNoValue, instanceInvalid, instanceNoFilter, input;
  let data = ImmutableHelper.parseJSON(
            { 'items': [{'id' : 1,  'name': 'foo' },
                        {'id' : 2,  'name': 'bar' },
                        {'id' : 3,  'name': 'far' },
                        {'id' : 4,  'name': 'boo' }
                      ]
                   });

  beforeEach(() => {
    instance = TestUtils.renderIntoDocument(<Dropdown name="foo" options={ data.get('items') } value={ 2 } />);
    instanceNoValue = TestUtils.renderIntoDocument(<Dropdown name="bar" options={ data.get('items') } />);
    instanceInvalid = TestUtils.renderIntoDocument(<Dropdown name="foo" options={ data.get('items') } value={ 3 } />);
    instanceNoFilter = TestUtils.renderIntoDocument(<Dropdown name="foo" options={ data.get('items') } value={ 2 } filter={ false } />);
    input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input');
  });

    describe ('componentWillReceiveProps', () => {
      describe('when props have changed', () => {
        it('clears the visible value', () => {
          instance.componentWillReceiveProps({value: 1});
          expect(instance.visibleValue).toBeFalsy();
        });
      });

      describe('when props have not changed', () => {
        it('does not clear the visible value', () => {
          instance.visibleValue = 'bar'
          instance.componentWillReceiveProps({value: 2 });
          expect(instance.visibleValue).toEqual('bar');
        });
      });
    });

  describe('emitOnChangeCallback', () => {
    it('calls the change handler with the selected item', () => {
      spyOn(instance, '_handleOnChange');
      let value = 'one';
      instance.emitOnChangeCallback(value);
      expect(instance._handleOnChange).toHaveBeenCalledWith({target: { value: value }});
    });
  });

  describe('handleFocus', () => {
    beforeEach(() => {
      spyOn(instance.refs.input, 'setSelectionRange');
      spyOn(instanceNoFilter.refs.input, 'setSelectionRange');
      spyOn(instance, 'setState').and.callThrough();
    });

    it('select all the value', () => {
      TestUtils.Simulate.focus(input[0]);
      expect(instance.refs.input.setSelectionRange).toHaveBeenCalledWith(0, instance.refs.input.value.length);
    });

    it('does not select the value when filter disabled', () => {
      TestUtils.Simulate.focus(instanceNoFilter.refs.input);
      expect(instanceNoFilter.refs.input.setSelectionRange).not.toHaveBeenCalled();
    });

    it('calls setState and opens the dropdown', () => {
      TestUtils.Simulate.focus(input[0]);
      expect(instance.setState).toHaveBeenCalledWith({ open: true, highlighted: instance.props.value });
    });

    describe('when no option has been selected', () => {
      beforeEach(() => {
        spyOn(instanceNoValue, 'setState');
        input = TestUtils.scryRenderedDOMComponentsWithTag(instanceNoValue, 'input');
      });

      it('highlights the first option', () => {
        TestUtils.Simulate.focus(input[0]);
        expect(instanceNoValue.setState).toHaveBeenCalledWith({ open: true, highlighted: instanceNoValue.props.options.first().get('id') });
      });
    });

    describe('when an option has been selected', () => {
      it('highlights the selected option', () => {
        TestUtils.Simulate.focus(input[0]);
        expect(instance.setState).toHaveBeenCalledWith({ open: true, highlighted: instance.props.value });
      });
    });

    describe('when disabled', () => {
      it('does not call setState', () => {
        instance = TestUtils.renderIntoDocument(<Dropdown disabled name="foo" options={ data.get('items') } value={ 2 } />);
        input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input');
        spyOn(instance, 'setState');
        TestUtils.Simulate.focus(input[0]);
        expect(instance.setState).not.toHaveBeenCalled();
      });
    });

    describe('when readOnly', () => {
      it('does not call setState', () => {
        instance = TestUtils.renderIntoDocument(<Dropdown readOnly name="foo" options={ data.get('items') } value={ 2 } />);
        input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input');
        spyOn(instance, 'setState');
        TestUtils.Simulate.focus(input[0]);
        expect(instance.setState).not.toHaveBeenCalled();
      });
    });
  });

   describe('handleMouseEnterList', () => {
      it('turns blur blocking off', () => {
        instance.blockBlur = false;
        TestUtils.Simulate.mouseEnter(instance.refs.list);
        expect(instance.blockBlur).toBeTruthy();
      });
    });

    describe('handleMouseLeaveList', () => {
      it('turns blur blocking on', () => {
        instance.blockBlur = true;
        TestUtils.Simulate.mouseLeave(instance.refs.list);
        expect(instance.blockBlur).toBeFalsy();
      });
    });

    describe('handleMouseDownOnList', () => {
      beforeEach(() => {
        jasmine.clock().install();
        spyOn(instance.refs.input, 'focus');
      });

      afterEach(() => {
        jasmine.clock().uninstall();
      });

      describe('when the target was not the list', () => {
        it('does not call focus on the input', () => {
          TestUtils.Simulate.mouseDown(instance.refs.list, { target: 'foo' });
          jasmine.clock().tick(0);
          expect(instance.refs.input.focus).not.toHaveBeenCalled();
        });
      });

      describe('when the target was the list', () => {
        it('does call focus on the input', () => {
          TestUtils.Simulate.mouseDown(instance.refs.list, { target: instance.refs.list });
          jasmine.clock().tick(0);
          expect(instance.refs.input.focus).toHaveBeenCalled();
        });
      });
    });

  describe('handleBlur', () => {
    beforeEach(() => {
      spyOn(instance, 'setState');
      input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input');
    });

    describe('when blurring is not blocked', () => {
      it('clears the filter', () => {
        TestUtils.Simulate.blur(input[0]);
        expect(instance.setState).toHaveBeenCalledWith({ filter: null });
      });
    });

    describe('when blurring is blocked', () => {
      it('does not clear the filter', () => {
        instance.blockBlur = true;
        TestUtils.Simulate.blur(input[0]);
        expect(instance.setState).not.toHaveBeenCalled();
      });
    });

    describe('when filter is disabled', () => {
      it('does not clear the filter', () => {
        spyOn(instanceNoFilter, 'setState');
        instanceNoFilter.blockBlur = false;
        instanceNoFilter.handleBlur();
        expect(instanceNoFilter.setState).not.toHaveBeenCalled();
      });
    });
  });

  describe('handleSelect', () => {
    let ev;

    beforeEach(() => {
      spyOn(instance, 'setState');
      spyOn(instance, 'emitOnChangeCallback');
      ev = { currentTarget: { getAttribute: function() {} }};
      spyOn(ev.currentTarget, 'getAttribute').and.returnValue('foo');
      instance.blockBlur = true;
    });

    it('turns blur blocking off', () => {
      instance._handleSelect(ev);
      expect(instance.blockBlur).toBeFalsy();
    });

    it('calls emitOnChangeCallback with the selected value', () => {
      instance._handleSelect(ev);
      expect(instance.emitOnChangeCallback).toHaveBeenCalledWith('foo');
    });

    it('clears the filter', () => {
      instance._handleSelect(ev);
      expect(instance.setState).toHaveBeenCalledWith({ filter: null });
    });

    it('does not clear the filter if filter is disabled', () => {
      spyOn(instanceNoFilter, 'setState');
      instanceNoFilter.handleSelect(ev);
      expect(instanceNoFilter.setState).not.toHaveBeenCalled();
    });
  });

  describe('handleVisibleChange', () => {
    let ev;

    beforeEach(() => {
      spyOn(instance, 'setState');
      ev = { target: { value: 'far' }};
      instance.handleVisibleChange(ev);
    });

    it('calls setState with the filter text', () => {
      expect(instance.setState).toHaveBeenCalledWith({ filter: 'far' });
    });

    it('does not clear the filter if filter is disabled', () => {
      spyOn(instanceNoFilter, 'setState');
      instanceNoFilter.handleVisibleChange(ev);
      expect(instanceNoFilter.setState).not.toHaveBeenCalled();
    });
  });

  describe('nameByID', () => {
    describe('when no value has been selected', () => {
      it('returns an empty string', () => {
        instanceNoValue.nameByID();
        expect(instanceNoValue.props.value).toBeFalsy();
      });
    });

    describe('when a value has been selected', () => {
      describe('when the selected value is valid', () => {
        it('returns the corresponding name', () => {
          expect(instance.nameByID()).toEqual('bar');
        });
      });

      describe('when the selected value does not have a corresponding name', () => {
        it('sets visible value to an empty string', () => {
          let instance = TestUtils.renderIntoDocument(<Dropdown name="foo" options={ data.get('items') } value={ 5 } />);
          expect(instance.nameByID()).toBeFalsy();
        });
      });
    });
  });

  describe("highlightMatches",() => {
    let option;

    beforeEach(() => {
      let options = data.get('items').toJS();
      option = options[0];
    });

    it('returns the option when no filter text is passed', () => {
      expect(instance.highlightMatches(option.name, '')).toEqual(option.name);
    });

    describe('when valid matches are found', () => {
      let output, beginning, beginningOuter, beginningInner,
          beginningContent, middleInner, middleOuter, middleContent, endOuter, endInner, endContent;

      beforeEach(() => {
        output = instance.highlightMatches(option.name, 'o');
        beginning = output[0];
        beginningContent = beginning.props.children;
        middleOuter = output[1];
        middleInner = middleOuter.props.children;
        middleContent = middleInner.props.children;
        endOuter = output[2];
        endInner = endOuter.props.children;
        endContent = output[2].props.children;
      });

      it('returns option with matching text bold & underlined', () => {
        expect(middleOuter.type).toEqual('strong');
        expect(middleContent).toEqual('o');
        expect(middleInner.type).toEqual('u');
      });

      it('returns non-matched text as unformatted text', () => {
        expect(beginningContent).toEqual('f');
        expect(middleContent).toEqual('o');
        expect(middleContent.type).not.toEqual('strong');
      });
    });

    describe('when no matches are found', () => {
      it('returns the unformatted option', () => {
        expect(instance.highlightMatches(option.name, 'g')).toEqual('foo');
      });
    });
  });

  describe('prepareList', () => {
    let options;

    beforeEach(() => {
      options = data.get('items');
      spyOn(instance, 'highlightMatches');
    });

    describe('when no filter is applied', () => {
      it('returns the original options as JSON', () => {
        expect(instance.prepareList(options)).toEqual(options.toJS());
      });
    });

    describe('when a filter is being applied', () => {
      describe('when matches are found', () => {
        it('returns matched items with formatted matching text', () => {
          instance.state.filter = 'fo';
          instance.prepareList(options);
          expect(instance.highlightMatches).toHaveBeenCalled();
        });
      });

      describe('when no matches are found', () => {
        it('returns an empty object', () => {
          instance.state.filter = 'xXx';
          expect(instance.prepareList(options)).toEqual([]);
        });
      })
    });
  });

  describe('inputProps', () => {
    it('sets props to defined values', () => {
      expect(instance.inputProps.className).toMatch('ui-dropdown__input');
      spyOn(instance, 'handleFocus');
      instance.inputProps.onFocus();
      expect(instance.handleFocus).toHaveBeenCalled();
    });

    describe('when filtering is active', () => {
      it('sets value to the current filter string', () => {
        instance.state.filter = 'f'
        expect(instance.inputProps.value).toEqual('f');
      });
    });

    describe('when filtering is not active', () => {
      it('sets value to the corresponding value in the hidden input', () => {
        expect(instance.inputProps.value).toEqual('bar');
      });
    });

    describe('when filter is enabled', () => {
      it('sets the input to be readonly', () => {
        expect(instance.inputProps.readOnly).toBeFalsy();
      });
    });

    describe('when filter is disabled', () => {
      it('sets the input to be readonly', () => {
        expect(instanceNoFilter.inputProps.readOnly).toBeTruthy();
      });
    });
  });

  describe('hiddenInputProps', () => {
    it('sets the hidden props to the defined values', () => {
      expect(instance.hiddenInputProps.ref).toEqual('hidden');
      expect(instance.hiddenInputProps.type).toEqual('hidden');
      expect(instance.hiddenInputProps.readOnly).toBeTruthy();
      expect(instance.hiddenInputProps.name).toEqual(instance.props.name);
      expect(instance.hiddenInputProps.value).toEqual(instance.props.value);
    });
  });

  describe('rootClass', () => {
    it('returns the root class name', () => {
      expect(instance.rootClass).toEqual('ui-dropdown');
    });
  });

  describe('mainClasses', () => {
    it('returns the main class names', () => {
      expect(instance.mainClasses).toMatch('ui-dropdown');
    });
  });

  describe('inputClasses', () => {
    it('returns the input class names', () => {
      expect(instance.inputClasses).toMatch('ui-dropdown__input');
    });

    describe('when filtering is active', () => {
      it('adds a filter class', () => {
        instance.state.filter = 'a';
        expect(instance.inputClasses).toMatch('ui-dropdown__input ui-dropdown__input--filter');
      });
    });
  });

  describe('listHTML', () => {
    describe('when the dropdown is open', () => {
      it('sets the list classname', () => {
        TestUtils.Simulate.focus(input[0]);
        expect(instance.listHTML.props.className).toEqual('ui-dropdown__list common-list')
      });
    });

    describe('when the dropdown is closed', () => {
      it('adds hidden to the classname', () => {
        expect(instance.listHTML.props.className).toMatch('hidden')
      });
    });

    it('returns an unordered list containing the options', () => {
      expect(instance.listHTML.ref).toEqual('list');
      expect(instance.listHTML.props.children.length).toEqual(4);
    });
  });

  describe("render", () => {
    it("renders a hidden input", () => {
      input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input')[1];
      expect(input.tagName).toEqual("INPUT");
      expect(input.type).toEqual('hidden');
    });

    it("renders a visible input", () => {
      input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input')[0];
      expect(input.tagName).toEqual("INPUT");
    });

    it("renders a ul", () => {
      let ul = instance.refs.list;
      expect(ul.tagName).toEqual("UL");
      expect(ul.classList[1]).toEqual("hidden");
    });

    describe("render with options", () => {
      let ul, listItems;

      beforeEach(() => {
        ul = instance.refs.list;
        listItems = ul.childNodes;
      });

      it("renders a li with results", () => {
        expect(listItems.length).toEqual(4);
        expect(listItems[0].value).toEqual(1);
        expect(listItems[0].textContent).toEqual("foo");
        expect(listItems[1].value).toEqual(2);
        expect(listItems[1].textContent).toEqual("bar");
      });

      it("sets the highlighted class on the relevant option", () => {
        instance.setState({
          highlighted: 2
        });
        expect(listItems[0].className).toEqual("ui-dropdown__item common-list__item");
        expect(listItems[1].className).toEqual("ui-dropdown__item common-list__item ui-dropdown__item--highlighted common-list__item--highlighted ui-dropdown__item--selected common-list__item--selected");
      });
    });
  });

});
<commit_msg>fixed spec description<commit_after>import React from 'react';
import TestUtils from 'react/lib/ReactTestUtils';
import Dropdown from './dropdown';
import ImmutableHelper from './../../utils/helpers/immutable'

describe("Dropdown", () => {
  let instance, instanceNoValue, instanceInvalid, instanceNoFilter, input;
  let data = ImmutableHelper.parseJSON(
            { 'items': [{'id' : 1,  'name': 'foo' },
                        {'id' : 2,  'name': 'bar' },
                        {'id' : 3,  'name': 'far' },
                        {'id' : 4,  'name': 'boo' }
                      ]
                   });

  beforeEach(() => {
    instance = TestUtils.renderIntoDocument(<Dropdown name="foo" options={ data.get('items') } value={ 2 } />);
    instanceNoValue = TestUtils.renderIntoDocument(<Dropdown name="bar" options={ data.get('items') } />);
    instanceInvalid = TestUtils.renderIntoDocument(<Dropdown name="foo" options={ data.get('items') } value={ 3 } />);
    instanceNoFilter = TestUtils.renderIntoDocument(<Dropdown name="foo" options={ data.get('items') } value={ 2 } filter={ false } />);
    input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input');
  });

    describe ('componentWillReceiveProps', () => {
      describe('when props have changed', () => {
        it('clears the visible value', () => {
          instance.componentWillReceiveProps({value: 1});
          expect(instance.visibleValue).toBeFalsy();
        });
      });

      describe('when props have not changed', () => {
        it('does not clear the visible value', () => {
          instance.visibleValue = 'bar'
          instance.componentWillReceiveProps({value: 2 });
          expect(instance.visibleValue).toEqual('bar');
        });
      });
    });

  describe('emitOnChangeCallback', () => {
    it('calls the change handler with the selected item', () => {
      spyOn(instance, '_handleOnChange');
      let value = 'one';
      instance.emitOnChangeCallback(value);
      expect(instance._handleOnChange).toHaveBeenCalledWith({target: { value: value }});
    });
  });

  describe('handleFocus', () => {
    beforeEach(() => {
      spyOn(instance.refs.input, 'setSelectionRange');
      spyOn(instanceNoFilter.refs.input, 'setSelectionRange');
      spyOn(instance, 'setState').and.callThrough();
    });

    it('select all the value', () => {
      TestUtils.Simulate.focus(input[0]);
      expect(instance.refs.input.setSelectionRange).toHaveBeenCalledWith(0, instance.refs.input.value.length);
    });

    it('does not select the value when filter disabled', () => {
      TestUtils.Simulate.focus(instanceNoFilter.refs.input);
      expect(instanceNoFilter.refs.input.setSelectionRange).not.toHaveBeenCalled();
    });

    it('calls setState and opens the dropdown', () => {
      TestUtils.Simulate.focus(input[0]);
      expect(instance.setState).toHaveBeenCalledWith({ open: true, highlighted: instance.props.value });
    });

    describe('when no option has been selected', () => {
      beforeEach(() => {
        spyOn(instanceNoValue, 'setState');
        input = TestUtils.scryRenderedDOMComponentsWithTag(instanceNoValue, 'input');
      });

      it('highlights the first option', () => {
        TestUtils.Simulate.focus(input[0]);
        expect(instanceNoValue.setState).toHaveBeenCalledWith({ open: true, highlighted: instanceNoValue.props.options.first().get('id') });
      });
    });

    describe('when an option has been selected', () => {
      it('highlights the selected option', () => {
        TestUtils.Simulate.focus(input[0]);
        expect(instance.setState).toHaveBeenCalledWith({ open: true, highlighted: instance.props.value });
      });
    });

    describe('when disabled', () => {
      it('does not call setState', () => {
        instance = TestUtils.renderIntoDocument(<Dropdown disabled name="foo" options={ data.get('items') } value={ 2 } />);
        input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input');
        spyOn(instance, 'setState');
        TestUtils.Simulate.focus(input[0]);
        expect(instance.setState).not.toHaveBeenCalled();
      });
    });

    describe('when readOnly', () => {
      it('does not call setState', () => {
        instance = TestUtils.renderIntoDocument(<Dropdown readOnly name="foo" options={ data.get('items') } value={ 2 } />);
        input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input');
        spyOn(instance, 'setState');
        TestUtils.Simulate.focus(input[0]);
        expect(instance.setState).not.toHaveBeenCalled();
      });
    });
  });

   describe('handleMouseEnterList', () => {
      it('turns blur blocking off', () => {
        instance.blockBlur = false;
        TestUtils.Simulate.mouseEnter(instance.refs.list);
        expect(instance.blockBlur).toBeTruthy();
      });
    });

    describe('handleMouseLeaveList', () => {
      it('turns blur blocking on', () => {
        instance.blockBlur = true;
        TestUtils.Simulate.mouseLeave(instance.refs.list);
        expect(instance.blockBlur).toBeFalsy();
      });
    });

    describe('handleMouseDownOnList', () => {
      beforeEach(() => {
        jasmine.clock().install();
        spyOn(instance.refs.input, 'focus');
      });

      afterEach(() => {
        jasmine.clock().uninstall();
      });

      describe('when the target was not the list', () => {
        it('does not call focus on the input', () => {
          TestUtils.Simulate.mouseDown(instance.refs.list, { target: 'foo' });
          jasmine.clock().tick(0);
          expect(instance.refs.input.focus).not.toHaveBeenCalled();
        });
      });

      describe('when the target was the list', () => {
        it('does call focus on the input', () => {
          TestUtils.Simulate.mouseDown(instance.refs.list, { target: instance.refs.list });
          jasmine.clock().tick(0);
          expect(instance.refs.input.focus).toHaveBeenCalled();
        });
      });
    });

  describe('handleBlur', () => {
    beforeEach(() => {
      spyOn(instance, 'setState');
      input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input');
    });

    describe('when blurring is not blocked', () => {
      it('clears the filter', () => {
        TestUtils.Simulate.blur(input[0]);
        expect(instance.setState).toHaveBeenCalledWith({ filter: null });
      });
    });

    describe('when blurring is blocked', () => {
      it('does not clear the filter', () => {
        instance.blockBlur = true;
        TestUtils.Simulate.blur(input[0]);
        expect(instance.setState).not.toHaveBeenCalled();
      });
    });

    describe('when filter is disabled', () => {
      it('does not clear the filter', () => {
        spyOn(instanceNoFilter, 'setState');
        instanceNoFilter.blockBlur = false;
        instanceNoFilter.handleBlur();
        expect(instanceNoFilter.setState).not.toHaveBeenCalled();
      });
    });
  });

  describe('handleSelect', () => {
    let ev;

    beforeEach(() => {
      spyOn(instance, 'setState');
      spyOn(instance, 'emitOnChangeCallback');
      ev = { currentTarget: { getAttribute: function() {} }};
      spyOn(ev.currentTarget, 'getAttribute').and.returnValue('foo');
      instance.blockBlur = true;
    });

    it('turns blur blocking off', () => {
      instance._handleSelect(ev);
      expect(instance.blockBlur).toBeFalsy();
    });

    it('calls emitOnChangeCallback with the selected value', () => {
      instance._handleSelect(ev);
      expect(instance.emitOnChangeCallback).toHaveBeenCalledWith('foo');
    });

    it('clears the filter', () => {
      instance._handleSelect(ev);
      expect(instance.setState).toHaveBeenCalledWith({ filter: null });
    });

    it('does not clear the filter if filter is disabled', () => {
      spyOn(instanceNoFilter, 'setState');
      instanceNoFilter.handleSelect(ev);
      expect(instanceNoFilter.setState).not.toHaveBeenCalled();
    });
  });

  describe('handleVisibleChange', () => {
    let ev;

    beforeEach(() => {
      spyOn(instance, 'setState');
      ev = { target: { value: 'far' }};
      instance.handleVisibleChange(ev);
    });

    it('calls setState with the filter text', () => {
      expect(instance.setState).toHaveBeenCalledWith({ filter: 'far' });
    });

    it('does not clear the filter if filter is disabled', () => {
      spyOn(instanceNoFilter, 'setState');
      instanceNoFilter.handleVisibleChange(ev);
      expect(instanceNoFilter.setState).not.toHaveBeenCalled();
    });
  });

  describe('nameByID', () => {
    describe('when no value has been selected', () => {
      it('returns an empty string', () => {
        instanceNoValue.nameByID();
        expect(instanceNoValue.props.value).toBeFalsy();
      });
    });

    describe('when a value has been selected', () => {
      describe('when the selected value is valid', () => {
        it('returns the corresponding name', () => {
          expect(instance.nameByID()).toEqual('bar');
        });
      });

      describe('when the selected value does not have a corresponding name', () => {
        it('sets visible value to an empty string', () => {
          let instance = TestUtils.renderIntoDocument(<Dropdown name="foo" options={ data.get('items') } value={ 5 } />);
          expect(instance.nameByID()).toBeFalsy();
        });
      });
    });
  });

  describe("highlightMatches",() => {
    let option;

    beforeEach(() => {
      let options = data.get('items').toJS();
      option = options[0];
    });

    it('returns the option when no filter text is passed', () => {
      expect(instance.highlightMatches(option.name, '')).toEqual(option.name);
    });

    describe('when valid matches are found', () => {
      let output, beginning, beginningOuter, beginningInner,
          beginningContent, middleInner, middleOuter, middleContent, endOuter, endInner, endContent;

      beforeEach(() => {
        output = instance.highlightMatches(option.name, 'o');
        beginning = output[0];
        beginningContent = beginning.props.children;
        middleOuter = output[1];
        middleInner = middleOuter.props.children;
        middleContent = middleInner.props.children;
        endOuter = output[2];
        endInner = endOuter.props.children;
        endContent = output[2].props.children;
      });

      it('returns option with matching text bold & underlined', () => {
        expect(middleOuter.type).toEqual('strong');
        expect(middleContent).toEqual('o');
        expect(middleInner.type).toEqual('u');
      });

      it('returns non-matched text as unformatted text', () => {
        expect(beginningContent).toEqual('f');
        expect(middleContent).toEqual('o');
        expect(middleContent.type).not.toEqual('strong');
      });
    });

    describe('when no matches are found', () => {
      it('returns the unformatted option', () => {
        expect(instance.highlightMatches(option.name, 'g')).toEqual('foo');
      });
    });
  });

  describe('prepareList', () => {
    let options;

    beforeEach(() => {
      options = data.get('items');
      spyOn(instance, 'highlightMatches');
    });

    describe('when no filter is applied', () => {
      it('returns the original options as JSON', () => {
        expect(instance.prepareList(options)).toEqual(options.toJS());
      });
    });

    describe('when a filter is being applied', () => {
      describe('when matches are found', () => {
        it('returns matched items with formatted matching text', () => {
          instance.state.filter = 'fo';
          instance.prepareList(options);
          expect(instance.highlightMatches).toHaveBeenCalled();
        });
      });

      describe('when no matches are found', () => {
        it('returns an empty object', () => {
          instance.state.filter = 'xXx';
          expect(instance.prepareList(options)).toEqual([]);
        });
      })
    });
  });

  describe('inputProps', () => {
    it('sets props to defined values', () => {
      expect(instance.inputProps.className).toMatch('ui-dropdown__input');
      spyOn(instance, 'handleFocus');
      instance.inputProps.onFocus();
      expect(instance.handleFocus).toHaveBeenCalled();
    });

    describe('when filtering is active', () => {
      it('sets value to the current filter string', () => {
        instance.state.filter = 'f'
        expect(instance.inputProps.value).toEqual('f');
      });
    });

    describe('when filtering is not active', () => {
      it('sets value to the corresponding value in the hidden input', () => {
        expect(instance.inputProps.value).toEqual('bar');
      });
    });

    describe('when filter is enabled', () => {
      it('sets the input to not be readonly', () => {
        expect(instance.inputProps.readOnly).toBeFalsy();
      });
    });

    describe('when filter is disabled', () => {
      it('sets the input to be readonly', () => {
        expect(instanceNoFilter.inputProps.readOnly).toBeTruthy();
      });
    });
  });

  describe('hiddenInputProps', () => {
    it('sets the hidden props to the defined values', () => {
      expect(instance.hiddenInputProps.ref).toEqual('hidden');
      expect(instance.hiddenInputProps.type).toEqual('hidden');
      expect(instance.hiddenInputProps.readOnly).toBeTruthy();
      expect(instance.hiddenInputProps.name).toEqual(instance.props.name);
      expect(instance.hiddenInputProps.value).toEqual(instance.props.value);
    });
  });

  describe('rootClass', () => {
    it('returns the root class name', () => {
      expect(instance.rootClass).toEqual('ui-dropdown');
    });
  });

  describe('mainClasses', () => {
    it('returns the main class names', () => {
      expect(instance.mainClasses).toMatch('ui-dropdown');
    });
  });

  describe('inputClasses', () => {
    it('returns the input class names', () => {
      expect(instance.inputClasses).toMatch('ui-dropdown__input');
    });

    describe('when filtering is active', () => {
      it('adds a filter class', () => {
        instance.state.filter = 'a';
        expect(instance.inputClasses).toMatch('ui-dropdown__input ui-dropdown__input--filter');
      });
    });
  });

  describe('listHTML', () => {
    describe('when the dropdown is open', () => {
      it('sets the list classname', () => {
        TestUtils.Simulate.focus(input[0]);
        expect(instance.listHTML.props.className).toEqual('ui-dropdown__list common-list')
      });
    });

    describe('when the dropdown is closed', () => {
      it('adds hidden to the classname', () => {
        expect(instance.listHTML.props.className).toMatch('hidden')
      });
    });

    it('returns an unordered list containing the options', () => {
      expect(instance.listHTML.ref).toEqual('list');
      expect(instance.listHTML.props.children.length).toEqual(4);
    });
  });

  describe("render", () => {
    it("renders a hidden input", () => {
      input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input')[1];
      expect(input.tagName).toEqual("INPUT");
      expect(input.type).toEqual('hidden');
    });

    it("renders a visible input", () => {
      input = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input')[0];
      expect(input.tagName).toEqual("INPUT");
    });

    it("renders a ul", () => {
      let ul = instance.refs.list;
      expect(ul.tagName).toEqual("UL");
      expect(ul.classList[1]).toEqual("hidden");
    });

    describe("render with options", () => {
      let ul, listItems;

      beforeEach(() => {
        ul = instance.refs.list;
        listItems = ul.childNodes;
      });

      it("renders a li with results", () => {
        expect(listItems.length).toEqual(4);
        expect(listItems[0].value).toEqual(1);
        expect(listItems[0].textContent).toEqual("foo");
        expect(listItems[1].value).toEqual(2);
        expect(listItems[1].textContent).toEqual("bar");
      });

      it("sets the highlighted class on the relevant option", () => {
        instance.setState({
          highlighted: 2
        });
        expect(listItems[0].className).toEqual("ui-dropdown__item common-list__item");
        expect(listItems[1].className).toEqual("ui-dropdown__item common-list__item ui-dropdown__item--highlighted common-list__item--highlighted ui-dropdown__item--selected common-list__item--selected");
      });
    });
  });

});
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var markdown = require( "markdown" ).markdown;
var fs = require('fs');
app.get('/', function(req, res){
        res.sendFile(__dirname + '/chat.html');
        });
var users = 0;
io.on('connection', function(socket){
      users++;
      io.emit('connections', users);
      socket.on('chat message', function(msg){
                io.emit('chat message', markdown.toHTML(msg));
                });
      socket.on('users', function(){
                io.emit('connections', users);
                });
      socket.on('disconnect', function(){
                users--;
                io.emit('connections', users);
        });
      });
http.listen(3000, function(){
            console.log('listening on *:3000');
            });
<commit_msg>Update app.js<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var markdown = require( "markdown" ).markdown;
var fs = require('fs');
app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
        });
var users = 0;
io.on('connection', function(socket){
      users++;
      io.emit('connections', users);
      socket.on('chat message', function(msg){
                io.emit('chat message', markdown.toHTML(msg));
                });
      socket.on('users', function(){
                io.emit('connections', users);
                });
      socket.on('disconnect', function(){
                users--;
                io.emit('connections', users);
        });
      });
http.listen(3000, function(){
            console.log('listening on *:3000');
            });
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.9.3
(function() {
  var Client, Gist, HttpError, Issue, Label, Me, Milestone, Notification, Org, Pr, Release, Repo, Search, Team, User, extend, request, url,
    extend1 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    slice = [].slice;

  request = require('request');

  url = require('url');

  Me = require('./me');

  User = require('./user');

  Repo = require('./repo');

  Org = require('./org');

  Gist = require('./gist');

  Team = require('./team');

  Pr = require('./pr');

  Release = require('./release');

  Issue = require('./issue');

  Milestone = require('./milestone');

  Label = require('./label');

  Notification = require('./notification');

  extend = require('deep-extend');

  Search = require('./search');

  HttpError = (function(superClass) {
    extend1(HttpError, superClass);

    function HttpError(message, statusCode, headers, body1) {
      this.message = message;
      this.statusCode = statusCode;
      this.headers = headers;
      this.body = body1;
    }

    return HttpError;

  })(Error);

  Client = (function() {
    function Client(token1, options1) {
      this.token = token1;
      this.options = options1;
      this.limit = bind(this.limit, this);
      this.requestOptions = bind(this.requestOptions, this);
      this.request = this.options && this.options.request || request;
      this.requestDefaults = {
        headers: {
          'User-Agent': 'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
        }
      };
    }

    Client.prototype.me = function() {
      return new Me(this);
    };

    Client.prototype.user = function(name) {
      return new User(name, this);
    };

    Client.prototype.repo = function(name) {
      return new Repo(name, this);
    };

    Client.prototype.org = function(name) {
      return new Org(name, this);
    };

    Client.prototype.gist = function() {
      return new Gist(this);
    };

    Client.prototype.team = function(id) {
      return new Team(id, this);
    };

    Client.prototype.pr = function(repo, number) {
      return new Pr(repo, number, this);
    };

    Client.prototype.release = function(repo, number) {
      return new Release(repo, number, this);
    };

    Client.prototype.search = function() {
      return new Search(this);
    };

    Client.prototype.issue = function(repo, number) {
      return new Issue(repo, number, this);
    };

    Client.prototype.milestone = function(repo, number) {
      return new Milestone(repo, number, this);
    };

    Client.prototype.label = function(repo, name) {
      return new Label(repo, name, this);
    };

    Client.prototype.notification = function(id) {
      return new Notification(id, this);
    };

    Client.prototype.requestOptions = function(params1, params2) {
      return extend(this.requestDefaults, params1, params2);
    };

    Client.prototype.buildUrl = function(path, pageOrQuery, per_page) {
      var _url, q, query, separator, urlFromPath;
      if (path == null) {
        path = '/';
      }
      if (pageOrQuery == null) {
        pageOrQuery = null;
      }
      if (per_page == null) {
        per_page = null;
      }
      if ((pageOrQuery != null) && typeof pageOrQuery === 'object') {
        query = pageOrQuery;
      } else {
        query = {};
        if (pageOrQuery != null) {
          query.page = pageOrQuery;
        }
        if (per_page != null) {
          query.per_page = per_page;
        }
      }
      if (this.token) {
        if (typeof this.token === 'string') {
          query.access_token = this.token;
        } else if (typeof this.token === 'object' && this.token.id) {
          query.client_id = this.token.id;
          query.client_secret = this.token.secret;
        }
      }
      if (query.q) {
        q = query.q;
        delete query.q;
        if (Object.keys(query).length) {
          separator = '&';
        } else {
          separator = '?';
        }
      }
      urlFromPath = url.parse(path);
      _url = url.format({
        protocol: urlFromPath.protocol || this.options && this.options.protocol || "https:",
        auth: urlFromPath.auth || (this.token && this.token.username && this.token.password ? this.token.username + ":" + this.token.password : ''),
        hostname: urlFromPath.hostname || this.options && this.options.hostname || "api.github.com",
        port: urlFromPath.port || this.options && this.options.port,
        pathname: urlFromPath.pathname,
        query: query
      });
      if (q) {
        _url += separator + "q=" + q;
        query.q = q;
      }
      return _url;
    };

    Client.prototype.errorHandle = function(res, body, callback) {
      var err, ref;
      if (Math.floor(res.statusCode / 100) === 5) {
        return callback(new HttpError('Error ' + res.statusCode, res.statusCode, res.headers));
      }
      if (typeof body === 'string') {
        try {
          body = JSON.parse(body || '{}');
        } catch (_error) {
          err = _error;
          return callback(err);
        }
      }
      if (body.message && ((ref = res.statusCode) === 400 || ref === 401 || ref === 403 || ref === 404 || ref === 410 || ref === 422)) {
        return callback(new HttpError(body.message, res.statusCode, res.headers, body));
      }
      return callback(null, res.statusCode, body, res.headers);
    };

    Client.prototype.get = function() {
      var callback, i, params, path;
      path = arguments[0], params = 3 <= arguments.length ? slice.call(arguments, 1, i = arguments.length - 1) : (i = 1, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET'
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.getNoFollow = function() {
      var callback, i, params, path;
      path = arguments[0], params = 3 <= arguments.length ? slice.call(arguments, 1, i = arguments.length - 1) : (i = 1, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET',
        followRedirect: false
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.getOptions = function() {
      var callback, i, options, params, path;
      path = arguments[0], options = arguments[1], params = 4 <= arguments.length ? slice.call(arguments, 2, i = arguments.length - 1) : (i = 2, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET'
      }, options), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.post = function(path, content, options, callback) {
      var reqDefaultOption, reqOpt;
      if ((callback == null) && typeof options === 'function') {
        callback = options;
        options = {};
      }
      reqDefaultOption = {
        uri: this.buildUrl(path, options.query),
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      };
      if (content) {
        reqDefaultOption.body = JSON.stringify(content);
      }
      reqOpt = this.requestOptions(extend(reqDefaultOption, options));
      return this.request(reqOpt, (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.patch = function(path, content, callback) {
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'PATCH',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json'
        }
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.put = function(path, content, options, callback) {
      if (!callback && options) {
        callback = options;
        options = {
          'Content-Type': 'application/json'
        };
      }
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'PUT',
        body: JSON.stringify(content),
        headers: options
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.del = function(path, content, callback) {
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'DELETE',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json'
        }
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.limit = function(callback) {
      return this.get('/rate_limit', function(err, s, b) {
        if (err) {
          return callback(err);
        }
        if (s !== 200) {
          return callback(new HttpError('Client rate_limit error', s));
        } else {
          return callback(null, b.rate.remaining, b.rate.limit, b);
        }
      });
    };

    return Client;

  })();

  module.exports = function() {
    var credentials, token;
    token = arguments[0], credentials = 2 <= arguments.length ? slice.call(arguments, 1) : [];
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Client, [token].concat(slice.call(credentials)), function(){});
  };

}).call(this);
<commit_msg>Added support for since based pagination<commit_after>// Generated by CoffeeScript 1.9.3
(function() {
  var Client, Gist, HttpError, Issue, Label, Me, Milestone, Notification, Org, Pr, Release, Repo, Search, Team, User, extend, request, url,
    extend1 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    slice = [].slice;

  request = require('request');

  url = require('url');

  Me = require('./me');

  User = require('./user');

  Repo = require('./repo');

  Org = require('./org');

  Gist = require('./gist');

  Team = require('./team');

  Pr = require('./pr');

  Release = require('./release');

  Issue = require('./issue');

  Milestone = require('./milestone');

  Label = require('./label');

  Notification = require('./notification');

  extend = require('deep-extend');

  Search = require('./search');

  HttpError = (function(superClass) {
    extend1(HttpError, superClass);

    function HttpError(message, statusCode, headers, body1) {
      this.message = message;
      this.statusCode = statusCode;
      this.headers = headers;
      this.body = body1;
    }

    return HttpError;

  })(Error);

  Client = (function() {
    function Client(token1, options1) {
      this.token = token1;
      this.options = options1;
      this.limit = bind(this.limit, this);
      this.requestOptions = bind(this.requestOptions, this);
      this.request = this.options && this.options.request || request;
      this.requestDefaults = {
        headers: {
          'User-Agent': 'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
        }
      };
    }

    Client.prototype.me = function() {
      return new Me(this);
    };

    Client.prototype.user = function(name) {
      return new User(name, this);
    };

    Client.prototype.repo = function(name) {
      return new Repo(name, this);
    };

    Client.prototype.org = function(name) {
      return new Org(name, this);
    };

    Client.prototype.gist = function() {
      return new Gist(this);
    };

    Client.prototype.team = function(id) {
      return new Team(id, this);
    };

    Client.prototype.pr = function(repo, number) {
      return new Pr(repo, number, this);
    };

    Client.prototype.release = function(repo, number) {
      return new Release(repo, number, this);
    };

    Client.prototype.search = function() {
      return new Search(this);
    };

    Client.prototype.issue = function(repo, number) {
      return new Issue(repo, number, this);
    };

    Client.prototype.milestone = function(repo, number) {
      return new Milestone(repo, number, this);
    };

    Client.prototype.label = function(repo, name) {
      return new Label(repo, name, this);
    };

    Client.prototype.notification = function(id) {
      return new Notification(id, this);
    };

    Client.prototype.requestOptions = function(params1, params2) {
      return extend(this.requestDefaults, params1, params2);
    };

    Client.prototype.buildUrl = function(path, pageOrQuery, per_page, since) {
      var _url, q, query, separator, urlFromPath;
      if (path == null) {
        path = '/';
      }
      if (pageOrQuery == null) {
        pageOrQuery = null;
      }
      if (per_page == null) {
        per_page = null;
      }
      if ((pageOrQuery != null) && typeof pageOrQuery === 'object') {
        query = pageOrQuery;
      } else {
        query = {};
        if (pageOrQuery != null) {
          if (typeof since != undefined && since) query.since = pageOrQuery;
          else query.page = pageOrQuery;
        }
        if (per_page != null) {
          query.per_page = per_page;
        }
      }
      if (this.token) {
        if (typeof this.token === 'string') {
          query.access_token = this.token;
        } else if (typeof this.token === 'object' && this.token.id) {
          query.client_id = this.token.id;
          query.client_secret = this.token.secret;
        }
      }
      if (query.q) {
        q = query.q;
        delete query.q;
        if (Object.keys(query).length) {
          separator = '&';
        } else {
          separator = '?';
        }
      }
      urlFromPath = url.parse(path);
      _url = url.format({
        protocol: urlFromPath.protocol || this.options && this.options.protocol || "https:",
        auth: urlFromPath.auth || (this.token && this.token.username && this.token.password ? this.token.username + ":" + this.token.password : ''),
        hostname: urlFromPath.hostname || this.options && this.options.hostname || "api.github.com",
        port: urlFromPath.port || this.options && this.options.port,
        pathname: urlFromPath.pathname,
        query: query
      });
      if (q) {
        _url += separator + "q=" + q;
        query.q = q;
      }
      return _url;
    };

    Client.prototype.errorHandle = function(res, body, callback) {
      var err, ref;
      if (Math.floor(res.statusCode / 100) === 5) {
        return callback(new HttpError('Error ' + res.statusCode, res.statusCode, res.headers));
      }
      if (typeof body === 'string') {
        try {
          body = JSON.parse(body || '{}');
        } catch (_error) {
          err = _error;
          return callback(err);
        }
      }
      if (body.message && ((ref = res.statusCode) === 400 || ref === 401 || ref === 403 || ref === 404 || ref === 410 || ref === 422)) {
        return callback(new HttpError(body.message, res.statusCode, res.headers, body));
      }
      return callback(null, res.statusCode, body, res.headers);
    };

    Client.prototype.get = function() {
      var callback, i, params, path;
      path = arguments[0], params = 3 <= arguments.length ? slice.call(arguments, 1, i = arguments.length - 1) : (i = 1, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET'
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.getNoFollow = function() {
      var callback, i, params, path;
      path = arguments[0], params = 3 <= arguments.length ? slice.call(arguments, 1, i = arguments.length - 1) : (i = 1, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET',
        followRedirect: false
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.getOptions = function() {
      var callback, i, options, params, path;
      path = arguments[0], options = arguments[1], params = 4 <= arguments.length ? slice.call(arguments, 2, i = arguments.length - 1) : (i = 2, []), callback = arguments[i++];
      return this.request(this.requestOptions({
        uri: this.buildUrl.apply(this, [path].concat(slice.call(params))),
        method: 'GET'
      }, options), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.post = function(path, content, options, callback) {
      var reqDefaultOption, reqOpt;
      if ((callback == null) && typeof options === 'function') {
        callback = options;
        options = {};
      }
      reqDefaultOption = {
        uri: this.buildUrl(path, options.query),
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      };
      if (content) {
        reqDefaultOption.body = JSON.stringify(content);
      }
      reqOpt = this.requestOptions(extend(reqDefaultOption, options));
      return this.request(reqOpt, (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.patch = function(path, content, callback) {
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'PATCH',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json'
        }
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.put = function(path, content, options, callback) {
      if (!callback && options) {
        callback = options;
        options = {
          'Content-Type': 'application/json'
        };
      }
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'PUT',
        body: JSON.stringify(content),
        headers: options
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.del = function(path, content, callback) {
      return this.request(this.requestOptions({
        uri: this.buildUrl(path),
        method: 'DELETE',
        body: JSON.stringify(content),
        headers: {
          'Content-Type': 'application/json'
        }
      }), (function(_this) {
        return function(err, res, body) {
          if (err) {
            return callback(err);
          }
          return _this.errorHandle(res, body, callback);
        };
      })(this));
    };

    Client.prototype.limit = function(callback) {
      return this.get('/rate_limit', function(err, s, b) {
        if (err) {
          return callback(err);
        }
        if (s !== 200) {
          return callback(new HttpError('Client rate_limit error', s));
        } else {
          return callback(null, b.rate.remaining, b.rate.limit, b);
        }
      });
    };

    return Client;

  })();

  module.exports = function() {
    var credentials, token;
    token = arguments[0], credentials = 2 <= arguments.length ? slice.call(arguments, 1) : [];
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Client, [token].concat(slice.call(credentials)), function(){});
  };

}).call(this);
<|endoftext|>


<commit_before>(function (O2) {
    /**
     * @property bar.store.users
     */
    O2.createObject('bar.store.users', [
        {name:'Daedalus', pref: [16]},
        {name:'Neo', pref: [16, 0, 8]},
        {name:'Priguns', pref: [16, 0]},
        {name:'Reebox', pref: [2]},
        {name:'Ralphy', pref: [16, 0]},
        {name:'Briscoto', pref: [16, 0]},
        {name:'Alex', pref: [16, 0]},
        {name:'Max', pref: [12]},
        {name:'Sam', pref: [16, 0]},
        {name:'Loïc', pref: [16, 0]},
        {name:'Damien', pref: [16, 0]},
        {name:'Laurent F.', pref: [16, 0]}
    ]);
})(O2);<commit_msg>Ajout de Rémi F<commit_after>(function (O2) {
    /**
     * @property bar.store.users
     */
    O2.createObject('bar.store.users', [
        {name:'Daedalus', pref: [16]},
        {name:'Neo', pref: [16, 0, 8]},
        {name:'Priguns', pref: [16, 0]},
        {name:'Reebox', pref: [2]},
        {name:'Ralphy', pref: [16, 0]},
        {name:'Briscoto', pref: [16, 0]},
        {name:'Alex', pref: [16, 0]},
        {name:'Max', pref: [12]},
        {name:'Sam', pref: [16, 0]},
        {name:'Loïc', pref: [16, 0]},
        {name:'Damien', pref: [16, 0]},
        {name:'Laurent F.', pref: [16, 0]},
        {name:'Rémi F.', pref: [16, 0]}
    ]);
})(O2);
<|endoftext|>


<commit_before><commit_msg>Fixed an issue where data in first row is not saved when an EditGrid is shown conditionally and Open when Empty is checked<commit_after><|endoftext|>


<commit_before>/*
  Copyright 2015 One Zero Capital

  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.
*/

Autoencoder = function(headers, splits, Ws, bs) {
  this.headers = headers;
  this.splits = splits;
  this.Ws = Ws;
  this.bs = bs;
  this.splitsByJ = [];
  for (var i = 0; i < this.splits.length; i++) {
    var j = this.splits[i][0];
    var x = this.splits[i][1];
    while (this.splitsByJ.length <= j) this.splitsByJ.push([]);
    this.splitsByJ[j].push(x);
  }
}

Autoencoder.deserialize = function(data) {
  return new Autoencoder(data['headers'],
			 data['splits'],
			 data['Ws'],
			 data['bs']);
}

Autoencoder.prototype.getOutput = function(row) {
  var input = [];
  for (var j = 0; j < this.splitsByJ.length; j++) {
    // Instead of encoding it as a -1 or +1 input, we smooth it using a tanh representation
    // See description in getPdfs, it's the same idea
    var D = (this.splitsByJ[j][this.splitsByJ[j].length-1] - this.splitsByJ[j][0]) / this.splitsByJ[j].length;

    for (var i = 0; i < this.splitsByJ[j].length; i++) {
      var x = this.splitsByJ[j][i];
      if (row[j] == undefined) {
	input.push(0.0);
      } else {
	input.push(Math.tanh((x - row[j]) / D));
      }
    }
  }

  // Normalize input
  var k = 0;
  for (var j = 0; j < row.length; j++)
    k += row[j] != undefined ? 1 : 0;
  var row = input.map(function(x) { return x * Math.pow(k+1, -0.5); });

  for (var layer = 0; layer < this.Ws.length; layer++) {
    // console.log(this.Ws[layer].length + ' * ' + this.Ws[layer][0].length);
    // Compute row * Ws[layer] + bs[layer]
    var nextRow = [];
    for (var b = 0; b < this.bs[layer].length; b++)
      nextRow.push(this.bs[layer][b]);

    for (var a = 0; a < this.Ws[layer].length; a++)
      for (var b = 0; b < this.Ws[layer][0].length; b++)
	nextRow[b] += row[a] * this.Ws[layer][a][b];

    if (layer < this.Ws.length - 1) {
      for (var b = 0; b < this.bs[layer].length; b++)
	nextRow[b] = Math.max(0, nextRow[b]); // relu
    } else {
      for (var b = 0; b < this.bs[layer].length; b++)
	nextRow[b] = 1.0 / (1 + Math.exp(-nextRow[b]));
    }
    row = nextRow
  }
  return row;
}

Autoencoder.prototype.getCdfs = function(row) {
  var row = this.getOutput(row);
  var cdfs = [];
  for (var i = 0; i < this.splits.length; i++) {
    var j = this.splits[i][0];
    var x = this.splits[i][1];
    while (cdfs.length <= j)
      cdfs.push({'xy': []});
    cdfs[j].xy.push({'x': x, 'y': row[i]});
  }
  return cdfs;
}

Autoencoder.prototype.getPdfs = function(row, points) {
  // We cheat a bit and define some smoothing
  // Let's approximate the CDF as a sum of sigmoids:
  // CDF = sum_i (row[i+1] - row[i]) * sigm((x' - x) / D)
  // Where i2 is a fractional version of i
  // Then take the derivative to get the PDF
  var cdfs = this.getCdfs(row);

  if (points == undefined)
    points = 100;

  var pdfs = [];

  for (var j = 0; j < row.length; j++) {
    pdfs.push({'xy': [], 'xyQuartile': []});

    var D = (cdfs[j].xy[cdfs[j].xy.length-1].x - cdfs[j].xy[0].x) / cdfs[j].xy.length;

    for (var p = 0; p < points; p++) {
      var x = cdfs[j].xy[0].x + (cdfs[j].xy[cdfs[j].xy.length-1].x - cdfs[j].xy[0].x) * p / (points - 1);
      var y = 0.0;
      var yCdf = 0.0;

      for (var i = 0; i < cdfs[j].xy.length; i++) {
	var xp = cdfs[j].xy[i].x;
	var d = cdfs[j].xy[i].y;
	if (i > 0) d -= cdfs[j].xy[i-1].y;
	var delta = (x - xp) / D;
	var s = 1.0 / (1 + Math.exp(-delta));
	y += d * s * (1 - s) / D;
	yCdf += d * s;
      }
      pdfs[j].xy.push({'x': x, 'y': y});

      if (yCdf > 0.25 && yCdf < 0.75) {
	pdfs[j].xyQuartile.push({'x': x, 'y': y});
      }
    }
  }
  return pdfs;
}
<commit_msg>better smoothing<commit_after>/*
  Copyright 2015 One Zero Capital

  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.
*/

Autoencoder = function(headers, splits, Ws, bs) {
  this.headers = headers;
  this.splits = splits;
  this.Ws = Ws;
  this.bs = bs;
  this.splitsByJ = [];
  for (var i = 0; i < this.splits.length; i++) {
    var j = this.splits[i][0];
    var x = this.splits[i][1];
    while (this.splitsByJ.length <= j) this.splitsByJ.push([]);
    this.splitsByJ[j].push(x);
  }

  this.Ds = []; // Smoothing factors
  for (var j = 0; j < this.splitsByJ.length; j++) {
    this.Ds.push([]);
    for (var i = 0; i < this.splitsByJ[j].length; i++) {
      var iLo = i > 0 ? i - 1 : i;
      var iHi = i < this.splitsByJ[j].length - 1 ? i + 1 : i;
      this.Ds[j].push((this.splitsByJ[j][iHi] - this.splitsByJ[j][iLo]) / (iHi - iLo));
    }
  }
}

Autoencoder.deserialize = function(data) {
  return new Autoencoder(data['headers'],
			 data['splits'],
			 data['Ws'],
			 data['bs']);
}

Autoencoder.prototype.getOutput = function(row) {
  var input = [];
  for (var j = 0; j < this.splitsByJ.length; j++) {
    for (var i = 0; i < this.splitsByJ[j].length; i++) {
      var x = this.splitsByJ[j][i];
      // Instead of encoding it as a -1 or +1 input, we smooth it using a tanh representation
      // See description in getPdfs, it's the same idea
      var D = this.Ds[j][i];

      if (row[j] == undefined) {
	input.push(0.0);
      } else {
	input.push(Math.tanh((x - row[j]) / D));
      }
    }
  }

  // Normalize input
  var k = 0;
  for (var j = 0; j < row.length; j++)
    k += row[j] != undefined ? 1 : 0;
  var row = input.map(function(x) { return x * Math.pow(k+1, -0.5); });

  for (var layer = 0; layer < this.Ws.length; layer++) {
    // console.log(this.Ws[layer].length + ' * ' + this.Ws[layer][0].length);
    // Compute row * Ws[layer] + bs[layer]
    var nextRow = [];
    for (var b = 0; b < this.bs[layer].length; b++)
      nextRow.push(this.bs[layer][b]);

    for (var a = 0; a < this.Ws[layer].length; a++)
      for (var b = 0; b < this.Ws[layer][0].length; b++)
	nextRow[b] += row[a] * this.Ws[layer][a][b];

    if (layer < this.Ws.length - 1) {
      for (var b = 0; b < this.bs[layer].length; b++)
	nextRow[b] = Math.max(0, nextRow[b]); // relu
    } else {
      for (var b = 0; b < this.bs[layer].length; b++)
	nextRow[b] = 1.0 / (1 + Math.exp(-nextRow[b]));
    }
    row = nextRow
  }
  return row;
}

Autoencoder.prototype.getCdfs = function(row) {
  var row = this.getOutput(row);
  var cdfs = [];
  for (var i = 0; i < this.splits.length; i++) {
    var j = this.splits[i][0];
    var x = this.splits[i][1];
    while (cdfs.length <= j)
      cdfs.push({'xy': []});
    cdfs[j].xy.push({'x': x, 'y': row[i]});
  }
  return cdfs;
}

Autoencoder.prototype.getPdfs = function(row, points) {
  // We cheat a bit and define some smoothing
  // Let's approximate the CDF as a sum of sigmoids:
  // CDF = sum_i (row[i+1] - row[i]) * sigm((x' - x) / D)
  // Where i2 is a fractional version of i
  // Then take the derivative to get the PDF
  var cdfs = this.getCdfs(row);

  if (points == undefined)
    points = 100;

  var pdfs = [];

  for (var j = 0; j < row.length; j++) {
    pdfs.push({'xy': [], 'xyQuartile': []});

    for (var p = 0; p < points; p++) {
      var x = cdfs[j].xy[0].x + (cdfs[j].xy[cdfs[j].xy.length-1].x - cdfs[j].xy[0].x) * p / (points - 1);
      var y = 0.0;
      var yCdf = 0.0;

      for (var i = 0; i < cdfs[j].xy.length; i++) {
	var D = this.Ds[j][i];

	var xp = cdfs[j].xy[i].x;
	var d = cdfs[j].xy[i].y;
	if (i > 0) d -= cdfs[j].xy[i-1].y;
	var delta = (x - xp) / D;
	var s = 1.0 / (1 + Math.exp(-delta));
	y += d * s * (1 - s) / D;
	yCdf += d * s;
      }
      pdfs[j].xy.push({'x': x, 'y': y});

      if (yCdf > 0.25 && yCdf < 0.75) {
	pdfs[j].xyQuartile.push({'x': x, 'y': y});
      }
    }
  }
  return pdfs;
}
<|endoftext|>