<commit_before>/**
 * @jest-environment node
 */
"use strict";

const shell = require("shelljs");
const util = require("../fixtures/util");
const kill = require("../utils/psKill");
const path = require("path");
const fs = require("fs");

shell.config.silent = true;

const stageName = 'stage-start-spa';

describe('razzle start', () => {
  describe('razzle basic example', () => {

    beforeAll(() => {
      util.teardownStage(stageName);
    });

    jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000; // eslint-disable-line no-undef

    it('should start a dev server for spa mode', () => {
      util.setupStageWithExample(stageName, 'basic-spa');
      let outputTest;
      const run = new Promise(resolve => {
        const child = shell.exec(
          `${path.join('./node_modules/.bin/razzle')} start --type=spa`,
          () => {
            resolve(outputTest);
          }
        );
        child.stdout.on('data', data => {
          if (data.includes('> SPA Started on port 3000')) {
            shell.exec('sleep 5');
            const devServerOutput = shell.exec(
              'curl -sb -o "" localhost:3000/static/js/bundle.js'
            );
            outputTest = devServerOutput.stdout.includes("React");
            kill(child.pid);
          }
        });
      });
      return run.then((test) => expect(test).toBeTruthy());
    });

    jasmine.DEFAULT_TIMEOUT_INTERVAL = 400000; // eslint-disable-line no-undef

    it('should build and run in spa mode', () => {
      util.setupStageWithExample(stageName, 'basic-spa');
      let outputTest;
      shell.exec(`${path.join('./node_modules/.bin/razzle')} build --type=spa`);
      const run = new Promise(resolve => {
        const child = shell.exec(
          `${path.join('./node_modules/.bin/serve')} -s ${path.join('build/public')}`,
          () => {
            resolve(outputTest);
          }
        );
        child.stdout.on('data', data => {
          console.log(data);
          if (data.includes('http://localhost:5000')) {
            shell.exec('sleep 5');
            // we use serve package and it will run in prot 5000
            const output = shell.exec("curl -I localhost:5000");
            outputTest = output.stdout.includes("200");
            kill(child.pid);
          }
        });
        child.stderr.on('data', data => {
          console.log(data);
          kill(child.pid);
        });
      });
      return run.then((test) => expect(test).toBeTruthy());
    });

    afterEach(() => {
      util.teardownStage(stageName);
    });

  });
});
<commit_msg>dev-infra: wait longer to debug ci tests<commit_after>/**
 * @jest-environment node
 */
"use strict";

const shell = require("shelljs");
const util = require("../fixtures/util");
const kill = require("../utils/psKill");
const path = require("path");
const fs = require("fs");

shell.config.silent = true;

const stageName = 'stage-start-spa';

describe('razzle start', () => {
  describe('razzle basic example', () => {

    beforeAll(() => {
      util.teardownStage(stageName);
    });

    jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000; // eslint-disable-line no-undef

    it('should start a dev server for spa mode', () => {
      util.setupStageWithExample(stageName, 'basic-spa');
      let outputTest;
      const run = new Promise(resolve => {
        const child = shell.exec(
          `${path.join('./node_modules/.bin/razzle')} start --type=spa`,
          () => {
            resolve(outputTest);
          }
        );
        child.stdout.on('data', data => {
          if (data.includes('> SPA Started on port 3000')) {
            shell.exec('sleep 5');
            const devServerOutput = shell.exec(
              'curl -sb -o "" localhost:3000/static/js/bundle.js'
            );
            outputTest = devServerOutput.stdout.includes("React");
            kill(child.pid);
          }
        });
      });
      return run.then((test) => expect(test).toBeTruthy());
    });

    jasmine.DEFAULT_TIMEOUT_INTERVAL = 400000; // eslint-disable-line no-undef

    it('should build and run in spa mode', () => {
      util.setupStageWithExample(stageName, 'basic-spa');
      let outputTest;
      shell.exec(`${path.join('./node_modules/.bin/razzle')} build --type=spa`);
      const run = new Promise(resolve => {
        const child = shell.exec(
          `${path.join('./node_modules/.bin/serve')} -s ${path.join('build/public')}`,
          () => {
            shell.exec('sleep 5');
            resolve(outputTest);
          }
        );
        child.stdout.on('data', data => {
          console.log(data);
          if (data.includes('http://localhost:5000')) {
            shell.exec('sleep 5');
            // we use serve package and it will run in prot 5000
            const output = shell.exec("curl -I localhost:5000");
            outputTest = output.stdout.includes("200");
            kill(child.pid);
          }
        });
        child.stderr.on('data', data => {
          console.log(data);
          kill(child.pid);
        });
      });
      return run.then((test) => expect(test).toBeTruthy());
    });

    afterEach(() => {
      util.teardownStage(stageName);
    });

  });
});
<|endoftext|>


<commit_before>/**
  * LzMouseKernel.js
  *
  * @copyright Copyright 2007, 2009 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.
  *
  * @topic Kernel
  * @subtopic DHTML
  * @author Max Carlson <max@openlaszlo.org>
  */

// Receives mouse events from the runtime
var LzMouseKernel = {
    // the last view to receive the mouse down event
    __lastMouseDown: null
    ,__x: 0
    ,__y: 0
    ,owner: null
    ,__showncontextmenu: null
    // handles global mousedown, move events
    ,__mouseEvent: function(e) {
        if (!e) {
            e = window.event;
            var targ = e.srcElement;
        } else {
            var targ = e.target;
        }
        var eventname = 'on' + e.type;

        // send option/shift/ctrl key events
        if (window['LzKeyboardKernel'] && LzKeyboardKernel['__updateControlKeys']) {
            LzKeyboardKernel.__updateControlKeys(e);
        }

        var lzinputproto = window['LzInputTextSprite'] && LzInputTextSprite.prototype;
        if (lzinputproto && lzinputproto.__lastshown != null) {
            if (LzSprite.prototype.quirks.fix_ie_clickable) {
                lzinputproto.__hideIfNotFocused(eventname, targ);
            } else if (eventname != 'onmousemove') {
                lzinputproto.__hideIfNotFocused();
            }
        }

        if (eventname == 'onmousemove') {
            LzMouseKernel.__sendMouseMove(e);
            // hide any active inputtexts to allow clickable to work - see LPP-5447...
            if (lzinputproto && lzinputproto.__lastshown != null) {
                if (targ && targ.owner && ! (targ.owner instanceof LzInputTextSprite)) {
                    if (! lzinputproto.__lastshown.__isMouseOver()) {
                        lzinputproto.__lastshown.__hide();
                    }
                }
            }

        } else if (eventname == 'oncontextmenu' || (eventname == 'onmousedown' && e.button == 2)) {
            // If browser supports DOM mouse events level 2 feature,
            // trigger menu on mousedown-right, and suppress the
            // system builtin menu when the oncontextmenu event comes.
            if (LzSprite.prototype.quirks.has_dom2_mouseevents) {
                if (eventname == 'onmousedown') {
                    if (targ) {
                    // update mouse position, required for Safari
                        LzMouseKernel.__sendMouseMove(e);
                        return LzMouseKernel.__showContextMenu(e);
                    }
                } else if (eventname == 'oncontextmenu') {
                    var cmenu = LzMouseKernel.__findContextMenu(e);
                    if (cmenu != null) {
                        // If there is an LZX menu defined,
                        // suppress display of browser's builtin menu
                        return false;
                    } else {
                        // display system builtin menu
                        return true;
                    }
                }
            } else if (eventname == 'oncontextmenu') {
                // If there is no DOM level 2 mouse event support,
                // then use the oncontextmenu event to display context menu
                if (targ) {
                    // update mouse position, required for Safari
                    LzMouseKernel.__sendMouseMove(e);
                    return LzMouseKernel.__showContextMenu(e);
                }
            }
        } else if (e.button != 2) {
            LzMouseKernel.__sendEvent(eventname);
        }
        //Debug.write('LzMouseKernel event', eventname);
    }
    // sends mouse events to the callback
    ,__sendEvent: function(eventname, view) {
        // hide context menus and skip events - see LPP-8189
        if (eventname == 'onclick') {
            if (LzMouseKernel.__showncontextmenu) {
                LzMouseKernel.__showncontextmenu.__hide();
            }
            if (! view) {
                // don't send global onclick events
                return;
            }
        }
        if (LzMouseKernel.__callback) {
            LzMouseKernel.__scope[LzMouseKernel.__callback](eventname, view);
        }
        //Debug.write('LzMouseKernel event', eventname);
    }
    ,__callback: null
    ,__scope: null
    // handles global mouseup events
    ,__mouseupEvent: function (e) {
        if (LzMouseKernel.__lastMouseDown != null) {
            // call mouseup on the sprite that got the last mouse down
            LzMouseKernel.__lastMouseDown.__globalmouseup(e);
        } else {
            LzMouseKernel.__mouseEvent(e);
        }
    }
    ,setCallback: function (scope, funcname) {
        this.__scope = scope;
        this.__callback = funcname;
    }
    ,__mousecontrol: false
    // Called to register/unregister global mouse events.
    ,setMouseControl: function (ison) {
        if (ison == LzMouseKernel.__mousecontrol) return;
        //Debug.write('mousecontrol', ison);
        LzMouseKernel.__mousecontrol = ison;
        if (ison) {
            lz.embed.attachEventHandler(document, 'mousemove', LzMouseKernel, '__mouseEvent');
            lz.embed.attachEventHandler(document, 'mousedown', LzMouseKernel, '__mouseEvent');
            lz.embed.attachEventHandler(document, 'mouseup', LzMouseKernel, '__mouseupEvent');
            lz.embed.attachEventHandler(document, 'click', LzMouseKernel, '__mouseEvent');
            // Correct possible cross-domain issues - see LPP-8093
            try {
                if (window.top != window) lz.embed.attachEventHandler(window.top.document, 'mouseup', LzMouseKernel, '__mouseupEvent');
            } catch (e) {
            }
        } else {
            lz.embed.removeEventHandler(document, 'mousemove', LzMouseKernel, '__mouseEvent');
            lz.embed.removeEventHandler(document, 'mousedown', LzMouseKernel, '__mouseEvent');
            lz.embed.removeEventHandler(document, 'mouseup', LzMouseKernel, '__mouseupEvent');
            lz.embed.removeEventHandler(document, 'click', LzMouseKernel, '__mouseEvent');
            // Correct possible cross-domain issues - see LPP-8093
            try {
                if (window.top != window) lz.embed.removeEventHandler(window.top.document, 'mouseup', LzMouseKernel, '__mouseupEvent');
            } catch (e) {
            }
        }
        // Prevent context menus in Firefox 1.5 - see LPP-2678
        document.oncontextmenu = ison ? LzMouseKernel.__mouseEvent : null;
    }
    ,__showhand: 'pointer'

    /**
    * Shows or hides the hand cursor for all clickable views.
    * @param Boolean show: true shows the hand cursor for buttons, false hides it
    */
    ,showHandCursor: function (show) {
        var c = show == true ? 'pointer' : 'default';
        this.__showhand = c;
        LzMouseKernel.setCursorGlobal(c);
    }

    /**
    * Sets the cursor to a resource
    * @param String c: cursor ID to use, or '' for default.  See
    * http://www.quirksmode.org/css/cursor.html for valid IDs
    */
    ,setCursorGlobal: function ( n ){
        if (LzSprite.prototype.quirks.no_cursor_colresize) {
            return;
        }
        var n = LzSprite.prototype.__defaultStyles.hyphenate(n);
        LzSprite.prototype.__setCSSClassProperty('.lzclickdiv', 'cursor', n);
        LzSprite.prototype.__setCSSClassProperty('.lzdiv', 'cursor', n);
        LzSprite.prototype.__setCSSClassProperty('.lzcanvasdiv', 'cursor', n);
        LzSprite.prototype.__setCSSClassProperty('.lzcanvasclickdiv', 'cursor', n);
    }

    /**
    * This function restores the default cursor if there is no locked cursor on
    * the screen.
    *
    * @access private
    */
    ,restoreCursor: function ( ){
        if (LzSprite.prototype.quirks.no_cursor_colresize) {
            return;
        }
        if ( LzMouseKernel.__amLocked ) return;
        LzSprite.prototype.__setCSSClassProperty('.lzclickdiv', 'cursor', LzMouseKernel.__showhand);
        LzSprite.prototype.__setCSSClassProperty('.lzdiv', 'cursor', 'default');
        LzSprite.prototype.__setCSSClassProperty('.lzcanvasdiv', 'cursor', 'default');
        LzSprite.prototype.__setCSSClassProperty('.lzcanvasclickdiv', 'cursor', 'default');
    }

    /**
    * Prevents the cursor from being changed until unlock is called.
    *
    */
    ,lock: function (){
        LzMouseKernel.__amLocked = true;
    }

    /**
    * Restores the default cursor.
    *
    */
    ,unlock: function (){
        LzMouseKernel.__amLocked = false;
        LzMouseKernel.restoreCursor();
    }

    ,disableMouseTemporarily: function (){
        this.setGlobalClickable(false);
        this.__resetonmouseover = true;
    }
    ,__resetonmouseover: false
    ,__resetMouse: function (){
        if (this.__resetonmouseover) {
            this.__resetonmouseover = false;
            this.setGlobalClickable(true);
            var cs = this.__cachedSelection;
            if (cs) {
                var sprite = cs.s;
                sprite.setSelection(cs.st, cs.st + cs.sz);
                cs = null;
            }
        }
    }
    ,__cachedSelection: null
    ,__globalClickable: true
    ,setGlobalClickable: function (isclickable){
        var el = document.getElementById('lzcanvasclickdiv');
        this.__globalClickable = isclickable;
        el.style.display = isclickable ? '' : 'none';
    }
    ,__sendMouseMove: function(e, offsetx, offsety) {
        // see http://www.quirksmode.org/js/events_properties.html#position
        if (e.pageX || e.pageY) {
            LzMouseKernel.__x = e.pageX;
            LzMouseKernel.__y = e.pageY;
        } else if (e.clientX || e.clientY) {
            // IE doesn't implement pageX/pageY, instead scrollLeft/scrollTop
            // needs to be added to clientX/clientY
            var body = document.body, docElem = document.documentElement;
            LzMouseKernel.__x = e.clientX + body.scrollLeft + docElem.scrollLeft;
            LzMouseKernel.__y = e.clientY + body.scrollTop + docElem.scrollTop;
        }
        if (offsetx) {
            LzMouseKernel.__x += offsetx;
        }
        if (offsety) {
            LzMouseKernel.__y += offsety;
        }
        if (e.type == 'mousemove') {
            LzMouseKernel.__sendEvent('onmousemove');
        }
    }
    ,__showContextMenu: function(e) {
        // show the default menu if not found...
        var cmenu = LzMouseKernel.__findContextMenu(e);
        if (cmenu) {
            cmenu.kernel.__show();
            return cmenu.kernel.showbuiltins;
        }
    }
    ,__findContextMenu: function(e) {
        // show the default menu if not found...
        var cmenu = LzSprite.__rootSprite.__contextmenu;
        var quirks = LzSprite.prototype.quirks;
        if (document.elementFromPoint) {
            var swf8mode = quirks.swf8_contextmenu;
            var x = LzMouseKernel.__x;
            var y = LzMouseKernel.__y;
            var rootdiv = canvas.sprite.__LZdiv;
            var arr = [];

            if (quirks.fix_contextmenu) {
                // get root div to back, so contextmenudiv will be at the front
                arr.push(rootdiv, rootdiv.style.display);
                var rootprevZ = rootdiv.style.zIndex; // save current zindex
                rootdiv.style.zIndex = -1000;

                // get click div to back, so contextmenudiv will be at the front
                var rootclickdiv = canvas.sprite.__LZclickcontainerdiv;
                var clickprevZ = rootclickdiv.style.zIndex;
                arr.push(rootclickdiv, rootclickdiv.style.display);
                rootclickdiv.style.zIndex = -9999;
            }
            do {
                var elem = document.elementFromPoint(x, y);
                if (! elem) {
                    // no element under position
                    break;
                } else {
                    var owner = elem.owner;
                    if (! owner) {
                        // no owner attached
                    } else if (owner.__contextmenu) {
                        // found a contextmenu
                        cmenu = owner.__contextmenu;
                        break;
                    } else if (quirks.ie_elementfrompoint && owner.scrolldiv === elem) {
                        // IE returns this first for text div. See LPP-8254
                    } else if (swf8mode && ((owner.__LZdiv === elem && owner.bgcolor != null)
                                    || owner instanceof LzTextSprite)) {
                        // swf8 compatibility: movieclips with bgcolor and textfields
                        // don't pass through context-menu
                        break;
                    }
                    // hide this element to get next layer
                    arr.push(elem, elem.style.display);
                    elem.style.display = 'none';
                }
            } while (elem !== rootdiv && elem.tagName != 'HTML');

            // restore display
            for (var i = arr.length - 1; i >= 0; i -= 2) {
                arr[i - 1].style.display = arr[i];
            }

            if (quirks.fix_contextmenu) {
                rootdiv.style.zIndex = rootprevZ;;
                rootclickdiv.style.zIndex = clickprevZ ;
            }

        } else {
            // this is less reliable compared to elementFromPoint..
            var sprite = (e.srcElement || e.target).owner;
            if (sprite) {
                // walk up the parent chain looking for a __contextmenu
                while (sprite.__parent) {
                    if (sprite.__contextmenu) {
                        // check mouse bounds
                        var mpos = sprite.getMouse();
                        //Debug.write('pos', mpos, sprite.width, sprite.height);
                        if (mpos.x >= 0 && mpos.x < sprite.width &&
                            mpos.y >= 0 && mpos.y < sprite.height) {
                            cmenu = sprite.__contextmenu;
                            break;
                        }
                    }
                    sprite = sprite.__parent;
                }
            }
        }
        return cmenu;
    }
}
<commit_msg>Change 20090827-hqm-s by hqm@badtzmaru.home on 2009-08-27 23:33:23 EDT     in /Users/hqm/openlaszlo/trunk-diamond/WEB-INF/lps/lfc     for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc<commit_after>/**
  * LzMouseKernel.js
  *
  * @copyright Copyright 2007, 2009 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.
  *
  * @topic Kernel
  * @subtopic DHTML
  * @author Max Carlson <max@openlaszlo.org>
  */

// Receives mouse events from the runtime
var LzMouseKernel = {
    // the last view to receive the mouse down event
    __lastMouseDown: null
    ,__x: 0
    ,__y: 0
    ,owner: null
    ,__showncontextmenu: null
    // handles global mousedown, move events
    ,__mouseEvent: function(e) {
        if (!e) {
            e = window.event;
            var targ = e.srcElement;
        } else {
            var targ = e.target;
        }
        var eventname = 'on' + e.type;

        // send option/shift/ctrl key events
        if (window['LzKeyboardKernel'] && LzKeyboardKernel['__updateControlKeys']) {
            LzKeyboardKernel.__updateControlKeys(e);
        }

        var lzinputproto = window['LzInputTextSprite'] && LzInputTextSprite.prototype;
        if (lzinputproto && lzinputproto.__lastshown != null) {
            if (LzSprite.prototype.quirks.fix_ie_clickable) {
                lzinputproto.__hideIfNotFocused(eventname, targ);
            } else if (eventname != 'onmousemove') {
                lzinputproto.__hideIfNotFocused();
            }
        }

        if (eventname == 'onmousemove') {
            LzMouseKernel.__sendMouseMove(e);
            // hide any active inputtexts to allow clickable to work - see LPP-5447...
            if (lzinputproto && lzinputproto.__lastshown != null) {
                if (targ && targ.owner && ! (targ.owner instanceof LzInputTextSprite)) {
                    if (! lzinputproto.__lastshown.__isMouseOver()) {
                        lzinputproto.__lastshown.__hide();
                    }
                }
            }

        } else if (eventname == 'oncontextmenu' || (eventname == 'onmousedown' && e.button == 2)) {
            // If browser supports DOM mouse events level 2 feature,
            // trigger menu on mousedown-right, and suppress the
            // system builtin menu when the oncontextmenu event comes.
            if (LzSprite.prototype.quirks.has_dom2_mouseevents) {
                if (eventname == 'onmousedown') {
                    if (targ) {
                    // update mouse position, required for Safari
                        LzMouseKernel.__sendMouseMove(e);
                        return LzMouseKernel.__showContextMenu(e);
                    }
                } else if (eventname == 'oncontextmenu') {
                    var cmenu = LzMouseKernel.__findContextMenu(e);
                    if (cmenu != null) {
                        // If there is an LZX menu defined,
                        // suppress display of browser's builtin menu
                        return false;
                    } else {
                        // display system builtin menu
                        return true;
                    }
                }
            } else if (eventname == 'oncontextmenu') {
                // If there is no DOM level 2 mouse event support,
                // then use the oncontextmenu event to display context menu
                if (targ) {
                    // update mouse position, required for Safari
                    LzMouseKernel.__sendMouseMove(e);
                    return LzMouseKernel.__showContextMenu(e);
                }
            }
        } else if (e.button != 2) {
            LzMouseKernel.__sendEvent(eventname);
        }
        //Debug.write('LzMouseKernel event', eventname);
    }
    // sends mouse events to the callback
    ,__sendEvent: function(eventname, view) {
        // hide context menus and skip events - see LPP-8189
        if (eventname == 'onclick') {
            if (LzMouseKernel.__showncontextmenu) {
                LzMouseKernel.__showncontextmenu.__hide();
            }
            if (! view) {
                // don't send global onclick events
                return;
            }
        }
        // Make context menus go away when you mouse up or down outside of
        // them, to behave more like swf - see LPP-8218
        if ((eventname == 'onmousedown') || (eventname == 'onmouseup')) {
            if (LzMouseKernel.__showncontextmenu) {
                LzMouseKernel.__showncontextmenu.__hide();
            }
        }
        if (LzMouseKernel.__callback) {
            LzMouseKernel.__scope[LzMouseKernel.__callback](eventname, view);
        }
        //Debug.write('LzMouseKernel event', eventname);
    }
    ,__callback: null
    ,__scope: null
    // handles global mouseup events
    ,__mouseupEvent: function (e) {
        if (LzMouseKernel.__lastMouseDown != null) {
            // call mouseup on the sprite that got the last mouse down
            LzMouseKernel.__lastMouseDown.__globalmouseup(e);
        } else {
            LzMouseKernel.__mouseEvent(e);
        }
    }
    ,setCallback: function (scope, funcname) {
        this.__scope = scope;
        this.__callback = funcname;
    }
    ,__mousecontrol: false
    // Called to register/unregister global mouse events.
    ,setMouseControl: function (ison) {
        if (ison == LzMouseKernel.__mousecontrol) return;
        //Debug.write('mousecontrol', ison);
        LzMouseKernel.__mousecontrol = ison;
        if (ison) {
            lz.embed.attachEventHandler(document, 'mousemove', LzMouseKernel, '__mouseEvent');
            lz.embed.attachEventHandler(document, 'mousedown', LzMouseKernel, '__mouseEvent');
            lz.embed.attachEventHandler(document, 'mouseup', LzMouseKernel, '__mouseupEvent');
            lz.embed.attachEventHandler(document, 'click', LzMouseKernel, '__mouseEvent');
            // Correct possible cross-domain issues - see LPP-8093
            try {
                if (window.top != window) lz.embed.attachEventHandler(window.top.document, 'mouseup', LzMouseKernel, '__mouseupEvent');
            } catch (e) {
            }
        } else {
            lz.embed.removeEventHandler(document, 'mousemove', LzMouseKernel, '__mouseEvent');
            lz.embed.removeEventHandler(document, 'mousedown', LzMouseKernel, '__mouseEvent');
            lz.embed.removeEventHandler(document, 'mouseup', LzMouseKernel, '__mouseupEvent');
            lz.embed.removeEventHandler(document, 'click', LzMouseKernel, '__mouseEvent');
            // Correct possible cross-domain issues - see LPP-8093
            try {
                if (window.top != window) lz.embed.removeEventHandler(window.top.document, 'mouseup', LzMouseKernel, '__mouseupEvent');
            } catch (e) {
            }
        }
        // Prevent context menus in Firefox 1.5 - see LPP-2678
        document.oncontextmenu = ison ? LzMouseKernel.__mouseEvent : null;
    }
    ,__showhand: 'pointer'

    /**
    * Shows or hides the hand cursor for all clickable views.
    * @param Boolean show: true shows the hand cursor for buttons, false hides it
    */
    ,showHandCursor: function (show) {
        var c = show == true ? 'pointer' : 'default';
        this.__showhand = c;
        LzMouseKernel.setCursorGlobal(c);
    }

    /**
    * Sets the cursor to a resource
    * @param String c: cursor ID to use, or '' for default.  See
    * http://www.quirksmode.org/css/cursor.html for valid IDs
    */
    ,setCursorGlobal: function ( n ){
        if (LzSprite.prototype.quirks.no_cursor_colresize) {
            return;
        }
        var n = LzSprite.prototype.__defaultStyles.hyphenate(n);
        LzSprite.prototype.__setCSSClassProperty('.lzclickdiv', 'cursor', n);
        LzSprite.prototype.__setCSSClassProperty('.lzdiv', 'cursor', n);
        LzSprite.prototype.__setCSSClassProperty('.lzcanvasdiv', 'cursor', n);
        LzSprite.prototype.__setCSSClassProperty('.lzcanvasclickdiv', 'cursor', n);
    }

    /**
    * This function restores the default cursor if there is no locked cursor on
    * the screen.
    *
    * @access private
    */
    ,restoreCursor: function ( ){
        if (LzSprite.prototype.quirks.no_cursor_colresize) {
            return;
        }
        if ( LzMouseKernel.__amLocked ) return;
        LzSprite.prototype.__setCSSClassProperty('.lzclickdiv', 'cursor', LzMouseKernel.__showhand);
        LzSprite.prototype.__setCSSClassProperty('.lzdiv', 'cursor', 'default');
        LzSprite.prototype.__setCSSClassProperty('.lzcanvasdiv', 'cursor', 'default');
        LzSprite.prototype.__setCSSClassProperty('.lzcanvasclickdiv', 'cursor', 'default');
    }

    /**
    * Prevents the cursor from being changed until unlock is called.
    *
    */
    ,lock: function (){
        LzMouseKernel.__amLocked = true;
    }

    /**
    * Restores the default cursor.
    *
    */
    ,unlock: function (){
        LzMouseKernel.__amLocked = false;
        LzMouseKernel.restoreCursor();
    }

    ,disableMouseTemporarily: function (){
        this.setGlobalClickable(false);
        this.__resetonmouseover = true;
    }
    ,__resetonmouseover: false
    ,__resetMouse: function (){
        if (this.__resetonmouseover) {
            this.__resetonmouseover = false;
            this.setGlobalClickable(true);
            var cs = this.__cachedSelection;
            if (cs) {
                var sprite = cs.s;
                sprite.setSelection(cs.st, cs.st + cs.sz);
                cs = null;
            }
        }
    }
    ,__cachedSelection: null
    ,__globalClickable: true
    ,setGlobalClickable: function (isclickable){
        var el = document.getElementById('lzcanvasclickdiv');
        this.__globalClickable = isclickable;
        el.style.display = isclickable ? '' : 'none';
    }
    ,__sendMouseMove: function(e, offsetx, offsety) {
        // see http://www.quirksmode.org/js/events_properties.html#position
        if (e.pageX || e.pageY) {
            LzMouseKernel.__x = e.pageX;
            LzMouseKernel.__y = e.pageY;
        } else if (e.clientX || e.clientY) {
            // IE doesn't implement pageX/pageY, instead scrollLeft/scrollTop
            // needs to be added to clientX/clientY
            var body = document.body, docElem = document.documentElement;
            LzMouseKernel.__x = e.clientX + body.scrollLeft + docElem.scrollLeft;
            LzMouseKernel.__y = e.clientY + body.scrollTop + docElem.scrollTop;
        }
        if (offsetx) {
            LzMouseKernel.__x += offsetx;
        }
        if (offsety) {
            LzMouseKernel.__y += offsety;
        }
        if (e.type == 'mousemove') {
            LzMouseKernel.__sendEvent('onmousemove');
        }
    }
    ,__showContextMenu: function(e) {
        // show the default menu if not found...
        var cmenu = LzMouseKernel.__findContextMenu(e);
        if (cmenu) {
            cmenu.kernel.__show();
            return cmenu.kernel.showbuiltins;
        }
    }
    ,__findContextMenu: function(e) {
        // show the default menu if not found...
        var cmenu = LzSprite.__rootSprite.__contextmenu;
        var quirks = LzSprite.prototype.quirks;
        if (document.elementFromPoint) {
            var swf8mode = quirks.swf8_contextmenu;
            var x = LzMouseKernel.__x;
            var y = LzMouseKernel.__y;
            var rootdiv = canvas.sprite.__LZdiv;
            var arr = [];

            if (quirks.fix_contextmenu) {
                // get root div to back, so contextmenudiv will be at the front
                arr.push(rootdiv, rootdiv.style.display);
                var rootprevZ = rootdiv.style.zIndex; // save current zindex
                rootdiv.style.zIndex = -1000;

                // get click div to back, so contextmenudiv will be at the front
                var rootclickdiv = canvas.sprite.__LZclickcontainerdiv;
                var clickprevZ = rootclickdiv.style.zIndex;
                arr.push(rootclickdiv, rootclickdiv.style.display);
                rootclickdiv.style.zIndex = -9999;
            }
            do {
                var elem = document.elementFromPoint(x, y);
                if (! elem) {
                    // no element under position
                    break;
                } else {
                    var owner = elem.owner;
                    if (! owner) {
                        // no owner attached
                    } else if (owner.__contextmenu) {
                        // found a contextmenu
                        cmenu = owner.__contextmenu;
                        break;
                    } else if (quirks.ie_elementfrompoint && owner.scrolldiv === elem) {
                        // IE returns this first for text div. See LPP-8254
                    } else if (swf8mode && ((owner.__LZdiv === elem && owner.bgcolor != null)
                                    || owner instanceof LzTextSprite)) {
                        // swf8 compatibility: movieclips with bgcolor and textfields
                        // don't pass through context-menu
                        break;
                    }
                    // hide this element to get next layer
                    arr.push(elem, elem.style.display);
                    elem.style.display = 'none';
                }
            } while (elem !== rootdiv && elem.tagName != 'HTML');

            // restore display
            for (var i = arr.length - 1; i >= 0; i -= 2) {
                arr[i - 1].style.display = arr[i];
            }

            if (quirks.fix_contextmenu) {
                rootdiv.style.zIndex = rootprevZ;;
                rootclickdiv.style.zIndex = clickprevZ ;
            }

        } else {
            // this is less reliable compared to elementFromPoint..
            var sprite = (e.srcElement || e.target).owner;
            if (sprite) {
                // walk up the parent chain looking for a __contextmenu
                while (sprite.__parent) {
                    if (sprite.__contextmenu) {
                        // check mouse bounds
                        var mpos = sprite.getMouse();
                        //Debug.write('pos', mpos, sprite.width, sprite.height);
                        if (mpos.x >= 0 && mpos.x < sprite.width &&
                            mpos.y >= 0 && mpos.y < sprite.height) {
                            cmenu = sprite.__contextmenu;
                            break;
                        }
                    }
                    sprite = sprite.__parent;
                }
            }
        }
        return cmenu;
    }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule RelayRootContainer
 * @typechecks
 * @flow
 */

'use strict';

const React = require('React');
const RelayDeprecated = require('RelayDeprecated');
import type {RelayQueryConfigSpec} from 'RelayContainer';
const RelayPropTypes = require('RelayPropTypes');
import type {
  ComponentFetchState,
  ReadyState,
  RelayContainer
} from 'RelayTypes';
const RelayRenderer = require('RelayRenderer');

type RootContainerProps = {
  Component: RelayContainer;
  forceFetch?: ?boolean;
  onReadyStateChange?: ?(readyState: ReadyState) => void;
  refetchRoute?: ?boolean; // TODO: Deprecate, #6247867.
  renderFailure?: ?(error: Error, retry: () => void) => ReactElement;
  renderFetched?: ?(
    data: Object,
    fetchState: ComponentFetchState
  ) => ReactElement;
  renderLoading?: ?() => ReactElement;
  route: RelayQueryConfigSpec;
};

const {PropTypes} = React;

/**
 * @public
 *
 * RelayRootContainer sends requests for data required to render the supplied
 * `Component` and `route`. The `Component` must be a container created using
 * `Relay.createContainer`.
 *
 * === Render Callbacks ===
 *
 * Whenever the RelayRootContainer renders, one of three render callback props
 * are invoked depending on whether data is being loaded, can be resolved, or if
 * an error is incurred.
 *
 *  ReactDOM.render(
 *    <RelayRootContainer
 *      Component={FooComponent}
 *      route={fooRoute}
 *      renderLoading={function() {
 *        return <View>Loading...</View>;
 *      }}
 *      renderFetched={function(data) {
 *        // Must spread `data` into <FooComponent>.
 *        return <FooComponent {...data} />;
 *      }}
 *      renderFailure={function(error) {
 *        return <View>Error: {error.message}</View>;
 *      }}
 *    />,
 *    ...
 *  );
 *
 * If a callback is not supplied, it has a default behavior:
 *
 *  - Without `renderFetched`, `Component` will be rendered with fetched data.
 *  - Without `renderFailure`, an error will render to null.
 *  - Without `renderLoading`, the existing view will continue to render. If
 *    this is the initial mount (with no existing view), renders to null.
 *
 * In addition, supplying a `renderLoading` that returns undefined has the same
 * effect as not supplying the callback. (Usually, an undefined return value is
 * an error in React).
 *
 * === Refs ===
 *
 * References to elements rendered by any of these callbacks can be obtained by
 * using the React `ref` prop. For example:
 *
 *   <FooComponent {...data} ref={handleFooRef} />
 *
 *   function handleFooRef(component) {
 *     // Invoked when `<FooComponent>` is mounted or unmounted. When mounted,
 *     // `component` will be the component. When unmounted, `component` will
 *     // be null.
 *   }
 *
 */
function RelayRootContainer({
  Component,
  forceFetch,
  onReadyStateChange,
  refetchRoute,
  renderFailure,
  renderFetched,
  renderLoading,
  route,
}: RootContainerProps): ReactElement {
  if (typeof refetchRoute !== 'undefined') {
    RelayDeprecated.warn({
      was: 'RelayRootContainer.refetchRoute',
      now: 'RelayRootContainer.forceFetch',
    });
    forceFetch = refetchRoute;
  }
  return (
    <RelayRenderer
      Component={Component}
      forceFetch={forceFetch}
      onReadyStateChange={onReadyStateChange}
      queryConfig={route}
      render={({done, error, props, retry, stale}) => {
        if (error) {
          if (renderFailure) {
            return renderFailure(error, retry);
          }
        } else if (props) {
          if (renderFetched) {
            return renderFetched(props, {done, stale});
          } else {
            return <Component {...props} />;
          }
        } else {
          if (renderLoading) {
            return renderLoading();
          }
        }
        return undefined;
      }}
    />
  );
}

RelayRootContainer.propTypes = {
  Component: RelayPropTypes.Container,
  forceFetch: PropTypes.bool,
  onReadyStateChange: PropTypes.func,
  renderFailure: PropTypes.func,
  renderFetched: PropTypes.func,
  renderLoading: PropTypes.func,
  route: RelayPropTypes.QueryConfig.isRequired,
};

RelayRootContainer.childContextTypes = {
  route: RelayPropTypes.QueryConfig.isRequired,
};

module.exports = RelayRootContainer;
<commit_msg>remove deprecated refetchRoute prop from RelayRootContainer<commit_after>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule RelayRootContainer
 * @typechecks
 * @flow
 */

'use strict';

const React = require('React');
import type {RelayQueryConfigSpec} from 'RelayContainer';
const RelayPropTypes = require('RelayPropTypes');
import type {
  ComponentFetchState,
  ReadyState,
  RelayContainer,
} from 'RelayTypes';
const RelayRenderer = require('RelayRenderer');

type RootContainerProps = {
  Component: RelayContainer;
  forceFetch?: ?boolean;
  onReadyStateChange?: ?(readyState: ReadyState) => void;
  renderFailure?: ?(error: Error, retry: () => void) => ReactElement;
  renderFetched?: ?(
    data: Object,
    fetchState: ComponentFetchState
  ) => ReactElement;
  renderLoading?: ?() => ReactElement;
  route: RelayQueryConfigSpec;
};

const {PropTypes} = React;

/**
 * @public
 *
 * RelayRootContainer sends requests for data required to render the supplied
 * `Component` and `route`. The `Component` must be a container created using
 * `Relay.createContainer`.
 *
 * === Render Callbacks ===
 *
 * Whenever the RelayRootContainer renders, one of three render callback props
 * are invoked depending on whether data is being loaded, can be resolved, or if
 * an error is incurred.
 *
 *  ReactDOM.render(
 *    <RelayRootContainer
 *      Component={FooComponent}
 *      route={fooRoute}
 *      renderLoading={function() {
 *        return <View>Loading...</View>;
 *      }}
 *      renderFetched={function(data) {
 *        // Must spread `data` into <FooComponent>.
 *        return <FooComponent {...data} />;
 *      }}
 *      renderFailure={function(error) {
 *        return <View>Error: {error.message}</View>;
 *      }}
 *    />,
 *    ...
 *  );
 *
 * If a callback is not supplied, it has a default behavior:
 *
 *  - Without `renderFetched`, `Component` will be rendered with fetched data.
 *  - Without `renderFailure`, an error will render to null.
 *  - Without `renderLoading`, the existing view will continue to render. If
 *    this is the initial mount (with no existing view), renders to null.
 *
 * In addition, supplying a `renderLoading` that returns undefined has the same
 * effect as not supplying the callback. (Usually, an undefined return value is
 * an error in React).
 *
 * === Refs ===
 *
 * References to elements rendered by any of these callbacks can be obtained by
 * using the React `ref` prop. For example:
 *
 *   <FooComponent {...data} ref={handleFooRef} />
 *
 *   function handleFooRef(component) {
 *     // Invoked when `<FooComponent>` is mounted or unmounted. When mounted,
 *     // `component` will be the component. When unmounted, `component` will
 *     // be null.
 *   }
 *
 */
function RelayRootContainer({
  Component,
  forceFetch,
  onReadyStateChange,
  renderFailure,
  renderFetched,
  renderLoading,
  route,
}: RootContainerProps): ReactElement {
  return (
    <RelayRenderer
      Component={Component}
      forceFetch={forceFetch}
      onReadyStateChange={onReadyStateChange}
      queryConfig={route}
      render={({done, error, props, retry, stale}) => {
        if (error) {
          if (renderFailure) {
            return renderFailure(error, retry);
          }
        } else if (props) {
          if (renderFetched) {
            return renderFetched(props, {done, stale});
          } else {
            return <Component {...props} />;
          }
        } else {
          if (renderLoading) {
            return renderLoading();
          }
        }
        return undefined;
      }}
    />
  );
}

RelayRootContainer.propTypes = {
  Component: RelayPropTypes.Container,
  forceFetch: PropTypes.bool,
  onReadyStateChange: PropTypes.func,
  renderFailure: PropTypes.func,
  renderFetched: PropTypes.func,
  renderLoading: PropTypes.func,
  route: RelayPropTypes.QueryConfig.isRequired,
};

RelayRootContainer.childContextTypes = {
  route: RelayPropTypes.QueryConfig.isRequired,
};

module.exports = RelayRootContainer;
<|endoftext|>


<commit_before>describe('SimplePagination', function() {

    it('adds pagination elements to an empty container', function() {
        expect(pager).toBePaged();
    })

    describe('#destroy', function() {
        it('visually destroys the pager', function() {
            pager.pagination('destroy');

            expect(pager).not.toBePaged();
        })
    })

    describe('#selectPage', function() {
        it('changes to the specified page', function() {
            var page = pageCount - 1;
            pager.pagination('selectPage', page);

            expect(pager).toBeOnPage(page);
        })
    })

    describe('#getCurrentPage', function() {
        it('returns the current page number', function() {
            expect(pager.pagination('getCurrentPage')).toBe(1);

            var page = pageCount - 1;
            pager.pagination('selectPage', page);

            expect(pager.pagination('getCurrentPage')).toBe(page);
        })
    })

});<commit_msg>#getPagesCount test<commit_after>describe('SimplePagination', function() {

    it('adds pagination elements to an empty container', function() {
        expect(pager).toBePaged();
    })

    describe('#destroy', function() {
        it('visually destroys the pager', function() {
            pager.pagination('destroy');

            expect(pager).not.toBePaged();
        })
    })

    describe('#getPagesCount', function() {
        it('return the number of pages', function() {
            expect(pager.pagination('getPagesCount')).toBe(pageCount);
        })
    })

    describe('#selectPage', function() {
        it('changes to the specified page', function() {
            var page = pageCount - 1;
            pager.pagination('selectPage', page);

            expect(pager).toBeOnPage(page);
        })
    })

    describe('#getCurrentPage', function() {
        it('returns the current page number', function() {
            expect(pager.pagination('getCurrentPage')).toBe(1);

            var page = pageCount - 1;
            pager.pagination('selectPage', page);

            expect(pager.pagination('getCurrentPage')).toBe(page);
        })
    })

});<|endoftext|>


<commit_before>'use strict';

module.exports = {
  env: {
    es6: true,
    node: true,
  },
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
    },
  },
  rules: {
    // Possible errors
    'for-direction': 'error',
    'no-await-in-loop': 'error',
    'no-compare-neg-zero': 'error',
    'no-cond-assign': ['error', 'always'],
    'no-console': 'warn',
    'no-constant-condition': 'error',
    'no-control-regex': 'error',
    'no-debugger': 'warn',
    'no-dupe-args': 'error',
    'no-dupe-keys': 'error',
    'no-duplicate-case': 'error',
    'no-empty-character-class': 'error',
    'no-empty': ['error', {allowEmptyCatch: true}],
    'no-ex-assign': 'error',
    'no-extra-boolean-cast': 'error',
    'no-extra-parens': [
      'error',
      'all',
      {
        returnAssign: false,
        nestedBinaryExpressions: false,
        ignoreJSX: 'multi-line',
      },
    ],
    'no-extra-semi': 'error',
    'no-func-assign': 'error',
    'no-inner-declarations': 'error',
    'no-invalid-regexp': 'error',
    'no-irregular-whitespace': 'error',
    'no-obj-calls': 'error',
    'no-prototype-builtins': 'error',
    'no-regex-spaces': 'error',
    'no-sparse-arrays': 'error',
    'no-template-curly-in-string': 'error',
    'no-unexpected-multiline': 'error',
    'no-unreachable': 'error',
    'no-unsafe-finally': 'error',
    'no-unsafe-negation': 'error',
    'use-isnan': 'error',
    'valid-jsdoc': 'off',
    'valid-typeof': ['error', {requireStringLiterals: true}],

    // Best practices
    'accessor-pairs': 'error',
    'array-callback-return': 'error',
    'block-scoped-var': 'error',
    'class-methods-use-this': 'off',
    'complexity': ['warn', 11],
    'consistent-return': 'error',
    'curly': 'error',
    'default-case': 'error',
    'dot-location': ['error', 'property'],
    'dot-notation': 'error',
    'eqeqeq': 'error',
    'guard-for-in': 'error',
    'no-alert': 'warn',
    'no-caller': 'error',
    'no-case-declarations': 'error',
    'no-div-regex': 'off',
    'no-else-return': 'error',
    'no-empty-function': 'error',
    'no-empty-pattern': 'error',
    'no-eq-null': 'error',
    'no-eval': 'error',
    'no-extend-native': 'error',
    'no-extra-bind': 'error',
    'no-extra-label': 'error',
    'no-fallthrough': 'error',
    'no-floating-decimal': 'error',
    'no-global-assign': 'error',
    'no-implicit-coercion': ['error', {boolean: false}],
    'no-implicit-globals': 'error',
    'no-implied-eval': 'error',
    'no-invalid-this': 'error',
    'no-iterator': 'error',
    'no-labels': 'error',
    'no-lone-blocks': 'error',
    'no-loop-func': 'error',
    'no-magic-numbers': 'off',
    'no-multi-spaces': 'error',
    'no-multi-str': 'error',
    'no-new-func': 'error',
    'no-new-wrappers': 'error',
    'no-new': 'error',
    'no-octal-escape': 'error',
    'no-octal': 'error',
    'no-param-reassign': ['error', {props: true}],
    'no-proto': 'error',
    'no-redeclare': 'error',
    'no-restricted-properties': [
      'error',
      {
        object: 'Object',
        property: 'assign',
        message: 'Use object spread operator `{...obj}` instead.',
      },
      {
        object: 'Math',
        property: 'pow',
        message: 'Use exponentiation operator `**` instead.',
      },
    ],
    'no-return-assign': 'error',
    'no-return-await': 'error',
    'no-script-url': 'off',
    'no-self-assign': ['error', {props: true}],
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-throw-literal': 'error',
    'no-unmodified-loop-condition': 'error',
    'no-unused-expressions': 'error',
    'no-unused-labels': 'error',
    'no-useless-call': 'error',
    'no-useless-concat': 'error',
    'no-useless-escape': 'error',
    'no-useless-return': 'error',
    'no-void': 'error',
    'no-warning-comments': 'warn',
    'no-with': 'error',
    'prefer-promise-reject-errors': 'error',
    'radix': ['error', 'as-needed'],
    'require-await': 'error',
    'vars-on-top': 'error',
    'wrap-iife': ['error', 'inside', {functionPrototypeMethods: true}],
    'yoda': 'error',

    // Strict mode
    'strict': 'error',

    // Variables
    'init-declarations': 'error',
    'no-catch-shadow': 'off',
    'no-delete-var': 'error',
    'no-label-var': 'error',
    // Use `Number` property functions instead
    'no-restricted-globals': ['error', 'isNaN', 'parseInt', 'parseFloat'],
    'no-shadow-restricted-names': 'error',
    'no-shadow': 'error',
    'no-undef-init': 'error',
    'no-undef': 'error',
    'no-undefined': 'off',
    'no-unused-vars': 'error',
    'no-use-before-define': ['error', {functions: false, variables: false}],

    // Node.js and CommonJS
    'callback-return': 'off',
    'global-require': 'off',
    'handle-callback-err': 'error',
    'no-buffer-constructor': 'error',
    'no-mixed-requires': 'error',
    'no-new-require': 'error',
    'no-path-concat': 'error',
    'no-process-env': 'off',
    'no-process-exit': 'off',
    'no-restricted-modules': 'off',
    'no-sync': 'off',

    // Stylistic issues
    'array-bracket-newline': ['error', {multiline: true}],
    'array-bracket-spacing': 'error',
    'array-element-newline': ['error', {multiline: true}],
    'block-spacing': 'error',
    'brace-style': ['error', '1tbs', {allowSingleLine: true}],
    'camelcase': ['error', {properties: 'never'}],
    // TODO: Enable when false positive issue has been fixed
    // 'capitalized-comments': ['error', 'always', {ignoreInlineComments: true}],
    'comma-dangle': [
      'error',
      {
        arrays: 'always-multiline',
        objects: 'always-multiline',
        imports: 'always-multiline',
        exports: 'always-multiline',
        functions: 'always-multiline',
      },
    ],
    'comma-spacing': 'error',
    'comma-style': ['error', 'last'],
    'computed-property-spacing': 'error',
    'consistent-this': 'off',
    'eol-last': 'error',
    'func-call-spacing': 'error',
    'func-name-matching': 'error',
    'func-names': ['error', 'never'],
    'func-style': ['error', 'declaration', {allowArrowFunctions: true}],
    'id-blacklist': 'off',
    'id-length': 'off',
    'id-match': 'off',
    'indent': [
      'error',
      2,
      {
        SwitchCase: 1,
        MemberExpression: 1,
        FunctionDeclaration: {
          parameters: 1,
        },
        FunctionExpression: {
          parameters: 1,
        },
        CallExpression: {
          arguments: 1,
        },
      },
    ],
    'jsx-quotes': 'off',
    'key-spacing': 'error',
    'line-comment-position': 'off',
    'keyword-spacing': 'error',
    'linebreak-style': 'error',
    'lines-around-comment': 'off',
    'max-depth': 'warn',
    'max-len': 'off',
    'max-lines': 'off',
    'max-nested-callbacks': ['warn', 4],
    'max-params': ['warn', 5],
    'max-statements-per-line': 'warn',
    'max-statements': 'off',
    'multiline-ternary': 'off',
    'new-cap': 'error',
    'new-parens': 'error',
    'newline-per-chained-call': ['error', {ignoreChainWithDepth: 3}],
    'no-array-constructor': 'error',
    'no-bitwise': 'off',
    'no-continue': 'error',
    'no-inline-comments': 'off',
    'no-lonely-if': 'error',
    'no-mixed-operators': 'error',
    'no-mixed-spaces-and-tabs': 'error',
    'no-multi-assign': 'error',
    'no-multiple-empty-lines': ['error', {max: 1, maxBOF: 0}],
    'no-negated-condition': 'error',
    // TODO: Consider about disabling this rule again
    // Use separated function or switch-case
    // http://stackoverflow.com/questions/32289340/alternative-to-nested-ternary-operator-in-js
    'no-nested-ternary': 'error',
    'no-new-object': 'error',
    'no-plusplus': 'off',
    // Use `for-of` with `Object.keys()` instead of `for-in`
    // https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
    'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
    'no-tabs': 'error',
    'no-ternary': 'off',
    'no-trailing-spaces': ['error', {skipBlankLines: true}],
    'no-underscore-dangle': ['error', {allowAfterThis: true, allowAfterSuper: true}],
    'no-unneeded-ternary': ['error', {defaultAssignment: false}],
    'no-whitespace-before-property': 'error',
    'nonblock-statement-body-position': 'off',
    // TODO: Enable when issue has been fixed: https://github.com/eslint/eslint/issues/6488
    // 'object-curly-newline': ['error', {multiline: true, minProperties: 4}],
    'object-curly-spacing': 'error',
    'object-property-newline': ['error', {allowMultiplePropertiesPerLine: true}],
    'one-var-declaration-per-line': 'error',
    'one-var': ['error', 'never'],
    'operator-assignment': ['error', 'always'],
    'operator-linebreak': 'error',
    'padded-blocks': ['error', 'never'],
    'quote-props': ['error', 'as-needed'],
    'quotes': ['error', 'single'],
    'require-jsdoc': 'off',
    'semi': 'error',
    'semi-spacing': 'error',
    'semi-style': 'error',
    'sort-keys': 'off',
    'sort-vars': 'off',
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', {anonymous: 'always', named: 'never', asyncArrow: 'always'}],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': ['error', 'always', {block: {balanced: true}}],
    'switch-colon-spacing': 'error',
    'template-tag-spacing': 'error',
    'unicode-bom': 'error',
    'wrap-regex': 'off',

    // ECMAScript 6 (2015)
    'arrow-body-style': ['error', 'as-needed'],
    'arrow-parens': 'error',
    'arrow-spacing': 'error',
    'constructor-super': 'error',
    'generator-star-spacing': ['error', 'after'],
    'no-class-assign': 'error',
    'no-confusing-arrow': 'off',
    'no-const-assign': 'error',
    'no-dupe-class-members': 'error',
    'no-duplicate-imports': ['error', {includeExports: true}],
    'no-new-symbol': 'error',
    'no-restricted-imports': 'off',
    'no-this-before-super': 'error',
    'no-useless-computed-key': 'error',
    'no-useless-constructor': 'error',
    'no-useless-rename': 'error',
    'no-var': 'error',
    'object-shorthand': ['error', 'always', {avoidExplicitReturnArrows: true}],
    'prefer-arrow-callback': 'error',
    'prefer-const': ['error', {destructuring: 'all'}],
    'prefer-destructuring': ['error', {}, {enforceForRenamedProperties: true}],
    'prefer-numeric-literals': 'error',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'prefer-template': 'error',
    'require-yield': 'error',
    'rest-spread-spacing': 'error',
    'sort-imports': 'off',
    'symbol-description': 'off',
    'template-curly-spacing': 'error',
    'yield-star-spacing': 'error',
  },
};
<commit_msg>Finally enable `object-curly-newline` rule again<commit_after>'use strict';

module.exports = {
  env: {
    es6: true,
    node: true,
  },
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
    },
  },
  rules: {
    // Possible errors
    'for-direction': 'error',
    'no-await-in-loop': 'error',
    'no-compare-neg-zero': 'error',
    'no-cond-assign': ['error', 'always'],
    'no-console': 'warn',
    'no-constant-condition': 'error',
    'no-control-regex': 'error',
    'no-debugger': 'warn',
    'no-dupe-args': 'error',
    'no-dupe-keys': 'error',
    'no-duplicate-case': 'error',
    'no-empty-character-class': 'error',
    'no-empty': ['error', {allowEmptyCatch: true}],
    'no-ex-assign': 'error',
    'no-extra-boolean-cast': 'error',
    'no-extra-parens': [
      'error',
      'all',
      {
        returnAssign: false,
        nestedBinaryExpressions: false,
        ignoreJSX: 'multi-line',
      },
    ],
    'no-extra-semi': 'error',
    'no-func-assign': 'error',
    'no-inner-declarations': 'error',
    'no-invalid-regexp': 'error',
    'no-irregular-whitespace': 'error',
    'no-obj-calls': 'error',
    'no-prototype-builtins': 'error',
    'no-regex-spaces': 'error',
    'no-sparse-arrays': 'error',
    'no-template-curly-in-string': 'error',
    'no-unexpected-multiline': 'error',
    'no-unreachable': 'error',
    'no-unsafe-finally': 'error',
    'no-unsafe-negation': 'error',
    'use-isnan': 'error',
    'valid-jsdoc': 'off',
    'valid-typeof': ['error', {requireStringLiterals: true}],

    // Best practices
    'accessor-pairs': 'error',
    'array-callback-return': 'error',
    'block-scoped-var': 'error',
    'class-methods-use-this': 'off',
    'complexity': ['warn', 11],
    'consistent-return': 'error',
    'curly': 'error',
    'default-case': 'error',
    'dot-location': ['error', 'property'],
    'dot-notation': 'error',
    'eqeqeq': 'error',
    'guard-for-in': 'error',
    'no-alert': 'warn',
    'no-caller': 'error',
    'no-case-declarations': 'error',
    'no-div-regex': 'off',
    'no-else-return': 'error',
    'no-empty-function': 'error',
    'no-empty-pattern': 'error',
    'no-eq-null': 'error',
    'no-eval': 'error',
    'no-extend-native': 'error',
    'no-extra-bind': 'error',
    'no-extra-label': 'error',
    'no-fallthrough': 'error',
    'no-floating-decimal': 'error',
    'no-global-assign': 'error',
    'no-implicit-coercion': ['error', {boolean: false}],
    'no-implicit-globals': 'error',
    'no-implied-eval': 'error',
    'no-invalid-this': 'error',
    'no-iterator': 'error',
    'no-labels': 'error',
    'no-lone-blocks': 'error',
    'no-loop-func': 'error',
    'no-magic-numbers': 'off',
    'no-multi-spaces': 'error',
    'no-multi-str': 'error',
    'no-new-func': 'error',
    'no-new-wrappers': 'error',
    'no-new': 'error',
    'no-octal-escape': 'error',
    'no-octal': 'error',
    'no-param-reassign': ['error', {props: true}],
    'no-proto': 'error',
    'no-redeclare': 'error',
    'no-restricted-properties': [
      'error',
      {
        object: 'Object',
        property: 'assign',
        message: 'Use object spread operator `{...obj}` instead.',
      },
      {
        object: 'Math',
        property: 'pow',
        message: 'Use exponentiation operator `**` instead.',
      },
    ],
    'no-return-assign': 'error',
    'no-return-await': 'error',
    'no-script-url': 'off',
    'no-self-assign': ['error', {props: true}],
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-throw-literal': 'error',
    'no-unmodified-loop-condition': 'error',
    'no-unused-expressions': 'error',
    'no-unused-labels': 'error',
    'no-useless-call': 'error',
    'no-useless-concat': 'error',
    'no-useless-escape': 'error',
    'no-useless-return': 'error',
    'no-void': 'error',
    'no-warning-comments': 'warn',
    'no-with': 'error',
    'prefer-promise-reject-errors': 'error',
    'radix': ['error', 'as-needed'],
    'require-await': 'error',
    'vars-on-top': 'error',
    'wrap-iife': ['error', 'inside', {functionPrototypeMethods: true}],
    'yoda': 'error',

    // Strict mode
    'strict': 'error',

    // Variables
    'init-declarations': 'error',
    'no-catch-shadow': 'off',
    'no-delete-var': 'error',
    'no-label-var': 'error',
    // Use `Number` property functions instead
    'no-restricted-globals': ['error', 'isNaN', 'parseInt', 'parseFloat'],
    'no-shadow-restricted-names': 'error',
    'no-shadow': 'error',
    'no-undef-init': 'error',
    'no-undef': 'error',
    'no-undefined': 'off',
    'no-unused-vars': 'error',
    'no-use-before-define': ['error', {functions: false, variables: false}],

    // Node.js and CommonJS
    'callback-return': 'off',
    'global-require': 'off',
    'handle-callback-err': 'error',
    'no-buffer-constructor': 'error',
    'no-mixed-requires': 'error',
    'no-new-require': 'error',
    'no-path-concat': 'error',
    'no-process-env': 'off',
    'no-process-exit': 'off',
    'no-restricted-modules': 'off',
    'no-sync': 'off',

    // Stylistic issues
    'array-bracket-newline': ['error', {multiline: true}],
    'array-bracket-spacing': 'error',
    'array-element-newline': ['error', {multiline: true}],
    'block-spacing': 'error',
    'brace-style': ['error', '1tbs', {allowSingleLine: true}],
    'camelcase': ['error', {properties: 'never'}],
    // TODO: Enable when false positive issue has been fixed
    // 'capitalized-comments': ['error', 'always', {ignoreInlineComments: true}],
    'comma-dangle': [
      'error',
      {
        arrays: 'always-multiline',
        objects: 'always-multiline',
        imports: 'always-multiline',
        exports: 'always-multiline',
        functions: 'always-multiline',
      },
    ],
    'comma-spacing': 'error',
    'comma-style': ['error', 'last'],
    'computed-property-spacing': 'error',
    'consistent-this': 'off',
    'eol-last': 'error',
    'func-call-spacing': 'error',
    'func-name-matching': 'error',
    'func-names': ['error', 'never'],
    'func-style': ['error', 'declaration', {allowArrowFunctions: true}],
    'id-blacklist': 'off',
    'id-length': 'off',
    'id-match': 'off',
    'indent': [
      'error',
      2,
      {
        SwitchCase: 1,
        MemberExpression: 1,
        FunctionDeclaration: {
          parameters: 1,
        },
        FunctionExpression: {
          parameters: 1,
        },
        CallExpression: {
          arguments: 1,
        },
      },
    ],
    'jsx-quotes': 'off',
    'key-spacing': 'error',
    'line-comment-position': 'off',
    'keyword-spacing': 'error',
    'linebreak-style': 'error',
    'lines-around-comment': 'off',
    'max-depth': 'warn',
    'max-len': 'off',
    'max-lines': 'off',
    'max-nested-callbacks': ['warn', 4],
    'max-params': ['warn', 5],
    'max-statements-per-line': 'warn',
    'max-statements': 'off',
    'multiline-ternary': 'off',
    'new-cap': 'error',
    'new-parens': 'error',
    'newline-per-chained-call': ['error', {ignoreChainWithDepth: 3}],
    'no-array-constructor': 'error',
    'no-bitwise': 'off',
    'no-continue': 'error',
    'no-inline-comments': 'off',
    'no-lonely-if': 'error',
    'no-mixed-operators': 'error',
    'no-mixed-spaces-and-tabs': 'error',
    'no-multi-assign': 'error',
    'no-multiple-empty-lines': ['error', {max: 1, maxBOF: 0}],
    'no-negated-condition': 'error',
    // TODO: Consider about disabling this rule again
    // Use separated function or switch-case
    // http://stackoverflow.com/questions/32289340/alternative-to-nested-ternary-operator-in-js
    'no-nested-ternary': 'error',
    'no-new-object': 'error',
    'no-plusplus': 'off',
    // Use `for-of` with `Object.keys()` instead of `for-in`
    // https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
    'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
    'no-tabs': 'error',
    'no-ternary': 'off',
    'no-trailing-spaces': ['error', {skipBlankLines: true}],
    'no-underscore-dangle': ['error', {allowAfterThis: true, allowAfterSuper: true}],
    'no-unneeded-ternary': ['error', {defaultAssignment: false}],
    'no-whitespace-before-property': 'error',
    'nonblock-statement-body-position': 'off',
    'object-curly-newline': ['error', {consistent: true}],
    'object-curly-spacing': 'error',
    'object-property-newline': ['error', {allowMultiplePropertiesPerLine: true}],
    'one-var-declaration-per-line': 'error',
    'one-var': ['error', 'never'],
    'operator-assignment': ['error', 'always'],
    'operator-linebreak': 'error',
    'padded-blocks': ['error', 'never'],
    'quote-props': ['error', 'as-needed'],
    'quotes': ['error', 'single'],
    'require-jsdoc': 'off',
    'semi': 'error',
    'semi-spacing': 'error',
    'semi-style': 'error',
    'sort-keys': 'off',
    'sort-vars': 'off',
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', {anonymous: 'always', named: 'never', asyncArrow: 'always'}],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': ['error', 'always', {block: {balanced: true}}],
    'switch-colon-spacing': 'error',
    'template-tag-spacing': 'error',
    'unicode-bom': 'error',
    'wrap-regex': 'off',

    // ECMAScript 6 (2015)
    'arrow-body-style': ['error', 'as-needed'],
    'arrow-parens': 'error',
    'arrow-spacing': 'error',
    'constructor-super': 'error',
    'generator-star-spacing': ['error', 'after'],
    'no-class-assign': 'error',
    'no-confusing-arrow': 'off',
    'no-const-assign': 'error',
    'no-dupe-class-members': 'error',
    'no-duplicate-imports': ['error', {includeExports: true}],
    'no-new-symbol': 'error',
    'no-restricted-imports': 'off',
    'no-this-before-super': 'error',
    'no-useless-computed-key': 'error',
    'no-useless-constructor': 'error',
    'no-useless-rename': 'error',
    'no-var': 'error',
    'object-shorthand': ['error', 'always', {avoidExplicitReturnArrows: true}],
    'prefer-arrow-callback': 'error',
    'prefer-const': ['error', {destructuring: 'all'}],
    'prefer-destructuring': ['error', {}, {enforceForRenamedProperties: true}],
    'prefer-numeric-literals': 'error',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'prefer-template': 'error',
    'require-yield': 'error',
    'rest-spread-spacing': 'error',
    'sort-imports': 'off',
    'symbol-description': 'off',
    'template-curly-spacing': 'error',
    'yield-star-spacing': 'error',
  },
};
<|endoftext|>


<commit_before>var hack_night_data = [
  {
    "title": "Chicago Data Portal",
    "url": "http://data.cityofchicago.org",
    "description": "Official data portal for the City of Chicago. Contains hundreds of datasets including  crime, health, energy, budgets, salaries and more!",
    "links": [
      {"name": "Soda 2.0 API", "url": "http://dev.socrata.com/consumers/getting-started"},
      {"name": "Energy Usage 2010 API", "url": "https://data.cityofchicago.org/developers/docs/energy-usage-2010"}
    ]
  },
  {
    "title": "CTA API",
    "url": "http://www.transitchicago.com/developers/default.aspx",
    "description": "API for the Chicago Transit Authority (CTA) buses and trains.",
    "links": [
      {"name": "CTA Train Tracker API", "url": "http://www.transitchicago.com/developers/traintracker.aspx"},
      {"name": "Bus Tracker API", "url": "http://www.transitchicago.com/developers/bustracker.aspx"}
    ]
  },
  {
    "title": "Divvy API",
    "url": "http://divvybikes.com/stations/json",
    "description": "List of stations and available bikes for Chicago's bike share system."
  },
  {
    "title": "Open 311",
    "url": "http://dev.cityofchicago.org/docs/api",
    "description": "Open311 is a form of technology that provides open channels of communication for issues that concern public space and public services. Primarily, Open311 refers to a standardized protocol for location-based collaborative issue-tracking.",
    "links": [
      {"name": "The Launch of Open311 in Chicago", "url": "http://open311.org/2012/09/the-launch-of-open311-in-chicago/"},
      {"name": "Service Tracker", "url": "http://servicetracker.cityofchicago.org/"}
    ]
  },
  {
    "title": "ClearPath REST API",
    "url": "http://api1.chicagopolice.org/clearpath/documentation",
    "description": "Chicago Police Department data on community concerns, crime, mugshots, most wanted and events.",
    "links": [
      {"name": "Smart Chicago blog post", "url": "http://www.smartchicagocollaborative.org/using-the-new-clearpath-api-to-help-communities-interact-with-the-chicago-police-department/"}
    ]
  },
  {
    "title": "OpenStreetMap",
    "url": "http://openstreetmap.org",
    "description": "A wiki map, built on data submitted by volunteers and public data sources. The data is available and free to use through the OpenStreetMap API and bulk downloads.",
    "links": [
      {"name": "Homepage", "url": "http://openstreetmap.org"},
      {"name": "Chicagoland Download", "url": "http://metro.teczno.com/#chicago"},
      {"name": "OpenStreetMap API", "url": "http://wiki.openstreetmap.org/wiki/API_v0.6"}
    ]
  }
  {
    "title": "Cook County Data Portal",
    "url": "http://data.cookcountyil.gov/",
    "description": "Open data portal for Cook County government.",
    "links": [
      {"name": "Tutorials", "url": "http://blog.cookcountygov.com/opencc/tutorials-how-to-use-open-data/"}
    ]
  }
]
<commit_msg>Comma for JSON<commit_after>var hack_night_data = [
  {
    "title": "Chicago Data Portal",
    "url": "http://data.cityofchicago.org",
    "description": "Official data portal for the City of Chicago. Contains hundreds of datasets including  crime, health, energy, budgets, salaries and more!",
    "links": [
      {"name": "Soda 2.0 API", "url": "http://dev.socrata.com/consumers/getting-started"},
      {"name": "Energy Usage 2010 API", "url": "https://data.cityofchicago.org/developers/docs/energy-usage-2010"}
    ]
  },
  {
    "title": "CTA API",
    "url": "http://www.transitchicago.com/developers/default.aspx",
    "description": "API for the Chicago Transit Authority (CTA) buses and trains.",
    "links": [
      {"name": "CTA Train Tracker API", "url": "http://www.transitchicago.com/developers/traintracker.aspx"},
      {"name": "Bus Tracker API", "url": "http://www.transitchicago.com/developers/bustracker.aspx"}
    ]
  },
  {
    "title": "Divvy API",
    "url": "http://divvybikes.com/stations/json",
    "description": "List of stations and available bikes for Chicago's bike share system."
  },
  {
    "title": "Open 311",
    "url": "http://dev.cityofchicago.org/docs/api",
    "description": "Open311 is a form of technology that provides open channels of communication for issues that concern public space and public services. Primarily, Open311 refers to a standardized protocol for location-based collaborative issue-tracking.",
    "links": [
      {"name": "The Launch of Open311 in Chicago", "url": "http://open311.org/2012/09/the-launch-of-open311-in-chicago/"},
      {"name": "Service Tracker", "url": "http://servicetracker.cityofchicago.org/"}
    ]
  },
  {
    "title": "ClearPath REST API",
    "url": "http://api1.chicagopolice.org/clearpath/documentation",
    "description": "Chicago Police Department data on community concerns, crime, mugshots, most wanted and events.",
    "links": [
      {"name": "Smart Chicago blog post", "url": "http://www.smartchicagocollaborative.org/using-the-new-clearpath-api-to-help-communities-interact-with-the-chicago-police-department/"}
    ]
  },
  {
    "title": "OpenStreetMap",
    "url": "http://openstreetmap.org",
    "description": "A wiki map, built on data submitted by volunteers and public data sources. The data is available and free to use through the OpenStreetMap API and bulk downloads.",
    "links": [
      {"name": "Homepage", "url": "http://openstreetmap.org"},
      {"name": "Chicagoland Download", "url": "http://metro.teczno.com/#chicago"},
      {"name": "OpenStreetMap API", "url": "http://wiki.openstreetmap.org/wiki/API_v0.6"}
    ]
  },
  {
    "title": "Cook County Data Portal",
    "url": "http://data.cookcountyil.gov/",
    "description": "Open data portal for Cook County government.",
    "links": [
      {"name": "Tutorials", "url": "http://blog.cookcountygov.com/opencc/tutorials-how-to-use-open-data/"}
    ]
  }
]
<|endoftext|>


<commit_before>/*
	SLEEPIA PROJECT
	Author: Mario Esposito

	Libraries:
		Sandeep Mistry's sensortag
		Kue
		Redis
*/

var SensorTag = require('sensortag'); // sensortag library
var kue = require('kue');			  // queue management library
var queue = kue.createQueue({
	prefix: 'q',
	redis: {
		port: 6379,
		host: 'localhost',
		auth: '',			// use a password even if not exposed to the Internet!!
		db: 0, 				// database ID
		options: {
							// see https://github.com/mranney/node_redis#rediscreateclient
		}
	}
});

// listen for tags:
SensorTag.discover(function(tag) {

	// when you disconnect from a tag, exit the program:
	//
	tag.on('disconnect', function() {
		console.log('# Device Disconnected!');
		kue.shutdown(2000, function(err) {
  		console.log('Kue shutdown: ', err || '');
	});

	//
	// Connect and setup
	//
	function connectAndSetUpMe() { // attempt to connect to the tag
		console.log('# Connecting...');
		tag.connectAndSetUp(enableSensors); // when you connect and device is setup, call enableAccelMe
	}

	//
	// This function enables the accelerometer stream
	//
	function enableSensors() { // attempt to enable the accelerometer
		console.log('# Enabled Sensors (Acc, IR Temp)');
		// when you enable the accelerometer, start accelerometer notifications:
		tag.enableAccelerometer(notifyMe); // start the accelerometer listner
		tag.enableIrTemperature(notifyMe); // start the IR temp sensor listner

		console.log('timestamp, X, Y, Z, ambientTemp');
	}

	//
	// Activate which service we want to be notified by
	//
	function notifyMe() {
		tag.notifyAccelerometer(notificationManager); 	// setup call back for accelerometer
		tag.notifyIrTemperature(notificationManager); 	// setup call back for IR temp
		tag.notifySimpleKey(listenForButton); 			// setup call back for button/switches
	}

	//
	// When you get an accelermeter change, print it out:
	//
	function notificationManager() {
		var at = 0;
		var ot = 0;

		tag.on('irTemperatureChange', function(objectTemp, ambientTemp) {
			ot = objectTemp.toFixed(1);
			at = ambientTemp.toFixed(1);
		});

		tag.on('accelerometerChange', function(x, y, z) {
			// timestamp, 3 axes, temperature
			newSensorDataJob(getDateTime(), x.toFixed(1), y.toFixed(1), z.toFixed(1), at);
			// console.log('%s,%d,%d,%d,%d,%d', getDateTime(), x.toFixed(1), y.toFixed(1), z.toFixed(1), ot, at);
		});
	}

	// when you get a button change, print it out:
	//
	function listenForButton() {

		tag.on('simpleKeyChange', function(left, right) {

			if (left) {
				console.log('marker1: ' + left);
			}

			if (right) {
				console.log('marker2: ' + right);
			}

			// if both buttons are pressed, disconnect:
			if (left && right) {
				tag.disconnect();
			}
		});
	}

	//
	// Build time stamp according to YYYY:MM:DD:HH:MM:SS:MS
	//
	function getDateTime() {

		var date = new Date();

		var hour = date.getHours();
		hour = (hour < 10 ? "0" : "") + hour;

		var min = date.getMinutes();
		min = (min < 10 ? "0" : "") + min;

		var sec = date.getSeconds();
		sec = (sec < 10 ? "0" : "") + sec;

		var ms = date.getMilliseconds();
		ms = (ms < 10 ? "0" : "") + ms

		var year = date.getFullYear();

		var month = date.getMonth() + 1;
		month = (month < 10 ? "0" : "") + month;

		var day = date.getDate();
		day = (day < 10 ? "0" : "") + day;

		return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec + ":" + ms;

	}

	// Now that you've defined all the functions, start the process:
	connectAndSetUpMe();
});
	//
	// Job - this is what actually queues your data
	//
	function newSensorDataJob(t, x, y, z, temp) {
		// x = x || 'Default_val';
		var job = queue.create('sleepia', {
			timestamp: t,
			x: x,
			y: y,
			z: z,
			t: temp
		});

		job.on('complete', function() {
			console.log('Job ID', job.id, 'with values', job.data.timestamp, job.data.x, job.data.y, job.data.z, job.data.t, 'is done');
		});

		job.on('failed', function() {
			console.log('Job ID', job.id, job.data.timestamp, 'with values', job.data.x, 'has failed');
		});

		job.save();
	}

	//
	// Close the transaction opened by the new job function
	//
	queue.process('sleepia', function(job, done) {
		/* carry out all the job function here */
		done && done();
	});

	//
	// Shutdown grecefully if CTRL+C is pressed
	//
	process.once('SIGTERM', function(sig) {

		kue.shutdown(5000, function(err) {
			console.log('Graceful shutdown started: ', err || '');

			process.exit(0);
		});
	});<commit_msg>indented code moved some blocks to make the code easier to read<commit_after>/*
	SLEEPIA PROJECT
	Author: Mario Esposito

	Libraries:
		Sandeep Mistry's sensortag
		Kue
		Redis
*/

var SensorTag = require('sensortag'); // sensortag library
var kue = require('kue'); // queue management library
var queue = kue.createQueue({
	prefix: 'q',
	redis: {
		port: 6379,
		host: 'localhost',
		auth: '', // use a password even if not exposed to the Internet!!
		db: 0, // database ID
		options: {
			// see https://github.com/mranney/node_redis#rediscreateclient
		}
	}
});

if(process.argv[1] == "foo")
	console.log('test done');

// listen for tags:
SensorTag.discover(function(tag) {

	// when you disconnect from a tag, exit the program:
	//
	tag.on('disconnect', function() {
		console.log('# Device Disconnected!');
		kue.shutdown(2000, function(err) {
			console.log('# Shutting down: ', err || '');
		});

		//
		// Connect and setup
		//
		function connectAndSetUpMe() { // attempt to connect to the tag
			console.log('# Connecting...');
			tag.connectAndSetUp(enableSensors); // when you connect and device is setup, call enableAccelMe
		}

		//
		// This function enables the accelerometer stream
		//
		function enableSensors() { // attempt to enable the accelerometer
			console.log('# Enabled Sensors (Acc, IR Temp)');
			// when you enable the accelerometer, start accelerometer notifications:
			tag.enableAccelerometer(notifyMe); // start the accelerometer listner
			tag.enableIrTemperature(notifyMe); // start the IR temp sensor listner

			console.log('timestamp, X, Y, Z, ambientTemp');
		}

		//
		// Activate which service we want to be notified by
		//
		function notifyMe() {
			tag.notifyAccelerometer(notificationManager); // setup call back for accelerometer
			tag.notifyIrTemperature(notificationManager); // setup call back for IR temp
			tag.notifySimpleKey(listenForButton); // setup call back for button/switches
		}

		//
		// When you get an accelermeter change, print it out:
		//
		function notificationManager() {
			var at = 0;
			var ot = 0;

			tag.on('irTemperatureChange', function(objectTemp, ambientTemp) {
				ot = objectTemp.toFixed(1);
				at = ambientTemp.toFixed(1);
			});

			tag.on('accelerometerChange', function(x, y, z) {
				// timestamp, 3 axes, temperature
				newSensorDataJob(getDateTime(), x.toFixed(1), y.toFixed(1), z.toFixed(1), at);
				// console.log('%s,%d,%d,%d,%d,%d', getDateTime(), x.toFixed(1), y.toFixed(1), z.toFixed(1), ot, at);
			});
		}

		// when you get a button change, print it out:
		//
		function listenForButton() {

			tag.on('simpleKeyChange', function(left, right) {

				if (left) {
					console.log('marker1: ' + left);
				}

				if (right) {
					console.log('marker2: ' + right);
				}

				// if both buttons are pressed, disconnect:
				if (left && right) {
					tag.disconnect();
				}
			});
		}

		// Now that you've defined all the functions, start the process:
		connectAndSetUpMe();
	});
});

//
// Build time stamp according to YYYY:MM:DD:HH:MM:SS:MS
//
function getDateTime() {

	var date = new Date();

	var hour = date.getHours();
	hour = (hour < 10 ? "0" : "") + hour;

	var min = date.getMinutes();
	min = (min < 10 ? "0" : "") + min;

	var sec = date.getSeconds();
	sec = (sec < 10 ? "0" : "") + sec;

	var ms = date.getMilliseconds();
	ms = (ms < 10 ? "0" : "") + ms

	var year = date.getFullYear();

	var month = date.getMonth() + 1;
	month = (month < 10 ? "0" : "") + month;

	var day = date.getDate();
	day = (day < 10 ? "0" : "") + day;

	return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec + ":" + ms;

}

//
// Job - this is what actually queues your data
//
function newSensorDataJob(t, x, y, z, temp) {
	// x = x || 'Default_val';
	var job = queue.create('sleepia', {
		timestamp: t,
		x: x,
		y: y,
		z: z,
		t: temp
	});

	job.on('complete', function() {
		console.log('Job ID', job.id, 'with values', job.data.timestamp, job.data.x, job.data.y, job.data.z, job.data.t, 'is done');
	});

	job.on('failed', function() {
		console.log('Job ID', job.id, job.data.timestamp, 'with values', job.data.x, 'has failed');
	});

	job.save();
}

//
// Close the transaction opened by the new job function
//
queue.process('sleepia', function(job, done) {
	/* carry out all the job function here */
	done && done();
});

//
// Shutdown grecefully if CTRL+C is pressed
//
process.once('SIGTERM', function(sig) {

	kue.shutdown(5000, function(err) {
		console.log('Graceful shutdown started: ', err || '');

		process.exit(0);
	});
});<|endoftext|>


<commit_before>import {authenticateSession, invalidateSession} from 'ember-simple-auth/test-support';
import {currentURL, find, visit} from '@ember/test-helpers';
import {describe, it} from 'mocha';
import {enableLabsFlag} from '../helpers/labs-flag';
import {expect} from 'chai';
import {setupApplicationTest} from 'ember-mocha';
import {setupMirage} from 'ember-cli-mirage/test-support';

describe('Acceptance: Dashboard', function () {
    const hooks = setupApplicationTest();
    setupMirage(hooks);

    let user;

    beforeEach(async function () {
        this.server.loadFixtures('configs');
        this.server.loadFixtures('settings');
        enableLabsFlag(this.server, 'membersActivity');
        enableLabsFlag(this.server, 'improvedOnboarding');

        let role = this.server.create('role', {name: 'Administrator'});
        user = this.server.create('user', {roles: [role]});

        return await authenticateSession();
    });

    it('can visit /dashboard', async function () {
        await visit('/dashboard');
        expect(currentURL()).to.equal('/dashboard');
    });

    it('/ redirects to /dashboard', async function () {
        await visit('/');
        expect(currentURL()).to.equal('/dashboard');
    });

    describe('members graphs', function () {
        it('is shown when members exist', async function () {
            this.server.createList('member', 5);
            await visit('/dashboard');
            expect(find('[data-test-dashboard-members-graphs]'), 'members graphs block').to.exist;
        });

        it('is hidden when no members exist', async function () {
            this.server.db.members.remove();
            await visit('/dashboard');
            expect(find('[data-test-dashboard-members-graphs]'), 'members graphs block').to.not.exist;
        });

        it('is hidden when members is disabled', async function () {
            this.server.createList('member', 5);
            this.server.db.settings.update({key: 'members_signup_access'}, {value: 'none'});

            await visit('/dashboard');
            expect(find('[data-test-dashboard-members-graphs]'), 'members graphs block').to.not.exist;
        });
    });

    describe('permissions', function () {
        beforeEach(async function () {
            this.server.db.users.remove();
            await invalidateSession();
        });

        it('is not accessible when logged out', async function () {
            await visit('/dashboard');
            expect(currentURL()).to.equal('/signin');
        });
    });
});
<commit_msg>Fixed linter error for unused variable in dashboard-test.js<commit_after>import {authenticateSession, invalidateSession} from 'ember-simple-auth/test-support';
import {currentURL, find, visit} from '@ember/test-helpers';
import {describe, it} from 'mocha';
import {enableLabsFlag} from '../helpers/labs-flag';
import {expect} from 'chai';
import {setupApplicationTest} from 'ember-mocha';
import {setupMirage} from 'ember-cli-mirage/test-support';

describe('Acceptance: Dashboard', function () {
    const hooks = setupApplicationTest();
    setupMirage(hooks);

    beforeEach(async function () {
        this.server.loadFixtures('configs');
        this.server.loadFixtures('settings');
        enableLabsFlag(this.server, 'membersActivity');
        enableLabsFlag(this.server, 'improvedOnboarding');

        let role = this.server.create('role', {name: 'Administrator'});
        this.server.create('user', {roles: [role]});

        return await authenticateSession();
    });

    it('can visit /dashboard', async function () {
        await visit('/dashboard');
        expect(currentURL()).to.equal('/dashboard');
    });

    it('/ redirects to /dashboard', async function () {
        await visit('/');
        expect(currentURL()).to.equal('/dashboard');
    });

    describe('members graphs', function () {
        it('is shown when members exist', async function () {
            this.server.createList('member', 5);
            await visit('/dashboard');
            expect(find('[data-test-dashboard-members-graphs]'), 'members graphs block').to.exist;
        });

        it('is hidden when no members exist', async function () {
            this.server.db.members.remove();
            await visit('/dashboard');
            expect(find('[data-test-dashboard-members-graphs]'), 'members graphs block').to.not.exist;
        });

        it('is hidden when members is disabled', async function () {
            this.server.createList('member', 5);
            this.server.db.settings.update({key: 'members_signup_access'}, {value: 'none'});

            await visit('/dashboard');
            expect(find('[data-test-dashboard-members-graphs]'), 'members graphs block').to.not.exist;
        });
    });

    describe('permissions', function () {
        beforeEach(async function () {
            this.server.db.users.remove();
            await invalidateSession();
        });

        it('is not accessible when logged out', async function () {
            await visit('/dashboard');
            expect(currentURL()).to.equal('/signin');
        });
    });
});
<|endoftext|>


<commit_before><commit_msg>directly switch off routing with marker button on navpage again<commit_after><|endoftext|>