<commit_before>CONSTS = {
    GAME: {
        BULLET: {
            SPEED: 10,
        },
        ENEMY: {
            SPEED: 1,
        },
        SCREEN: {
            HEIGHT: 300,
            WIDTH: 400,
        },
        SHIP: {
            SPEED: 3,
        },
    },
    KEYS: {
        SPACE_BAR: 32,
        LEFT_ARROW: 37,
        UP_ARROW: 38,
        RIGHT_ARROW: 39,
        DOWN_ARROW: 40,
    }
};

state = {
    bullets: {},
    enemies: {},
    input: {
        left: false,
        up: false,
        right: false,
        down: false,
        shoot: false,
    }
};

textures = {
    bullet: PIXI.Texture.fromImage('assets/bullet.png'),
    enemy: PIXI.Texture.fromImage('assets/target.png'),
    ship: PIXI.Texture.fromImage('assets/ship.png'),
};

function Ship() {
    this.sprite = new PIXI.Sprite(textures.ship);
    this.sprite.anchor.x = 0.5;
    this.sprite.anchor.y = 0.5;
    this.sprite.position.x = 200;
    this.sprite.position.y = 150;
    stage.addChild(this.sprite);
}
Ship.prototype.getX = function () {
    return this.sprite.x;
}
Ship.prototype.getY = function () {
    return this.sprite.y;
}
Ship.prototype.moveDown = function () {
    this.sprite.y += CONSTS.GAME.SHIP.SPEED;
}
Ship.prototype.moveLeft = function () {
    this.sprite.x -= CONSTS.GAME.SHIP.SPEED;
}
Ship.prototype.moveRight = function () {
    this.sprite.x += CONSTS.GAME.SHIP.SPEED;
}
Ship.prototype.moveUp = function () {
    this.sprite.y -= CONSTS.GAME.SHIP.SPEED;
}

function Bullet(x, y) {
    this.id = Date.now();
    this.speed = CONSTS.GAME.BULLET.SPEED
    this.sprite = new PIXI.Sprite(textures.bullet);
    this.sprite.anchor.x = 0.5;
    this.sprite.anchor.y = 0.5;
    this.sprite.position.x = x;
    this.sprite.position.y = y;
    stage.addChild(this.sprite);
    state.bullets[this.id] = this;
}
Bullet.prototype.getHitboxCoordinates = function () {
    return {
        x1: this.sprite.x + this.hitbox.x[0],
        x2: this.sprite.x + this.hitbox.x[1],
        y1: this.sprite.y + this.hitbox.y[0],
        y2: this.sprite.y + this.hitbox.y[1],
    }
}
Bullet.prototype.hitbox = {
    x: [-2, 2],
    y: [-2, 2],
}
Bullet.prototype.move = function () {
    this.sprite.x += this.speed;
}
Bullet.prototype.remove = function () {
    stage.removeChild(this.sprite);
    delete state.bullets[this.id];
}
Bullet.prototype.removeIfDead = function (index) {
    if (this.sprite.x > CONSTS.GAME.SCREEN.WIDTH) {
        this.remove();
    }
}

function fireBullet() {
    new Bullet(ship.getX(), ship.getY());
    state.input.shoot = false;
}

function moveBullets() {
    _.each(state.bullets, function (bullet) {
        bullet.move();
        bullet.removeIfDead();
    });
}

function Enemy(x, y) {
    this.id = Date.now();
    this.speed = CONSTS.GAME.ENEMY.SPEED;
    this.sprite = new PIXI.Sprite(textures.enemy);
    this.sprite.anchor.x = 0.5;
    this.sprite.anchor.y = 0.5;
    this.sprite.position.x = x;
    this.sprite.position.y = y;
    stage.addChild(this.sprite);
    state.enemies[this.id] = this;
}
Enemy.prototype.getHitboxCoordinates = function () {
    return {
        x1: this.sprite.x + this.hitbox.x[0],
        x2: this.sprite.x + this.hitbox.x[1],
        y1: this.sprite.y + this.hitbox.y[0],
        y2: this.sprite.y + this.hitbox.y[1],
    }
}
Enemy.prototype.getX = function () {
    return this.sprite.x;
}
Enemy.prototype.getY = function () {
    return this.sprite.y;
}
Enemy.prototype.hitbox = {
    x: [-3, 3],
    y: [-3, 3],
}
Enemy.prototype.move = function () {
    this.sprite.x -= this.speed;
}
Enemy.prototype.remove = function () {
    stage.removeChild(this.sprite);
    delete state.enemies[this.id];
}
Enemy.prototype.removeIfDead = function () {
    if (this.sprite.x < 0) {
        this.remove();
    }
}

function moveEnemies() {
    _.each(state.enemies, function (enemy) {
        enemy.move();
        enemy.removeIfDead();
    });
}

function checkForCollisions() {
    _.each(state.bullets, function (bullet) {
        _.each(state.enemies, function (enemy) {
            bulletHitbox = bullet.getHitboxCoordinates();
            enemyHitbox = enemy.getHitboxCoordinates();

            if (bulletHitbox.x2 >= enemyHitbox.x1) {
                if (bulletHitbox.x1 <= enemyHitbox.x2) {

                    if (bulletHitbox.y2 >= enemyHitbox.y1) {
                        if (bulletHitbox.y1 <= enemyHitbox.y2) {
                            enemy.remove();
                            bullet.remove();
                        }
                    }
                }
            }
        });
    });
}

var stage = new PIXI.Container();
var renderer = PIXI.autoDetectRenderer(CONSTS.GAME.SCREEN.WIDTH, CONSTS.GAME.SCREEN.HEIGHT, {
    backgroundColor: 0x000000
});

document.body.appendChild(renderer.view);

requestAnimationFrame(animate);

var ship = new Ship();

new Enemy(450, 150);

function animate() {
    requestAnimationFrame(animate);

    moveBullets();
    moveEnemies();

    if (state.input.left) {
        ship.moveLeft();
    }
    if (state.input.up) {
        ship.moveUp();
    }
    if (state.input.right) {
        ship.moveRight();
    }
    if (state.input.down) {
        ship.moveDown();
    }

    if (state.input.shoot) {
        fireBullet();
    }

    checkForCollisions();

    renderer.render(stage);
}

document.addEventListener('keydown', function (event) {
    if (event.keyCode == CONSTS.KEYS.LEFT_ARROW) {
        state.input.left = true;
    } else if (event.keyCode == CONSTS.KEYS.UP_ARROW) {
        state.input.up = true;
    } else if (event.keyCode == CONSTS.KEYS.RIGHT_ARROW) {
        state.input.right = true;
    } else if (event.keyCode == CONSTS.KEYS.DOWN_ARROW) {
        state.input.down = true;
    } else if (event.keyCode == CONSTS.KEYS.SPACE_BAR) {
        state.input.shoot = true;
    }
});

document.addEventListener('keyup', function (event) {
    if (event.keyCode == CONSTS.KEYS.LEFT_ARROW) {
        state.input.left = false;
    } else if (event.keyCode == CONSTS.KEYS.UP_ARROW) {
        state.input.up = false;
    } else if (event.keyCode == CONSTS.KEYS.RIGHT_ARROW) {
        state.input.right = false;
    } else if (event.keyCode == CONSTS.KEYS.DOWN_ARROW) {
        state.input.down = false;
    } else if (event.keyCode == CONSTS.KEYS.SPACE_BAR) {
        state.input.shoot = false;
    }
});
<commit_msg>Add strict mode and missing var keywords<commit_after>'use strict';

var CONSTS = {
    GAME: {
        BULLET: {
            SPEED: 10,
        },
        ENEMY: {
            SPEED: 1,
        },
        SCREEN: {
            HEIGHT: 300,
            WIDTH: 400,
        },
        SHIP: {
            SPEED: 3,
        },
    },
    KEYS: {
        SPACE_BAR: 32,
        LEFT_ARROW: 37,
        UP_ARROW: 38,
        RIGHT_ARROW: 39,
        DOWN_ARROW: 40,
    }
};

var state = {
    bullets: {},
    enemies: {},
    input: {
        left: false,
        up: false,
        right: false,
        down: false,
        shoot: false,
    }
};

var textures = {
    bullet: PIXI.Texture.fromImage('assets/bullet.png'),
    enemy: PIXI.Texture.fromImage('assets/target.png'),
    ship: PIXI.Texture.fromImage('assets/ship.png'),
};

function Ship() {
    this.sprite = new PIXI.Sprite(textures.ship);
    this.sprite.anchor.x = 0.5;
    this.sprite.anchor.y = 0.5;
    this.sprite.position.x = 200;
    this.sprite.position.y = 150;
    stage.addChild(this.sprite);
}
Ship.prototype.getX = function () {
    return this.sprite.x;
}
Ship.prototype.getY = function () {
    return this.sprite.y;
}
Ship.prototype.moveDown = function () {
    this.sprite.y += CONSTS.GAME.SHIP.SPEED;
}
Ship.prototype.moveLeft = function () {
    this.sprite.x -= CONSTS.GAME.SHIP.SPEED;
}
Ship.prototype.moveRight = function () {
    this.sprite.x += CONSTS.GAME.SHIP.SPEED;
}
Ship.prototype.moveUp = function () {
    this.sprite.y -= CONSTS.GAME.SHIP.SPEED;
}

function Bullet(x, y) {
    this.id = Date.now();
    this.speed = CONSTS.GAME.BULLET.SPEED
    this.sprite = new PIXI.Sprite(textures.bullet);
    this.sprite.anchor.x = 0.5;
    this.sprite.anchor.y = 0.5;
    this.sprite.position.x = x;
    this.sprite.position.y = y;
    stage.addChild(this.sprite);
    state.bullets[this.id] = this;
}
Bullet.prototype.getHitboxCoordinates = function () {
    return {
        x1: this.sprite.x + this.hitbox.x[0],
        x2: this.sprite.x + this.hitbox.x[1],
        y1: this.sprite.y + this.hitbox.y[0],
        y2: this.sprite.y + this.hitbox.y[1],
    }
}
Bullet.prototype.hitbox = {
    x: [-2, 2],
    y: [-2, 2],
}
Bullet.prototype.move = function () {
    this.sprite.x += this.speed;
}
Bullet.prototype.remove = function () {
    stage.removeChild(this.sprite);
    delete state.bullets[this.id];
}
Bullet.prototype.removeIfDead = function (index) {
    if (this.sprite.x > CONSTS.GAME.SCREEN.WIDTH) {
        this.remove();
    }
}

function fireBullet() {
    new Bullet(ship.getX(), ship.getY());
    state.input.shoot = false;
}

function moveBullets() {
    _.each(state.bullets, function (bullet) {
        bullet.move();
        bullet.removeIfDead();
    });
}

function Enemy(x, y) {
    this.id = Date.now();
    this.speed = CONSTS.GAME.ENEMY.SPEED;
    this.sprite = new PIXI.Sprite(textures.enemy);
    this.sprite.anchor.x = 0.5;
    this.sprite.anchor.y = 0.5;
    this.sprite.position.x = x;
    this.sprite.position.y = y;
    stage.addChild(this.sprite);
    state.enemies[this.id] = this;
}
Enemy.prototype.getHitboxCoordinates = function () {
    return {
        x1: this.sprite.x + this.hitbox.x[0],
        x2: this.sprite.x + this.hitbox.x[1],
        y1: this.sprite.y + this.hitbox.y[0],
        y2: this.sprite.y + this.hitbox.y[1],
    }
}
Enemy.prototype.getX = function () {
    return this.sprite.x;
}
Enemy.prototype.getY = function () {
    return this.sprite.y;
}
Enemy.prototype.hitbox = {
    x: [-3, 3],
    y: [-3, 3],
}
Enemy.prototype.move = function () {
    this.sprite.x -= this.speed;
}
Enemy.prototype.remove = function () {
    stage.removeChild(this.sprite);
    delete state.enemies[this.id];
}
Enemy.prototype.removeIfDead = function () {
    if (this.sprite.x < 0) {
        this.remove();
    }
}

function moveEnemies() {
    _.each(state.enemies, function (enemy) {
        enemy.move();
        enemy.removeIfDead();
    });
}

function checkForCollisions() {
    _.each(state.bullets, function (bullet) {
        _.each(state.enemies, function (enemy) {
            var bulletHitbox = bullet.getHitboxCoordinates();
            var enemyHitbox = enemy.getHitboxCoordinates();

            if (bulletHitbox.x2 >= enemyHitbox.x1) {
                if (bulletHitbox.x1 <= enemyHitbox.x2) {

                    if (bulletHitbox.y2 >= enemyHitbox.y1) {
                        if (bulletHitbox.y1 <= enemyHitbox.y2) {
                            enemy.remove();
                            bullet.remove();
                        }
                    }
                }
            }
        });
    });
}

var stage = new PIXI.Container();
var renderer = PIXI.autoDetectRenderer(CONSTS.GAME.SCREEN.WIDTH, CONSTS.GAME.SCREEN.HEIGHT, {
    backgroundColor: 0x000000
});

document.body.appendChild(renderer.view);

requestAnimationFrame(animate);

var ship = new Ship();

new Enemy(450, 150);

function animate() {
    requestAnimationFrame(animate);

    moveBullets();
    moveEnemies();

    if (state.input.left) {
        ship.moveLeft();
    }
    if (state.input.up) {
        ship.moveUp();
    }
    if (state.input.right) {
        ship.moveRight();
    }
    if (state.input.down) {
        ship.moveDown();
    }

    if (state.input.shoot) {
        fireBullet();
    }

    checkForCollisions();

    renderer.render(stage);
}

document.addEventListener('keydown', function (event) {
    if (event.keyCode == CONSTS.KEYS.LEFT_ARROW) {
        state.input.left = true;
    } else if (event.keyCode == CONSTS.KEYS.UP_ARROW) {
        state.input.up = true;
    } else if (event.keyCode == CONSTS.KEYS.RIGHT_ARROW) {
        state.input.right = true;
    } else if (event.keyCode == CONSTS.KEYS.DOWN_ARROW) {
        state.input.down = true;
    } else if (event.keyCode == CONSTS.KEYS.SPACE_BAR) {
        state.input.shoot = true;
    }
});

document.addEventListener('keyup', function (event) {
    if (event.keyCode == CONSTS.KEYS.LEFT_ARROW) {
        state.input.left = false;
    } else if (event.keyCode == CONSTS.KEYS.UP_ARROW) {
        state.input.up = false;
    } else if (event.keyCode == CONSTS.KEYS.RIGHT_ARROW) {
        state.input.right = false;
    } else if (event.keyCode == CONSTS.KEYS.DOWN_ARROW) {
        state.input.down = false;
    } else if (event.keyCode == CONSTS.KEYS.SPACE_BAR) {
        state.input.shoot = false;
    }
});
<|endoftext|>


<commit_before>import React from 'react';
import { Provider } from 'react-redux';

import App from './containers/App';
import configureStore from './store/configureStore';

const store = configureStore();

React.render(
  // The child must be wrapped in a function
  // to work around an issue in React 0.13.
  <Provider store={store}>
    {() => <App />}
  </Provider>,
  document.getElementById('root')
);
<commit_msg>comments<commit_after>import React from 'react';

// Now is the time to meet the first binding that redux-react
// (https://github.com/gaearon/react-redux)
// brings to us: the Provider component.
import { Provider } from 'react-redux';

import App from './containers/App';
import configureStore from './store/configureStore';

const store = configureStore();

// Provider is a React Component designed to be used as a wrapper of your application's root component. Its
// purpose is to provide your redux instance to all of your application's components. How it does that does not
// really matter to us but just to let you know, it's using React's context feature (it's undocumented so you
// don't have to know about it, but if you're curious:
// https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html).

// The Provider must wrap your application's Root component. This way,
// this component and all of its children (even deeply nested ones) will have access to your
// Redux store. Of course, to allow Provider to do that, you must give it the store
// you built previously (via a "store" props).
// That's almost all there is to say about Provider...

React.render(
  // Provider needs to have as its child, a function that returns
  // the root component instead of the component itself. This is a temporary API until React 0.14 comes
  // out, to fix a React 0.13 context issue.
  <Provider store={store}>
    {() => <App />}
  </Provider>,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>// Make sure the XWiki 'namespace' and the ModalPopup class exist.
if(typeof(XWiki) == "undefined" || typeof(XWiki.widgets) == "undefined" || typeof(XWiki.widgets.ModalPopup) == "undefined") {
  if (typeof console != "undefined" && typeof console.warn == "function") {
    console.warn("[JumpToPage widget] Required class missing: XWiki.widgets.ModalPopup");
  }
} else {
/**
 * "Jump to page" behavior. Allows the users to jump to any other page by pressing a shortcut, entering a page name, and
 * pressing enter. It also enables a Suggest behavior on the document name selector, for easier selection.
 */
XWiki.widgets.JumpToPage = Class.create(XWiki.widgets.ModalPopup, {
  /** The template of the XWiki URL. */
  urlTemplate : "$xwiki.getURL('__space__.__document__', '__action__')",
  /** Constructor. Registers the key listener that pops up the dialog. */
  initialize : function($super) {
    var content = new Element("div");
    this.input = new Element("input", {
      "type" : "text",
      "id" : "jmp_target",
      "title" : "$msg.get('core.viewers.jump.dialog.input.tooltip')"
    });
    content.appendChild(this.input);
    this.viewButton = this.createButton("button", "$msg.get('core.viewers.jump.dialog.actions.view')", "$msg.get('core.viewers.jump.dialog.actions.view.tooltip')", "jmp_view");
    this.editButton = this.createButton("button", "$msg.get('core.viewers.jump.dialog.actions.edit')", "$msg.get('core.viewers.jump.dialog.actions.edit.tooltip')", "jmp_edit");
    var buttonContainer = new Element("div", {"class" : "buttons"});
    buttonContainer.appendChild(this.viewButton);
    buttonContainer.appendChild(this.editButton);
    content.appendChild(buttonContainer);
    $super(
      content,
      {
        "show" : { method : this.showDialog, keys : [$msg.get('core.viewers.jump.shortcuts')] },
        "view" : { method : this.openDocument, keys : [$msg.get('core.viewers.jump.dialog.actions.view.shortcuts')] },
        "edit" : { method : this.openDocument, keys : [$msg.get('core.viewers.jump.dialog.actions.edit.shortcuts')] }
      },
      {
        title : "$msg.get('core.viewers.jump.dialog.content')",
        verticalPosition : "top"
      }
    );
    this.addQuickLinksEntry();
  },
  /**
   * Callback called when the UI was fully retrieved and inserted. Adds listeners to the buttons, enables the suggest,
   * and forwards the call to the {@link #showDialog} method.
   */
  createDialog : function($super, event) {
    // Register the listeners executed when clicking on the buttons.
    Event.observe(this.viewButton, 'click', this.openDocument.bindAsEventListener(this, "view"));
    Event.observe(this.editButton, 'click', this.openDocument.bindAsEventListener(this, "edit"));
    $super(event);
    if (typeof(XWiki.widgets.Suggest) != "undefined") {
      // Create the Suggest.
      new XWiki.widgets.Suggest(this.input, {
        // This document also provides the suggestions.
        script: "${request.contextPath}/rest/wikis/${context.database}/search?scope=name&number=10&media=json&",
        // Prefixed with & since the current (as of 1.7) Suggest code does not automatically append it.
        varname: "q",
        noresults: "$msg.get('core.viewers.jump.suggest.noResults')",
        icon: "${xwiki.getSkinFile('icons/silk/page_white_text.gif')}",
        json: true,
        resultsParameter : "searchResults",
        resultId : "id",
        resultValue : "pageFullName",
        resultInfo : "pageFullName",
        timeout : 30000,
        parentContainer : this.dialog
      });
    }
  },
  /** Called when the dialog is displayed. Enables the key listeners and gives focus to the (cleared) input. */
  showDialog : function($super) {
    // Display the dialog
    $super();
    // Clear the input field
    this.input.value = '';
    // Focus the input field
    this.input.focus();
  },
  /**
   * Open the selected document in the specified mode.
   *
   * @param {Event} event The event that triggered this action. Either a keyboard shortcut or a button click.
   * @param {String} mode The mode that the document should be opened in. One of "view" or "edit". Note that on the
   *     server side, "edit" could be replaced with "inline" if the document is sheet-based.
   */
  openDocument : function(event, mode) {
    if (!$('as_jmp_target') && this.input.value != "") {
      Event.stop(event);
      window.self.location = this.urlTemplate.replace("__space__/__document__", this.input.value.replace(".", "/")).replace("__action__", mode);
    }
  },
  addQuickLinksEntry : function() {
    $$(".panel.QuickLinks .xwikipanelcontents").each(function(item) {
      var jumpToPageActivator = new Element('span', {'class': "jmp-activator"});
      jumpToPageActivator.update("$msg.get('core.viewers.jump.quickLinksText')");
      Event.observe(jumpToPageActivator, "click", function(event) {
        this.showDialog(event);
      }.bindAsEventListener(this));
      item.appendChild(jumpToPageActivator);
    }.bind(this));
  }
});

// When the document is loaded, enable the keyboard listener that triggers the dialog.
document.observe("xwiki:dom:loaded", function() {
  new XWiki.widgets.JumpToPage();
});
} // if the parent widget is defined<commit_msg>XWIKI-6640: JumpToPage widget doesn't display the correct suggestions when including + or & in the search box Fixed.<commit_after>// Make sure the XWiki 'namespace' and the ModalPopup class exist.
if(typeof(XWiki) == "undefined" || typeof(XWiki.widgets) == "undefined" || typeof(XWiki.widgets.ModalPopup) == "undefined") {
  if (typeof console != "undefined" && typeof console.warn == "function") {
    console.warn("[JumpToPage widget] Required class missing: XWiki.widgets.ModalPopup");
  }
} else {
/**
 * "Jump to page" behavior. Allows the users to jump to any other page by pressing a shortcut, entering a page name, and
 * pressing enter. It also enables a Suggest behavior on the document name selector, for easier selection.
 */
XWiki.widgets.JumpToPage = Class.create(XWiki.widgets.ModalPopup, {
  /** The template of the XWiki URL. */
  urlTemplate : "$xwiki.getURL('__space__.__document__', '__action__')",
  /** Constructor. Registers the key listener that pops up the dialog. */
  initialize : function($super) {
    var content = new Element("div");
    this.input = new Element("input", {
      "type" : "text",
      "id" : "jmp_target",
      "title" : "$msg.get('core.viewers.jump.dialog.input.tooltip')"
    });
    content.appendChild(this.input);
    this.viewButton = this.createButton("button", "$msg.get('core.viewers.jump.dialog.actions.view')", "$msg.get('core.viewers.jump.dialog.actions.view.tooltip')", "jmp_view");
    this.editButton = this.createButton("button", "$msg.get('core.viewers.jump.dialog.actions.edit')", "$msg.get('core.viewers.jump.dialog.actions.edit.tooltip')", "jmp_edit");
    var buttonContainer = new Element("div", {"class" : "buttons"});
    buttonContainer.appendChild(this.viewButton);
    buttonContainer.appendChild(this.editButton);
    content.appendChild(buttonContainer);
    $super(
      content,
      {
        "show" : { method : this.showDialog, keys : [$msg.get('core.viewers.jump.shortcuts')] },
        "view" : { method : this.openDocument, keys : [$msg.get('core.viewers.jump.dialog.actions.view.shortcuts')] },
        "edit" : { method : this.openDocument, keys : [$msg.get('core.viewers.jump.dialog.actions.edit.shortcuts')] }
      },
      {
        title : "$msg.get('core.viewers.jump.dialog.content')",
        verticalPosition : "top"
      }
    );
    this.addQuickLinksEntry();
  },
  /**
   * Callback called when the UI was fully retrieved and inserted. Adds listeners to the buttons, enables the suggest,
   * and forwards the call to the {@link #showDialog} method.
   */
  createDialog : function($super, event) {
    // Register the listeners executed when clicking on the buttons.
    Event.observe(this.viewButton, 'click', this.openDocument.bindAsEventListener(this, "view"));
    Event.observe(this.editButton, 'click', this.openDocument.bindAsEventListener(this, "edit"));
    $super(event);
    if (typeof(XWiki.widgets.Suggest) != "undefined") {
      // Create the Suggest.
      new XWiki.widgets.Suggest(this.input, {
        // This document also provides the suggestions.
        script: "${request.contextPath}/rest/wikis/${context.database}/search?scope=name&number=10&",
        // Prefixed with & since the current (as of 1.7) Suggest code does not automatically append it.
        varname: "q",
        noresults: "$msg.get('core.viewers.jump.suggest.noResults')",
        icon: "${xwiki.getSkinFile('icons/silk/page_white_text.gif')}",
        json: true,
        resultsParameter : "searchResults",
        resultId : "id",
        resultValue : "pageFullName",
        resultInfo : "pageFullName",
        timeout : 30000,
        parentContainer : this.dialog
      });
    }
  },
  /** Called when the dialog is displayed. Enables the key listeners and gives focus to the (cleared) input. */
  showDialog : function($super) {
    // Display the dialog
    $super();
    // Clear the input field
    this.input.value = '';
    // Focus the input field
    this.input.focus();
  },
  /**
   * Open the selected document in the specified mode.
   *
   * @param {Event} event The event that triggered this action. Either a keyboard shortcut or a button click.
   * @param {String} mode The mode that the document should be opened in. One of "view" or "edit". Note that on the
   *     server side, "edit" could be replaced with "inline" if the document is sheet-based.
   */
  openDocument : function(event, mode) {
    if (!$('as_jmp_target') && this.input.value != "") {
      Event.stop(event);
      window.self.location = this.urlTemplate.replace("__space__/__document__", this.input.value.replace(".", "/")).replace("__action__", mode);
    }
  },
  addQuickLinksEntry : function() {
    $$(".panel.QuickLinks .xwikipanelcontents").each(function(item) {
      var jumpToPageActivator = new Element('span', {'class': "jmp-activator"});
      jumpToPageActivator.update("$msg.get('core.viewers.jump.quickLinksText')");
      Event.observe(jumpToPageActivator, "click", function(event) {
        this.showDialog(event);
      }.bindAsEventListener(this));
      item.appendChild(jumpToPageActivator);
    }.bind(this));
  }
});

// When the document is loaded, enable the keyboard listener that triggers the dialog.
document.observe("xwiki:dom:loaded", function() {
  new XWiki.widgets.JumpToPage();
});
} // if the parent widget is defined<|endoftext|>


<commit_before>import './exit';
import config from './config';

console.log(process.env.test);

process.on("SIGINT", function () {
  //graceful shutdown
  process.exit();
});<commit_msg>messing with what bot can hear<commit_after>import './exit';
import config from './config';
import Botkit from 'botkit';
//console.log(process.env.test);

let token = config.slackToken || process.env.slack_token;

let controller = Botkit.slackbot({
    debug: false
});

controller.spawn({
    token: token
}).startRTM();

controller.hears(['test', 'hey memebot'], ['ambient', 'message_received', 'direct_mention', 'direct_message'], function(bot, message) {
    console.log(message);
    bot.reply(message, 'what the fuck u want');
});

process.on("SIGINT", function () {
  //graceful shutdown
  process.exit();
});<|endoftext|>


<commit_before>var CURR_TIME = (Math.floor(Date.now() / 1000)+31536000) * 1000000000;
var NON_ACTIVE_NUMBERS = [0, 3, 4, 5, 72, 109, 110, 111, 112] //2 = on foot... not sure how to count that
var SLEEP_NUMBERS = [79, 109, 110, 111]
var DAY = 86400000 //number of milliseconds in a day

var weight_data;
var all_activity_data;
var id_token;

function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());

  id_token = googleUser.getAuthResponse().id_token;
  console.log("ID Token: " + id_token);

  loadGapi();
}

function onFailure(error) {
  console.log(error);
}

function signOut() {
  id_token = null;
  var auth2 = gapi.auth2.getAuthInstance();
  auth2.signOut().then(function () {
    console.log('User signed out.');
  });
}

function getWeight() {
  // 2. Initialize the JavaScript client library.
  gapi.client.request("https://www.googleapis.com/fitness/v1/users/me/dataSources?dataTypeName=com.google.weight")
    .then(function(response) {
      weight_sources = response.result;
      idlist = [];
      for (el in weight_sources.dataSource){
        streamId = weight_sources.dataSource[el].dataStreamId;
        if (streamId == "derived:com.google.weight:com.google.android.gms:merge_weight") {
          idlist = [streamId];
          break;
        } else {
          idlist.push(streamId);
        }
      }
      Promise.all(idlist.map(getDataFromStream)).then(function(values){
        var data = extractDataFromStreams(values);
        for (el in data) {
          // Extract data from JSON object and convert kg to pounds
          data[el] = [new Date(+data[el].endTimeNanos/1000000), data[el].value[0].fpVal*2.20462];
        }
        weight_data = data;
        makeGraph(data);
      });
  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
};

function enableButtions() {
  d3.selectAll(".getdata").classed("disabled", false);
}

function loadGapi() {
  gapi.load('client', enableButtions);
};

function getDataFromStream(streamId) {
  console.log("https://www.googleapis.com/fitness/v1/users/me/dataSources/"+streamId+"/datasets/0-"+CURR_TIME);
  return gapi.client.request("https://www.googleapis.com/fitness/v1/users/me/dataSources/"+streamId+"/datasets/0-"+CURR_TIME);
}

function getActivity(){

  var activity_data = gapi.client.request({
    "path" : "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate",
    "method" : "POST",
    "body":{
      "aggregateBy": [
        {
          "dataTypeName": "com.google.activity.segment"
        }
      ],
      "endTimeMillis": Date.now(),
      "startTimeMillis": Date.now() - (30*DAY),
      "bucketByTime": {
        "period": {
          "type": "day",
          "value": 1,
          "timeZoneId": moment.tz.guess()
        }}
    }
  });
  activity_data.then(function(response){
    all_activity_data = response.result.bucket;

  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
}

function graphSleepData(){
  sleep_data = [];
  for (i in all_activity_data) {
    for (j in all_activity_data[i].dataset[0].point){
      if (all_activity_data[i].dataset[0].point[j].value[0].intVal == 72) {
        sleep_data.push([new Date(+all_activity_data[i].dataset[0].point[j].startTimeNanos/1000000), +all_activity_data[i].dataset[0].point[j].value[1].intVal/3600000]);
      }
    }
  }
  makeGraph(sleep_data);
}

function extractDataFromStreams(streams) {
  var data = [];
  for (stream in streams) {
    var curr = streams[stream].result.point;
    if (curr.length > data.length) {
      data = curr;
    }
  }

  return data;
}

function toggleLabelYAxis() {
  $.ajax("http://www.stability-app.com/update_settings", {
      type:"POST",
      dataType:"json",
      contentType:"application/json",
      data:{"user":id_token, "value":true},
      success:function(data, textStatus, jqXHR) {alert("success");},
      error: function(jqXHR, textStatus, errorThrown) {alert("failure");}
  });

  // var xmlHttp = new XMLHttpRequest();
  // xmlHttp.open( "POST", "http://stability-app.com/update_settings", true );
  // xmlHttp.send({"user":id_token, "value":true});
}

function makeGraph(data){
  // Based on https://github.com/jasondavies/science.js/blob/master/examples/loess/loess.js

  max_y = d3.max(data, function(d){return d[1];});
  min_y = d3.min(data, function(d){return d[1];});

  //Add margins
  max_y += max_y*.2
  min_y -= min_y*.2

  var w = 960,
      h = 500,
      p = 35.5,
      n = 100,
      x = d3.scaleTime().domain([new Date(data[0][0]-86400000), new Date(data[data.length-1][0]+86400000)]).range([0, w]),
      y = d3.scaleLinear().domain([min_y, max_y]).range([h, 0]);

  var xAxis = d3.axisBottom(x),
      yAxis = d3.axisLeft(y);

  var vis = d3.select("#vis")
    .append("svg")
      .attr("width", w + p + p)
      .attr("height", h + p + p)
    .append("g")
      .attr("transform", "translate(" + p + "," + p + ")");

  var min_band = 2/data.length;

  var loess = science.stats.loess().bandwidth(d3.max([min_band, .8]));

  var zipped_data = d3.transpose(data);
  var loess_result = loess(zipped_data[0], zipped_data[1]);
  console.log("loess", loess_result);
  zipped_data[1] = loess_result.loess;
  zipped_data.push(loess_result.confint);
  data = d3.zip(zipped_data[0], zipped_data[1], zipped_data[2]);

  var area = d3.area()
        .x(function(d) { return x(d[0]); })
        .y0(function(d) { return d[2] ? y(d[1]-d[2]) : y(d[1]);})
        .y1(function(d) { return d[2] ? y(d[1]+d[2]) : y(d[1]);});

  vis.selectAll("path")
      .data([data])
    .enter().append("path")
      .attr("d", function(d){return area(d);})
      .attr("stroke", "black")
      .attr("fill", "purple")
      .attr("stroke-width", 1);

  vis.append("g")
      .attr("class", "bottom axis")
      .attr("transform", "translate(0," + h + ")")
      .call(xAxis);

  vis.append("g")
      .attr("class", "left axis")
      .call(yAxis);
}
<commit_msg>oops it should be a request<commit_after>var CURR_TIME = (Math.floor(Date.now() / 1000)+31536000) * 1000000000;
var NON_ACTIVE_NUMBERS = [0, 3, 4, 5, 72, 109, 110, 111, 112] //2 = on foot... not sure how to count that
var SLEEP_NUMBERS = [79, 109, 110, 111]
var DAY = 86400000 //number of milliseconds in a day

var weight_data;
var all_activity_data;
var id_token;

function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());

  id_token = googleUser.getAuthResponse().id_token;
  console.log("ID Token: " + id_token);

  loadGapi();
}

function onFailure(error) {
  console.log(error);
}

function signOut() {
  id_token = null;
  var auth2 = gapi.auth2.getAuthInstance();
  auth2.signOut().then(function () {
    console.log('User signed out.');
  });
}

function getWeight() {
  // 2. Initialize the JavaScript client library.
  gapi.client.request("https://www.googleapis.com/fitness/v1/users/me/dataSources?dataTypeName=com.google.weight")
    .then(function(response) {
      weight_sources = response.result;
      idlist = [];
      for (el in weight_sources.dataSource){
        streamId = weight_sources.dataSource[el].dataStreamId;
        if (streamId == "derived:com.google.weight:com.google.android.gms:merge_weight") {
          idlist = [streamId];
          break;
        } else {
          idlist.push(streamId);
        }
      }
      Promise.all(idlist.map(getDataFromStream)).then(function(values){
        var data = extractDataFromStreams(values);
        for (el in data) {
          // Extract data from JSON object and convert kg to pounds
          data[el] = [new Date(+data[el].endTimeNanos/1000000), data[el].value[0].fpVal*2.20462];
        }
        weight_data = data;
        makeGraph(data);
      });
  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
};

function enableButtions() {
  d3.selectAll(".getdata").classed("disabled", false);
}

function loadGapi() {
  gapi.load('client', enableButtions);
};

function getDataFromStream(streamId) {
  console.log("https://www.googleapis.com/fitness/v1/users/me/dataSources/"+streamId+"/datasets/0-"+CURR_TIME);
  return gapi.client.request("https://www.googleapis.com/fitness/v1/users/me/dataSources/"+streamId+"/datasets/0-"+CURR_TIME);
}

function getActivity(){

  var activity_data = gapi.client.request({
    "path" : "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate",
    "method" : "POST",
    "body":{
      "aggregateBy": [
        {
          "dataTypeName": "com.google.activity.segment"
        }
      ],
      "endTimeMillis": Date.now(),
      "startTimeMillis": Date.now() - (30*DAY),
      "bucketByTime": {
        "period": {
          "type": "day",
          "value": 1,
          "timeZoneId": moment.tz.guess()
        }}
    }
  });
  activity_data.then(function(response){
    all_activity_data = response.result.bucket;

  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
}

function graphSleepData(){
  sleep_data = [];
  for (i in all_activity_data) {
    for (j in all_activity_data[i].dataset[0].point){
      if (all_activity_data[i].dataset[0].point[j].value[0].intVal == 72) {
        sleep_data.push([new Date(+all_activity_data[i].dataset[0].point[j].startTimeNanos/1000000), +all_activity_data[i].dataset[0].point[j].value[1].intVal/3600000]);
      }
    }
  }
  makeGraph(sleep_data);
}

function extractDataFromStreams(streams) {
  var data = [];
  for (stream in streams) {
    var curr = streams[stream].result.point;
    if (curr.length > data.length) {
      data = curr;
    }
  }

  return data;
}

function toggleLabelYAxis() {
  $.ajax("http://www.stability-app.com/update_settings", {
      type:"POST",
      dataType:"json",
      contentType:"application/json",
      data:JSON.stringify({"user":id_token, "value":true}),
      success:function(data, textStatus, jqXHR) {alert("success");},
      error: function(jqXHR, textStatus, errorThrown) {alert("failure");}
  });

  // var xmlHttp = new XMLHttpRequest();
  // xmlHttp.open( "POST", "http://stability-app.com/update_settings", true );
  // xmlHttp.send({"user":id_token, "value":true});
}

function makeGraph(data){
  // Based on https://github.com/jasondavies/science.js/blob/master/examples/loess/loess.js

  max_y = d3.max(data, function(d){return d[1];});
  min_y = d3.min(data, function(d){return d[1];});

  //Add margins
  max_y += max_y*.2
  min_y -= min_y*.2

  var w = 960,
      h = 500,
      p = 35.5,
      n = 100,
      x = d3.scaleTime().domain([new Date(data[0][0]-86400000), new Date(data[data.length-1][0]+86400000)]).range([0, w]),
      y = d3.scaleLinear().domain([min_y, max_y]).range([h, 0]);

  var xAxis = d3.axisBottom(x),
      yAxis = d3.axisLeft(y);

  var vis = d3.select("#vis")
    .append("svg")
      .attr("width", w + p + p)
      .attr("height", h + p + p)
    .append("g")
      .attr("transform", "translate(" + p + "," + p + ")");

  var min_band = 2/data.length;

  var loess = science.stats.loess().bandwidth(d3.max([min_band, .8]));

  var zipped_data = d3.transpose(data);
  var loess_result = loess(zipped_data[0], zipped_data[1]);
  console.log("loess", loess_result);
  zipped_data[1] = loess_result.loess;
  zipped_data.push(loess_result.confint);
  data = d3.zip(zipped_data[0], zipped_data[1], zipped_data[2]);

  var area = d3.area()
        .x(function(d) { return x(d[0]); })
        .y0(function(d) { return d[2] ? y(d[1]-d[2]) : y(d[1]);})
        .y1(function(d) { return d[2] ? y(d[1]+d[2]) : y(d[1]);});

  vis.selectAll("path")
      .data([data])
    .enter().append("path")
      .attr("d", function(d){return area(d);})
      .attr("stroke", "black")
      .attr("fill", "purple")
      .attr("stroke-width", 1);

  vis.append("g")
      .attr("class", "bottom axis")
      .attr("transform", "translate(0," + h + ")")
      .call(xAxis);

  vis.append("g")
      .attr("class", "left axis")
      .call(yAxis);
}
<|endoftext|>


<commit_before>// @flow
import { parse } from 'acorn';

import { PARSER_OPTIONS } from './constants';
import extendsLux from './utils/extends-lux';

export default {
  transform(src: string): string {
    const { body } = parse(src, PARSER_OPTIONS);
    const defaultExport = body.find(({ type }) => (
      type === 'ExportDefaultDeclaration'
    ));

    if (!defaultExport || defaultExport.type !== 'ExportDefaultDeclaration') {
      return src;
    }

    // console.log(JSON.stringify(body, null, 2));

    let classDecl;

    switch (defaultExport.declaration.type) {
      case 'Identifier':
        classDecl = body.find(node => (
          node.type === 'ClassDeclaration'
          && node.id.name === defaultExport.declaration.name
        ));

        if (!classDecl) {
          return src;
        }
        break;

      case 'ClassDeclaration':
        ({ declaration: classDecl } = defaultExport);
        break;

      default:
        return src;
    }

    if (extendsLux(classDecl) && classDecl.type === 'ClassDeclaration') {
      const { id: { name } } = classDecl;

      return [
        src,
        `\nObject.defineProperty(${name}, 'name', { value: '${name}' });\n`
      ].join('');
    }

    return src;
  }
};
<commit_msg>chore: remove console.log call<commit_after>// @flow
import { parse } from 'acorn';

import { PARSER_OPTIONS } from './constants';
import extendsLux from './utils/extends-lux';

export default {
  transform(src: string): string {
    const { body } = parse(src, PARSER_OPTIONS);
    const defaultExport = body.find(({ type }) => (
      type === 'ExportDefaultDeclaration'
    ));

    if (!defaultExport || defaultExport.type !== 'ExportDefaultDeclaration') {
      return src;
    }

    let classDecl;

    switch (defaultExport.declaration.type) {
      case 'Identifier':
        classDecl = body.find(node => (
          node.type === 'ClassDeclaration'
          && node.id.name === defaultExport.declaration.name
        ));

        if (!classDecl) {
          return src;
        }
        break;

      case 'ClassDeclaration':
        ({ declaration: classDecl } = defaultExport);
        break;

      default:
        return src;
    }

    if (extendsLux(classDecl) && classDecl.type === 'ClassDeclaration') {
      const { id: { name } } = classDecl;

      return [
        src,
        `\nObject.defineProperty(${name}, 'name', { value: '${name}' });\n`
      ].join('');
    }

    return src;
  }
};
<|endoftext|>


<commit_before>var restify = require('restify');
var app = restify.createServer();
var path = require('path');
var WOL_PORT = process.env.WOL_PORT || 4007;

/* route separation http://bit.ly/1Kt87xZ */
var ping = require('./routes/ping');
var leaderboard = require('./routes/leaderboard');
var auth = require('./routes/auth');
var debug = require('./routes/debug');

app.use(restify.queryParser());
app.use(restify.jsonp());
app.use(restify.bodyParser());

/* ensure game abbr is valid */
app.use(function(req, res, next) {
    if (!req.params.game) return next();
    /* in case client sends abbrv in caps */
    req.params.game = req.params.game.toLowerCase();
    if (!(!!req.params.game.match(/^(td|d2k?|ra2?|ts|fs|yr)$/))) {
        return next(new Error('game abbr invalid'));
    }
    next();
});

/* declare api version and allow origin */
app.use(function(req, res, next) {
    res.header('API-Version', require('../../package').version);
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

/* general */
app.get('/ping', ping);

/* leaderboard */
app.post('/ladder/:game', leaderboard.submit);
app.get('/ladder/:game', leaderboard.rankings);
app.get('/ladder/:game/game/:gameId', leaderboard.match);
app.get('/ladder/:game/player/:player', leaderboard.player);
app.post('/ladder/:game/search', leaderboard.search);

/* auth */
app.get('/auth/:game/:player', auth.player);
app.put('/auth/:game/:player', auth.create);

/* debug */
app.get('/debug/reset', debug.reset);

/* static server for development */
app.get(/.*/, restify.serveStatic({
    directory: __dirname + '/../../dist/public',
    default: 'index.html'
}));

app.listen(WOL_PORT, function() {
    console.log('WOL Leaderboard listening on %s:%s', require('os').hostname(), WOL_PORT);
});
<commit_msg>adding support for DTA <3 Rampastring<commit_after>var restify = require('restify');
var app = restify.createServer();
var path = require('path');
var WOL_PORT = process.env.WOL_PORT || 4007;

/* route separation http://bit.ly/1Kt87xZ */
var ping = require('./routes/ping');
var leaderboard = require('./routes/leaderboard');
var auth = require('./routes/auth');
var debug = require('./routes/debug');

app.use(restify.queryParser());
app.use(restify.jsonp());
app.use(restify.bodyParser());

/* ensure game abbr is valid */
app.use(function(req, res, next) {
    if (!req.params.game) return next();
    /* in case client sends abbrv in caps */
    req.params.game = req.params.game.toLowerCase();
    if (!(!!req.params.game.match(/^(td|d2k?|ra2?|ts|dta|fs|yr)$/))) {
        return next(new Error('game abbr invalid'));
    }
    next();
});

/* declare api version and allow origin */
app.use(function(req, res, next) {
    res.header('API-Version', require('../../package').version);
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

/* general */
app.get('/ping', ping);

/* leaderboard */
app.post('/ladder/:game', leaderboard.submit);
app.get('/ladder/:game', leaderboard.rankings);
app.get('/ladder/:game/game/:gameId', leaderboard.match);
app.get('/ladder/:game/player/:player', leaderboard.player);
app.post('/ladder/:game/search', leaderboard.search);

/* auth */
app.get('/auth/:game/:player', auth.player);
app.put('/auth/:game/:player', auth.create);

/* debug */
app.get('/debug/reset', debug.reset);

/* static server for development */
app.get(/.*/, restify.serveStatic({
    directory: __dirname + '/../../dist/public',
    default: 'index.html'
}));

app.listen(WOL_PORT, function() {
    console.log('WOL Leaderboard listening on %s:%s', require('os').hostname(), WOL_PORT);
});
<|endoftext|>


<commit_before>"use strict";

/*
* Global variables. Will make this more object based soon.
*/
var search = "aww+puppies", // Keep track of the subreddit we want to scrape for images
    searchArea = "r", // Display subreddits first
    baseURL = "https://www.reddit.com/" + searchArea + "/" + search + ".json", // Main URL for image feed
    currentURL = baseURL, // The current url starts off as the base URL, then changes
    debounceTimer = null, // Debounce the scroll function
    debounceDelay = 100,
    currentContainer,
    output = document.getElementById("output"),
    loadingMessage = document.getElementById("image-loading-message"),
    inputField = document.getElementById("input"),
    inputSearch = document.getElementById("input-search"),
    currentSelector = document.querySelectorAll("select")[0];

/*
* Debounce scroll event.
*/
function scrollLoad (event) {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(testScrollHeight, debounceDelay);
}

/*
* Initiate our Reddit request
*/
function fetchRedditImages () {
    fetch(currentURL).then(function (response) {
        if (response.status === 302 || response.status === 404) {
            loadingMessage.innerHTML = "No Results";
            return;
        }
        var contentType = response.headers.get("content-type");
        if (contentType && contentType.indexOf("application/json") !== -1) {
            response.json().then(function (json) {
                if (json.data.children.length === 0) {
                    loadingMessage.innerHTML = "No Results";
                    return;
                }
                currentURL = baseURL + "?after=" + json.data.after;
                insertImages(json.data);
            });
        }
    }).catch(function () {
        // fetch throws an error if reddit redirects us, subreddit doesn"t exist.
        inputField.value = "";
        loadingMessage.innerHTML = "That subreddit doesn't exist sorry.";
    });
}

/*
* Takes a string and replaces HTML escaped &
*/
function replaceHTMLEscape (string) {
    return string.split("&").join("&");
}

/*
* When the thumbnail loads change it's source to the larger image.
* This will cause a network request to start and the user can view the
* blurry thumbnail until it's done.
*/
function imageLoad (img, large) {
    large = replaceHTMLEscape(large);
    img.src = large;
    img.onload = function() {
        // when the larger version loads, apply the zoom effect
        this.className = "";
        // and enable the overlay click function to container
        this.parentElement.className += " image-zoom";
        this.parentElement.onclick = containerClick;
    };
}

/*
* When our JSON successfully loads parse it and render images on the page.
*/
function insertImages (data) {
    var row, container, image, element, sourceImage;
    var len = data.children.length;
    for (var i = 0; i < len; i++) {
        if (i % 4 === 0) {
            // starting a row
            if (row) output.appendChild(row);
            row = document.createElement("div");
            row.className = "row";
        }

        element = data.children[i];

        // Does this element have preview images?
        if (!element.data.preview) continue;
        var currentImages = element.data.preview.images[0];

        // If the resolutions array is empty just skip the image
        if (currentImages.resolutions.length === 0) continue;
        var currentResolutions = currentImages.resolutions;

        // Work out image aspect, pick something from the middle of the array
        var largeResolution = currentResolutions[Math.floor(currentResolutions.length - 1 / 2)];
        var aspect = largeResolution.width / largeResolution.height;

        // Create the image with thumbnail
        image = new Image();
        var thumbnail = replaceHTMLEscape(currentImages.resolutions[0].url);
        image.src = thumbnail;
        image.className = "image-loading";

        // Set the large image for our overlay
        if (element.data.url.indexOf(".gifv") > 0) {
            // it's an imgur gifv image
            sourceImage = element.data.url.substring(0, element.data.url.length - 1);
        } else {
            // it's something plain, or gyfcat
            sourceImage = replaceHTMLEscape(currentImages.source.url);
        }

        // when it loads change the src to the bigger one
        image.onload = (function (image, largeResolution) {
            return function () {
                imageLoad(image, largeResolution);
            };
        })(image, largeResolution.url);

        // if it fails to load delete the element
        image.onerror = function () {
            this.outerHTML = "";
        }

        // Build the container
        container = document.createElement("div");
        container.className = "image-container";

        // let's our images be tiled
        container.style.flex = aspect;
        container.setAttribute("large-image", sourceImage);
        var titleText = element.data.title;
        image.alt = titleText;
        container.setAttribute("title-text", titleText);
        container.setAttribute("author", element.data.author);
        container.appendChild(image);

        // Add title overlay to image
        var title = document.createElement("p");
        if (titleText.length > 25) {
            titleText = titleText.substring(0, 24) + "...";
        }
        title.innerHTML = titleText;
        title.className = "image-title";

        // add to dom
        container.appendChild(title);
        row.appendChild(container);
    }

    // append last row
    output.appendChild(row);
    loadingMessage.style.display = "none";

    // is this enough to fill the page? Some sneaky recursion to fill it out. NB: fires too soon
    var headerHeight = document.getElementsByTagName("header")[0].clientHeight;
    var outputHeight = output.clientHeight;
    var bannerHeight = document.querySelector("nav").clientHeight;
    if ((headerHeight + outputHeight + bannerHeight) < window.innerHeight) {
        fetchRedditImages();
    } else {
        document.addEventListener("scroll", scrollLoad);
    }
}

/*
* Function to see if we have scrolled far enough down the page.
*/
function testScrollHeight () {
    if (document.body.scrollHeight == document.body.scrollTop + window.innerHeight) {
        document.removeEventListener("scroll", scrollLoad);
        fetchRedditImages();
        loadingMessage.style.display = "block";
    }
}

/*
* When a user clicks on one of the images.
*/
function containerClick () {
    bindArrowKeys();
    // display the overlay with options
    document.getElementById("overlay").style.display = "block";
    currentContainer = this;
    setOverlayContents(this);
    var author = this.getAttribute("author");
    var userButton = document.getElementById("overlay-user");
    userButton.setAttribute("author", author);
    userButton.innerHTML = "By /user/" + author;
    document.body.style.overflow = "hidden"; // don"t let body scroll
}

// bind a thing
function bindArrowKeys () {
    document.addEventListener("keydown", directionPress);
}

// unbind a thing
function unbindArrowKeys () {
    document.removeEventListener("keydown", directionPress);
}

/*
* Setup overlay handler and begin searching.
*/
function beginSearch () {
    // setup overlay dismiss
    try {
        output.innerHTML = "";
        loadingMessage.style.display = "block";
        loadingMessage.innerHTML = "Loading...";
        document.getElementById("overlay").onclick = function() {
            this.style.display = "none";
            // let body scroll again
            document.body.style.overflow = "";
            unbindArrowKeys();
        };
        fetchRedditImages();
    } catch (_) {
        var error = document.createElement("h2");
        error.innerHTML = "Something went super wrong, try refreshing.";
        output.appendChild(error);
    }
}

// they pressed an arrow key maybe
function directionPress (e) {
    var newElement, newRow, sibling, child;
    var key = e.which || e.keyCode;

    // which key?
    if (key === 37) {
        // hit left
        sibling = "previousSibling";
        child = "lastChild";
    } else if (key === 39) {
        // pressed right
        sibling = "nextSibling";
        child = "firstChild";
    } else {
        // exit early if not one of those
        return;
    }

    newElement = currentContainer[sibling];
    if (newElement) {
        // found next element right away
        currentContainer = newElement;
        setOverlayContents(currentContainer);
    } else {
        // we need to go up and into the previous row
        newRow = currentContainer.parentElement[sibling];
        if (newRow) {
            currentContainer = newRow[child];
            setOverlayContents(currentContainer);
        } else {
            // this was the first row and they went back - end forwards
            return;
        }
    }
}

/*
* For the overlay element, extract it's data attributes.
*/
function setOverlayContents (element) {
    document.getElementById("overlay-title").innerHTML = element.getAttribute("title-text");
    document.getElementById("overlay-image").alt = element.getAttribute("title-text");
    document.getElementById("overlay-image").src = element.getAttribute("large-image");
}

/*
* Returns the search URL depending on it we want a user or subreddit.
*/
function createSearchURL (searchArea, sub) {
    var url = "https://www.reddit.com/" + searchArea + "/" + sub;
    if (searchArea === "user") url += "/submitted";
    return url + ".json";
}

/*
* Check the input field after enter is hit or search button clicked.
*/
function checkInputs (ele) {
    var searchAreas = ["r", "user"];

    // set the current search area
    searchArea = searchAreas[currentSelector.selectedIndex];

    // work out the input value
    var sub = ele.value;
    if (searchArea === "user" && sub.indexOf(" ") >= 0) {
        ele.placeholder = "Users can't have spaces.";
        ele.value = "";
        return;
    }
    if (sub.length === 0) {
        ele.placeholder = "Please search for something.";
        return;
    }

    // break up the search into an array of subreddits
    var subReddits = sub.trim().replace(/\s\s+/g, " ").split(" ");

    // assign globals
    search = sub = subReddits.join("+");
    baseURL = currentURL = createSearchURL(searchArea, sub);

    // start search after checks done
    beginSearch();
}

/*
* Apply event listeners.
*/
function bindListeners () {
    inputField.addEventListener("keypress", function (e) {
        this.placeholder = "";
        var key = e.which || e.keyCode;
        if (key === 13) { // listen for enter key
          checkInputs(this);
        }
    });

    inputSearch.addEventListener("submit", function (e) {
        e.preventDefault();
        checkInputs(inputField);
    });

    // out overlays image click
    document.getElementById("overlay-user").addEventListener("click", function (e) {
        document.querySelectorAll("select option")[1].selected = true;
        searchArea = "user";
        search = this.getAttribute("author");
        document.querySelectorAll("input")[0].value = search;
        baseURL = "https://www.reddit.com/" + searchArea + "/" + search + "/submitted.json";
        currentURL = baseURL;
        beginSearch();
    });
}

/*
* Check to see if browser supports fetch.
* If not, polyfill it then start.
*/
(function init () {
    if (window.fetch) {
        bindListeners();
    } else {
        var fetchPoly = document.createElement("script");
        fetchPoly.src = "https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.1/fetch.min.js";
        fetchPoly.onload = bindListeners;
        document.head.appendChild(fetchPoly);
    }
})();
<commit_msg>If we don't get back json something went wrong.<commit_after>"use strict";

/*
* Global variables. Will make this more object based soon.
*/
var search = "aww+puppies", // Keep track of the subreddit we want to scrape for images
    searchArea = "r", // Display subreddits first
    baseURL = "https://www.reddit.com/" + searchArea + "/" + search + ".json", // Main URL for image feed
    currentURL = baseURL, // The current url starts off as the base URL, then changes
    debounceTimer = null, // Debounce the scroll function
    debounceDelay = 100,
    currentContainer,
    output = document.getElementById("output"),
    loadingMessage = document.getElementById("image-loading-message"),
    inputField = document.getElementById("input"),
    inputSearch = document.getElementById("input-search"),
    currentSelector = document.querySelectorAll("select")[0];

/*
* Debounce scroll event.
*/
function scrollLoad (event) {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(testScrollHeight, debounceDelay);
}

/*
* Initiate our Reddit request
*/
function fetchRedditImages () {
    fetch(currentURL).then(function (response) {
        if (response.status === 302 || response.status === 404) {
            loadingMessage.innerHTML = "No Results";
            return;
        }
        var contentType = response.headers.get("content-type");
        if (contentType && contentType.indexOf("application/json") !== -1) {
            response.json().then(function (json) {
                if (json.data.children.length === 0) {
                    loadingMessage.innerHTML = "No Results";
                    return;
                }
                currentURL = baseURL + "?after=" + json.data.after;
                insertImages(json.data);
            });
        } else {
            loadingMessage.innerHTML = "Result looked strange.";
            return;
        }
    }).catch(function () {
        // fetch throws an error if reddit redirects us, subreddit doesn"t exist.
        inputField.value = "";
        loadingMessage.innerHTML = "That subreddit doesn't exist sorry.";
    });
}

/*
* Takes a string and replaces HTML escaped &
*/
function replaceHTMLEscape (string) {
    return string.split("&").join("&");
}

/*
* When the thumbnail loads change it's source to the larger image.
* This will cause a network request to start and the user can view the
* blurry thumbnail until it's done.
*/
function imageLoad (img, large) {
    large = replaceHTMLEscape(large);
    img.src = large;
    img.onload = function() {
        // when the larger version loads, apply the zoom effect
        this.className = "";
        // and enable the overlay click function to container
        this.parentElement.className += " image-zoom";
        this.parentElement.onclick = containerClick;
    };
}

/*
* When our JSON successfully loads parse it and render images on the page.
*/
function insertImages (data) {
    var row, container, image, element, sourceImage;
    var len = data.children.length;
    for (var i = 0; i < len; i++) {
        if (i % 4 === 0) {
            // starting a row
            if (row) output.appendChild(row);
            row = document.createElement("div");
            row.className = "row";
        }

        element = data.children[i];

        // Does this element have preview images?
        if (!element.data.preview) continue;
        var currentImages = element.data.preview.images[0];

        // If the resolutions array is empty just skip the image
        if (currentImages.resolutions.length === 0) continue;
        var currentResolutions = currentImages.resolutions;

        // Work out image aspect, pick something from the middle of the array
        var largeResolution = currentResolutions[Math.floor(currentResolutions.length - 1 / 2)];
        var aspect = largeResolution.width / largeResolution.height;

        // Create the image with thumbnail
        image = new Image();
        var thumbnail = replaceHTMLEscape(currentImages.resolutions[0].url);
        image.src = thumbnail;
        image.className = "image-loading";

        // Set the large image for our overlay
        if (element.data.url.indexOf(".gifv") > 0) {
            // it's an imgur gifv image
            sourceImage = element.data.url.substring(0, element.data.url.length - 1);
        } else {
            // it's something plain, or gyfcat
            sourceImage = replaceHTMLEscape(currentImages.source.url);
        }

        // when it loads change the src to the bigger one
        image.onload = (function (image, largeResolution) {
            return function () {
                imageLoad(image, largeResolution);
            };
        })(image, largeResolution.url);

        // if it fails to load delete the element
        image.onerror = function () {
            this.outerHTML = "";
        }

        // Build the container
        container = document.createElement("div");
        container.className = "image-container";

        // let's our images be tiled
        container.style.flex = aspect;
        container.setAttribute("large-image", sourceImage);
        var titleText = element.data.title;
        image.alt = titleText;
        container.setAttribute("title-text", titleText);
        container.setAttribute("author", element.data.author);
        container.appendChild(image);

        // Add title overlay to image
        var title = document.createElement("p");
        if (titleText.length > 25) {
            titleText = titleText.substring(0, 24) + "...";
        }
        title.innerHTML = titleText;
        title.className = "image-title";

        // add to dom
        container.appendChild(title);
        row.appendChild(container);
    }

    // append last row
    output.appendChild(row);
    loadingMessage.style.display = "none";

    // is this enough to fill the page? Some sneaky recursion to fill it out. NB: fires too soon
    var headerHeight = document.getElementsByTagName("header")[0].clientHeight;
    var outputHeight = output.clientHeight;
    var bannerHeight = document.querySelector("nav").clientHeight;
    if ((headerHeight + outputHeight + bannerHeight) < window.innerHeight) {
        fetchRedditImages();
    } else {
        document.addEventListener("scroll", scrollLoad);
    }
}

/*
* Function to see if we have scrolled far enough down the page.
*/
function testScrollHeight () {
    if (document.body.scrollHeight == document.body.scrollTop + window.innerHeight) {
        document.removeEventListener("scroll", scrollLoad);
        fetchRedditImages();
        loadingMessage.style.display = "block";
    }
}

/*
* When a user clicks on one of the images.
*/
function containerClick () {
    bindArrowKeys();
    // display the overlay with options
    document.getElementById("overlay").style.display = "block";
    currentContainer = this;
    setOverlayContents(this);
    var author = this.getAttribute("author");
    var userButton = document.getElementById("overlay-user");
    userButton.setAttribute("author", author);
    userButton.innerHTML = "By /user/" + author;
    document.body.style.overflow = "hidden"; // don"t let body scroll
}

// bind a thing
function bindArrowKeys () {
    document.addEventListener("keydown", directionPress);
}

// unbind a thing
function unbindArrowKeys () {
    document.removeEventListener("keydown", directionPress);
}

/*
* Setup overlay handler and begin searching.
*/
function beginSearch () {
    // setup overlay dismiss
    try {
        output.innerHTML = "";
        loadingMessage.style.display = "block";
        loadingMessage.innerHTML = "Loading...";
        document.getElementById("overlay").onclick = function() {
            this.style.display = "none";
            // let body scroll again
            document.body.style.overflow = "";
            unbindArrowKeys();
        };
        fetchRedditImages();
    } catch (_) {
        var error = document.createElement("h2");
        error.innerHTML = "Something went super wrong, try refreshing.";
        output.appendChild(error);
    }
}

// they pressed an arrow key maybe
function directionPress (e) {
    var newElement, newRow, sibling, child;
    var key = e.which || e.keyCode;

    // which key?
    if (key === 37) {
        // hit left
        sibling = "previousSibling";
        child = "lastChild";
    } else if (key === 39) {
        // pressed right
        sibling = "nextSibling";
        child = "firstChild";
    } else {
        // exit early if not one of those
        return;
    }

    newElement = currentContainer[sibling];
    if (newElement) {
        // found next element right away
        currentContainer = newElement;
        setOverlayContents(currentContainer);
    } else {
        // we need to go up and into the previous row
        newRow = currentContainer.parentElement[sibling];
        if (newRow) {
            currentContainer = newRow[child];
            setOverlayContents(currentContainer);
        } else {
            // this was the first row and they went back - end forwards
            return;
        }
    }
}

/*
* For the overlay element, extract it's data attributes.
*/
function setOverlayContents (element) {
    document.getElementById("overlay-title").innerHTML = element.getAttribute("title-text");
    document.getElementById("overlay-image").alt = element.getAttribute("title-text");
    document.getElementById("overlay-image").src = element.getAttribute("large-image");
}

/*
* Returns the search URL depending on it we want a user or subreddit.
*/
function createSearchURL (searchArea, sub) {
    var url = "https://www.reddit.com/" + searchArea + "/" + sub;
    if (searchArea === "user") url += "/submitted";
    return url + ".json";
}

/*
* Check the input field after enter is hit or search button clicked.
*/
function checkInputs (ele) {
    var searchAreas = ["r", "user"];

    // set the current search area
    searchArea = searchAreas[currentSelector.selectedIndex];

    // work out the input value
    var sub = ele.value;
    if (searchArea === "user" && sub.indexOf(" ") >= 0) {
        ele.placeholder = "Users can't have spaces.";
        ele.value = "";
        return;
    }
    if (sub.length === 0) {
        ele.placeholder = "Please search for something.";
        return;
    }

    // break up the search into an array of subreddits
    var subReddits = sub.trim().replace(/\s\s+/g, " ").split(" ");

    // assign globals
    search = sub = subReddits.join("+");
    baseURL = currentURL = createSearchURL(searchArea, sub);

    // start search after checks done
    beginSearch();
}

/*
* Apply event listeners.
*/
function bindListeners () {
    inputField.addEventListener("keypress", function (e) {
        this.placeholder = "";
        var key = e.which || e.keyCode;
        if (key === 13) { // listen for enter key
          checkInputs(this);
        }
    });

    inputSearch.addEventListener("submit", function (e) {
        e.preventDefault();
        checkInputs(inputField);
    });

    // out overlays image click
    document.getElementById("overlay-user").addEventListener("click", function (e) {
        document.querySelectorAll("select option")[1].selected = true;
        searchArea = "user";
        search = this.getAttribute("author");
        document.querySelectorAll("input")[0].value = search;
        baseURL = "https://www.reddit.com/" + searchArea + "/" + search + "/submitted.json";
        currentURL = baseURL;
        beginSearch();
    });
}

/*
* Check to see if browser supports fetch.
* If not, polyfill it then start.
*/
(function init () {
    if (window.fetch) {
        bindListeners();
    } else {
        var fetchPoly = document.createElement("script");
        fetchPoly.src = "https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.1/fetch.min.js";
        fetchPoly.onload = bindListeners;
        document.head.appendChild(fetchPoly);
    }
})();
<|endoftext|>


<commit_before>import LCARS from 'lcars';
import Immutable from 'immutable';
import {EventEmitter} from 'events';
import {Component} from 'react';
const CHANGE_EVENT = 'change';

class WelpComponent extends Component {

  constructor(props, stores) {
    super(props);
    this.stores = stores;
    this.handleStoresChanged = this.handleStoresChanged.bind(this);
    this.getStateFromStores = this.getStateFromStores.bind(this);
    this.state = this.getStateFromStores();
  }

  componentDidMount() {
    this.mounted = true;
    if (!this.stores) {
      throw new Error('You must have a stores array property');
    }
    if (!this.getStateFromStores) {
      throw new Error('You must implement this.getStateFromStores');
    }
    this.stores.forEach(store => {
      store.addChangeListener(this.handleStoresChanged);
    }, this);
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !Immutable.is(this.props, nextProps) || !Immutable.is(this.state, nextState);
  }

  componentWillUnmount() {
    this.mounted = false;
    this.stores.forEach(store => {
      store.removeChangeListener(this.handleStoresChanged);
    }, this);
  }

  getStateFromStores() {
    if (this.stores.length > 1) {
      return this.stores.reduce((a, b) => a.getDataStructure().merge(b.getDataStructure())).toJS();
    }
    return this.stores[0].getDataStructure().toJS();
  }

  handleStoresChanged() {
    if (this.mounted) {
      return this.setState(this.getStateFromStores());
    }
  }

}

class WelpStore extends EventEmitter {
  constructor(store_data, callback) {
    super();
    if (process.env.NODE_ENV !== 'production') {
      const store_data_type = Object.prototype.toString.call(store_data);
      if (store_data_type !== '[object Object]') {
        throw new Error('Base Store: The first argument must be type object');
      }
      if (typeof callback !== 'function') {
        throw new Error('Base Store: The second argument must be type function');
      }
    }
    this._data = Immutable.fromJS(store_data);
    this.dispatchToken = LCARS.register((action) => {
      callback(action);
    });
  }
  _check_data (current, next) {
    if (current !== next) {
      this._data = next;
      this.emit(CHANGE_EVENT);
    }
    return this._data;
  }
  get(key) {
    return this._data.get(key);
  }
  getStateData() {
    return this._data.toJS();
  }
  set(key, value) {
    return this._check_data(this._data, this._data.set(key, value));
  }
  updateIn(key_path, value) {
    return this._check_data(this._data, this._data.updateIn(key_path, value));
  }
  getDataStructure() {
    return this._data;
  }
  emitChange() {
    this.emit(CHANGE_EVENT);
  }
  addChangeListener(callback) {
    this.on(CHANGE_EVENT, callback);
  }
  removeChangeListener(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
  delete(key) {
    return this._check_data(this._data, this._data.delete(key));
  }
  clear() {
    return this._check_data(this._data, this._data.clear());
  }
  merge(...maps){
    return this._check_data(this._data, this._data.merge(...maps));
  }
}

export {
  WelpComponent,
  WelpStore
};
<commit_msg>linting<commit_after>import LCARS from 'lcars';
import Immutable from 'immutable';
import {EventEmitter} from 'events';
import {Component} from 'react';
const CHANGE_EVENT = 'change';

class WelpComponent extends Component {

  constructor(props, stores) {
    super(props);
    this.stores = stores;
    this.handleStoresChanged = this.handleStoresChanged.bind(this);
    this.getStateFromStores = this.getStateFromStores.bind(this);
    this.state = this.getStateFromStores();
  }

  componentDidMount() {
    this.mounted = true;
    if (!this.stores) {
      throw new Error('You must have a stores array property');
    }
    if (!this.getStateFromStores) {
      throw new Error('You must implement this.getStateFromStores');
    }
    this.stores.forEach(store => {
      store.addChangeListener(this.handleStoresChanged);
    }, this);
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !Immutable.is(this.props, nextProps) || !Immutable.is(this.state, nextState);
  }

  componentWillUnmount() {
    this.mounted = false;
    this.stores.forEach(store => {
      store.removeChangeListener(this.handleStoresChanged);
    }, this);
  }

  getStateFromStores() {
    if (this.stores.length > 1) {
      return this.stores.reduce((a, b) => a.getDataStructure().merge(b.getDataStructure())).toJS();
    }
    return this.stores[0].getDataStructure().toJS();
  }

  handleStoresChanged() {
    if (this.mounted) {
      return this.setState(this.getStateFromStores());
    }
  }

}

class WelpStore extends EventEmitter {
  constructor(store_data, callback) {
    super();
    if (process.env.NODE_ENV !== 'production') {
      const store_data_type = Object.prototype.toString.call(store_data);
      if (store_data_type !== '[object Object]') {
        throw new Error('Base Store: The first argument must be type object');
      }
      if (typeof callback !== 'function') {
        throw new Error('Base Store: The second argument must be type function');
      }
    }
    this._data = Immutable.fromJS(store_data);
    this.dispatchToken = LCARS.register((action) => {
      callback(action);
    });
  }
  _check_data(current, next) {
    if (current !== next) {
      this._data = next;
      this.emit(CHANGE_EVENT);
    }
    return this._data;
  }
  get(key) {
    return this._data.get(key);
  }
  getStateData() {
    return this._data.toJS();
  }
  set(key, value) {
    return this._check_data(this._data, this._data.set(key, value));
  }
  updateIn(key_path, value) {
    return this._check_data(this._data, this._data.updateIn(key_path, value));
  }
  getDataStructure() {
    return this._data;
  }
  emitChange() {
    this.emit(CHANGE_EVENT);
  }
  addChangeListener(callback) {
    this.on(CHANGE_EVENT, callback);
  }
  removeChangeListener(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
  delete(key) {
    return this._check_data(this._data, this._data.delete(key));
  }
  clear() {
    return this._check_data(this._data, this._data.clear());
  }
  merge(...maps){
    return this._check_data(this._data, this._data.merge(...maps));
  }
}

export {
  WelpComponent,
  WelpStore
};
<|endoftext|>


<commit_before>
'use strict';

const koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/articles');
const app = koa();

import { User } from './models';

app.use(bodyParser());

router.get('/', function *(next) {
  this.body = 'ohcE';
});

router.use(function *(next) {
  if (!this.request.headers.alias) {
    yield next;
    return;
  }
  const me = yield User.findOne({ 'alias': this.request.headers.alias }).exec();
  if (me) {
    this.user = me;
  }
  yield next;
});

router.get('/me', function *(next) {
  this.body = this.user;
});

router.post('/me', function *(next) {
  const reqAlias = this.request.headers.alias;
  if (!reqAlias || /^\s*$/.exec(reqAlias)) {
    this.throw(`need a valid alias: "${reqAlias}"`, 400);
  }
  if (!this.user) {
    this.user = new User({
      alias: reqAlias,
    });
    yield this.user.save();
    this.status = 201;
  }
  this.body = this.user;
});

app.use(router.routes());

const server = app.listen(8000, () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log(`"Articles" listening at http://${host}:${port}`);
});
<commit_msg>api nits<commit_after>
'use strict';

const koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/articles');
const app = koa();

import { User } from './models';

app.use(bodyParser());

router.use(function *(next) {
  if (!this.request.headers.alias) {
    yield next;
    return;
  }
  const me = yield User.findOne({ 'alias': this.request.headers.alias }).exec();
  if (me) {
    this.user = me;
  }
  yield next;
});

router.get('/', function *(next) {
  this.body = 'ohcE';
});

router.get('/me', function *(next) {
  this.body = this.user;
});

router.post('/me', function *(next) {
  const reqAlias = this.request.headers.alias;
  if (!reqAlias || /^\s*$/.exec(reqAlias)) {
    this.throw(`need a valid alias: "${reqAlias}"`, 400);
  }
  if (!this.user) {
    this.user = new User({
      alias: reqAlias,
    });
    yield this.user.save();
    this.status = 201;
  }
  this.body = this.user;
});

app.use(router.routes());

const server = app.listen(8000, () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log(`"ArticlesAPI" listening at http://${host}:${port}`);
});
<|endoftext|>


<commit_before>var container, left_div, right_div;
var scale = 1;
var image_width;
var image_left, image_top, image_right, image_bottom;

function init() {
	container = document.getElementById("content");
	left_div = container.getElementsByClassName("left")[0];
	right_div = container.getElementsByClassName("right")[0];
	left_div.addEventListener( 'click', onViewClick, false );
	left_div.addEventListener( 'wheel', onViewWheel, false );
	right_div.addEventListener( 'click', onViewClick, false );
	right_div.addEventListener( 'wheel', onViewWheel, false );
	loadImage();
}

function loadImage() {
	img = new Image();
	img.src = "images/Art_Institute_of_Chicago_Lion_Statue.jpg";
	img.addEventListener( 'load', onImageLoad, false );
}

function onImageLoad(event) {
	var img_aspect = img.width / img.height;
	var cont_width = container.getBoundingClientRect().width;
	var cont_height = cont_width / img_aspect;
	var right_width = right_div.getBoundingClientRect().width;
	image_width = right_width * 2.0;
	container.style.height = cont_height.toString() + "px";
	left_div.style.backgroundImage = "url(" + img.src + ")";
	right_div.style.backgroundImage = "url(" + img.src + ")";
	right_div.style.backgroundSize = image_width.toString() + "px auto";
	left_div.style.backgroundSize = image_width.toString() + "px auto";
	right_div.style.backgroundPosition = (cont_width / -2.0).toString() + "px 0";

	image_left = 0;
	image_top = 0;
	image_right = image_width;
}

function onViewClick(event) {
	var local_rect = event.target.getBoundingClientRect();
	var click_x = event.clientX - local_rect.x;
	var click_y = event.clientY - local_rect.y;
}

function onViewWheel(evt) {
	console.log(evt.deltaY);
	var target_rect = evt.target.getBoundingClientRect();
	var target_width = target_rect.width;
	var click_x = evt.clientX - target_rect.left;
	var click_y = evt.clientY - target_rect.top;

  var scale = (evt.deltaY > 0) ? 1.05 : .95;

	image_left = ((image_left - click_x) * scale) + click_x;
	image_top = ((image_top - click_y) * scale) + click_y;
	image_right = ((image_right - click_x) * scale) + click_x;
	if (image_left > 0) image_left = 0;
	if (image_top > 0) image_top = 0;
	if (image_right < (target_width * 2)) image_right = (target_width * 2);

	console.log(scale);
	displayImage(target_width);

	evt.preventDefault();
}

function displayImage(div_width) {
	var image_width = (image_right - image_left);
	right_div.style.backgroundSize = left_div.style.backgroundSize = image_width.toString() + "px auto";
	left_div.style.backgroundPosition = image_left.toString() + "px " + image_top.toString() + "px";
	right_div.style.backgroundPosition = (image_left - (image_width/2)).toString() + "px " + image_top.toString() + "px";
}
<commit_msg>dragging works<commit_after>var container, left_div, right_div;
var scale = 1;
var image_width;
var image_left, image_top, image_right, image_bottom;

function init() {
	container = document.getElementById("content");
	left_div = container.getElementsByClassName("left")[0];
	right_div = container.getElementsByClassName("right")[0];
	// left_div.addEventListener( 'click', onViewClick, false );
	left_div.addEventListener( 'wheel', onViewWheel, false );
	// left_div.addEventListener( 'mousemove', onMouseMove, false );
	left_div.addEventListener("dragstart", function() { console.log(event.button);return false; }, false );
	left_div.addEventListener("mousedown", onMouseDown, false );
	// right_div.addEventListener( 'click', onViewClick, false );
	right_div.addEventListener( 'wheel', onViewWheel, false );
	loadImage();
}

function loadImage() {
	img = new Image();
	img.src = "images/Art_Institute_of_Chicago_Lion_Statue.jpg";
	img.addEventListener( 'load', onImageLoad, false );
}

function onImageLoad(event) {
	var img_aspect = img.width / img.height;
	var cont_width = container.getBoundingClientRect().width;
	var cont_height = cont_width / img_aspect;
	var right_width = right_div.getBoundingClientRect().width;
	image_width = right_width * 2.0;
	container.style.height = cont_height.toString() + "px";
	left_div.style.backgroundImage = "url(" + img.src + ")";
	right_div.style.backgroundImage = "url(" + img.src + ")";
	right_div.style.backgroundSize = image_width.toString() + "px auto";
	left_div.style.backgroundSize = image_width.toString() + "px auto";
	right_div.style.backgroundPosition = (cont_width / -2.0).toString() + "px 0";

	image_left = 0;
	image_top = 0;
	image_right = image_width;
}

function onViewClick(event) {
	console.log(event.button);
	var local_rect = event.target.getBoundingClientRect();
	var click_x = event.clientX - local_rect.left;
	var click_y = event.clientY - local_rect.top;
}

var start_x, start_y;
function onMouseMove(event) {
	console.log(event);
	var local_rect = event.target.getBoundingClientRect();
	var click_x = event.clientX - local_rect.left;
	var click_y = event.clientY - local_rect.top;
	var dist_x = click_x - start_x;
	var dist_y = click_y - start_y;
	start_x = click_x;
	start_y = click_y;
	console.log(dist_x);
	image_left = image_left + dist_x;
	image_top = image_top + dist_y;
	displayImage();
}

function onMouseUp(event) {
	console.log(event);
	event.target.removeEventListener( 'mousemove', onMouseMove );
	event.target.removeEventListener( 'mouseup', onMouseUp );
}

function onMouseDown(event) {
	console.log(event);
	var local_rect = event.target.getBoundingClientRect();
	start_x = event.clientX - local_rect.left;
	start_y = event.clientY - local_rect.top;
	if (event.buttons == 1) {
		event.target.addEventListener( 'mousemove', onMouseMove, false );
		event.target.addEventListener( 'mouseup', onMouseUp, false );
	}
}

function onViewWheel(evt) {
	// console.log(evt.deltaY);
	var target_rect = evt.target.getBoundingClientRect();
	var target_width = target_rect.width;
	var click_x = evt.clientX - target_rect.left;
	var click_y = evt.clientY - target_rect.top;

  var scale = (evt.deltaY > 0) ? 1.05 : .95;

	image_left = ((image_left - click_x) * scale) + click_x;
	image_top = ((image_top - click_y) * scale) + click_y;
	image_right = ((image_right - click_x) * scale) + click_x;
	if (image_left > 0) image_left = 0;
	if (image_top > 0) image_top = 0;
	if (image_right < (target_width * 2)) image_right = (target_width * 2);

	// console.log(scale);
	displayImage();

	evt.preventDefault();
}

function displayImage() {
	var image_width = (image_right - image_left);
	right_div.style.backgroundSize = left_div.style.backgroundSize = image_width.toString() + "px auto";
	left_div.style.backgroundPosition = image_left.toString() + "px " + image_top.toString() + "px";
	right_div.style.backgroundPosition = (image_left - (image_width/2)).toString() + "px " + image_top.toString() + "px";
}
<|endoftext|>


<commit_before>/* global app:true, io:false */

var socket;
var myname;
var block_id;
var pattern_array = [];
var pattern_string;

(function() {
  'use strict';

  /*socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/replay/#join');
  });

  socket.on('message', function (message) {
      console.log(message);
  });

  socket.on('disconnect', function() {
      console.log('>>> DB disconnected');
  });*/

  app = app || {};

  app.Reset = Backbone.Model.extend({
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      blockid: undefined,
      confitm: ''
    },
    url: function(){
      return '/account/pattern/' + this.get('block_id') +'/';
    }
  });

  app.PatternView = Backbone.View.extend({
    el: '#pattern_menu',
    template: _.template( $('#tmpl-pattern_menu').html() ),
    events: {
      'click .btn-check': 'reqCheck',
      'click .btn-edit': 'reqEdit',
      'click .btn-submit': 'reqSubmit'
    },
    initialize: function() {
      //this.model = new app.Blocks();
      //this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template);
    },
    reqCheck: function() {
      document.getElementById("btn_check").disabled = true;
      document.getElementById("btn_submit").disabled = false;
      document.getElementById("btn_edit").disabled = false;
      document.getElementById("pattern_input").disabled = true;
      var input = document.getElementById("pattern_input").value.split(/\n/);
      input = cleanArray(input);

      input.forEach(function(line){
	    var res = line.split(",");
	    var pattern = new Object();
	    pattern.id = res[0];
	    pattern.msec = res[1];
	    pattern.led = res[2];
	    pattern_array.push(pattern);
      });
      console.log(pattern_array);

      pattern_string = input.join("&&");
      console.log(pattern_string);

      drawVis(pattern_array);
    },
    reqEdit: function() {
      document.getElementById("btn_check").disabled = false;
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      document.getElementById("pattern_input").disabled = false;
    },
    reqSubmit: function() {
      document.getElementById("btn_check").disabled = true;
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      console.log("Submit");
    }
  });

  app.Router = Backbone.Router.extend({
    routes: {
      'account/pattern/': 'default',
      'account/pattern/load/:block/': 'load'
    },
    default: function(){
      console.log(" >>default view, nothing loaded");
    },
    load: function(block) {
      console.log(">> loading block "+block);
      block_id = block;
      var info_div = document.getElementById("info_box");
      var info_text = document.createElement("h6");
      var block_node = document.createTextNode("Pattern for [ block # "+block_id+" ]");
      var pattern_node = document.createTextNode(" -  [ pattern # "+" ]");
	info_text.appendChild(block_node);
	info_text.appendChild(pattern_node);
	info_div.appendChild(info_text);
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      //socket.emit('/replay/#callblock', { targetBlock: block});
      setupVis();
    }
  });

  $(document).ready(function() {
    app.patternView = new app.PatternView();
    app.router = new app.Router();
    Backbone.history.start({ pushState: true });
  });
}());

function cleanArray(actual){
  var newArray = new Array();
  for(var i = 0; i<actual.length; i++){
      if (actual[i].length > 0){
        newArray.push(actual[i]);
    }
  }
  return newArray;
}

/////////////////////////////
// Canvas setup functions
/////////////////////////////

var svg_vis;
var margin = {top: 20, right: 20, bottom: 30, left: 60},
	width = 600 - margin.left - margin.right,
	height = 3600 - margin.top - margin.bottom;

function setupVis(){
    d3.select("#pattern_vis").selectAll("svg")
	.remove();

    svg_vis = d3.select("#pattern_vis").append("svg")
	.attr("width", width + margin.left + margin.right)
	.attr("height", height + margin.top + margin.bottom)
     .append("g")
	.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
}

function drawVis(data){
    var format = d3.time.format("%M:%S");
    var y = d3.time.scale()
	.domain([d3.time.minute.offset(new Date(0), 5), new Date(0)])
	.range([height, 0]);

    var color = d3.scale.category10();

    var yAxis = d3.svg.axis()
	.scale(y)
	.orient("left")
	.ticks(d3.time.seconds, 5)
	.tickFormat(format);

    svg_vis.append("g")
      .attr("class", "y axis")
      .call(yAxis);

    var plot = svg_vis.selectAll('.plot')
	  .data(data)
      .enter().append('rect')
	  .attr('class', 'spot')
	  .attr('x', function(d){
	      //console.log(d.msec-Math.floor(d.msec/5000)*5000);
	      return (d.msec-Math.floor(d.msec/1000)*1000)/2
	  })
	  .attr('y', function(d){
	      //console.log(y(d3.time.second.offset(new Date(0), Math.floor(d.msec/1000))));
	      return  y(d3.time.second.offset(new Date(0), Math.floor(d.msec/1000)))+1
	  })
	  .attr('width', 10)
	  .attr('height', 48);
      plot.append('text')
	  .attr('class', 'arrow')
	  .attr('font-family', 'FontAwesome')
	      .style('font-size', '100%' )
	      .attr("x",0)
	      .attr("y",0)
	      .text(function(d) { return '\uf023' });
	      //.style("display", function(d) {
	          //return d.lock == true ? null : "none";
	      //});

    svg_vis.append("g")
        .attr("class", "grid")
        .attr("transform", "translate(1,0)")
        .call(make_y_axis()
            .tickSize(-width, 0, 0)
            .tickFormat("")
        )

    function make_y_axis() {
	return d3.svg.axis()
	    .scale(y)
	    .orient("left")
	    .ticks(250)
    }
}

 /*   var frame = svg_data_vis.selectAll(".frame")
	    .data(d3data)
    .enter().append("g")
	    .attr("class", "block")
	    .attr("transform", function (d,i)
	    {
		    var dx = (i+1)%100*datavis_x_gap;
		    var dy = 20 + Math.floor((i+1)/100)*datavis_y_gap;
		    return "translate(" + dx + ","+ dy + ")";
	    });
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide);

    frame.append("rect")
	    .attr("class", function (d,i)
	    {
		    var class_name;
		    if(i==current_frame){
		      class_name="current-frame";
		    }
		    else{
		      if (d.ledarray.length>0){
			    class_name="frame-with-led";
		      }else{
			    class_name="frame-no-led";
		      }

		    }
		    return class_name;
	    })
	    .attr("width", 8)
	    .attr("height", 8);*/
	    /*.attr("led", function (d){
		    if (d.ledarray.length>0){
			    return true;
		    }else{
			    return false
		    }
	    });*/
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide)
	    //.on('click', mouseclick);
    /*frame.append("line")
	    .attr("class", function (d,i)
	    {
		    var class_name = "stroke-led";
		    return class_name;
	    })
	    .attr("x1", 4)
	    .attr("y1", 4)
	    .attr("x2", function (d){
	      if (d.ledarray.length>0) {
		var x2=0;

		d.ledarray.forEach(function(ele){
		  x2 = x2 + parseFloat(ele.arrow[1])*8 - parseFloat(ele.arrow[3])*8;
		});

		return 4 + x2/(d.ledarray.length)
	      }else{
		return 4
	      }
	    })
	    .attr("y2",function (d){
	      if (d.ledarray.length>0) {
		var y2=0;

		d.ledarray.forEach(function(ele){
		  y2 = y2 + parseFloat(ele.arrow[0])*8 - parseFloat(ele.arrow[2])*8;
		});

		return 4 + y2/(d.ledarray.length)
	      }else{
		return 4
	      }

	      return 4
	    });
	    */<commit_msg>pattern vis grid<commit_after>/* global app:true, io:false */

var socket;
var myname;
var block_id;
var pattern_array = [];
var pattern_string;

(function() {
  'use strict';

  /*socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/replay/#join');
  });

  socket.on('message', function (message) {
      console.log(message);
  });

  socket.on('disconnect', function() {
      console.log('>>> DB disconnected');
  });*/

  app = app || {};

  app.Reset = Backbone.Model.extend({
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      blockid: undefined,
      confitm: ''
    },
    url: function(){
      return '/account/pattern/' + this.get('block_id') +'/';
    }
  });

  app.PatternView = Backbone.View.extend({
    el: '#pattern_menu',
    template: _.template( $('#tmpl-pattern_menu').html() ),
    events: {
      'click .btn-check': 'reqCheck',
      'click .btn-edit': 'reqEdit',
      'click .btn-submit': 'reqSubmit'
    },
    initialize: function() {
      //this.model = new app.Blocks();
      //this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template);
    },
    reqCheck: function() {
      document.getElementById("btn_check").disabled = true;
      document.getElementById("btn_submit").disabled = false;
      document.getElementById("btn_edit").disabled = false;
      document.getElementById("pattern_input").disabled = true;
      var input = document.getElementById("pattern_input").value.split(/\n/);
      input = cleanArray(input);

      input.forEach(function(line){
	    var res = line.split(",");
	    var pattern = new Object();
	    pattern.id = res[0];
	    pattern.msec = res[1];
	    pattern.led = res[2];
	    pattern_array.push(pattern);
      });
      console.log(pattern_array);

      pattern_string = input.join("&&");
      console.log(pattern_string);

      drawVis(pattern_array);
    },
    reqEdit: function() {
      document.getElementById("btn_check").disabled = false;
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      document.getElementById("pattern_input").disabled = false;
    },
    reqSubmit: function() {
      document.getElementById("btn_check").disabled = true;
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      console.log("Submit");
    }
  });

  app.Router = Backbone.Router.extend({
    routes: {
      'account/pattern/': 'default',
      'account/pattern/load/:block/': 'load'
    },
    default: function(){
      console.log(" >>default view, nothing loaded");
    },
    load: function(block) {
      console.log(">> loading block "+block);
      block_id = block;
      var info_div = document.getElementById("info_box");
      var info_text = document.createElement("h6");
      var block_node = document.createTextNode("Pattern for [ block # "+block_id+" ]");
      var pattern_node = document.createTextNode(" -  [ pattern # "+" ]");
	info_text.appendChild(block_node);
	info_text.appendChild(pattern_node);
	info_div.appendChild(info_text);
      document.getElementById("btn_submit").disabled = true;
      document.getElementById("btn_edit").disabled = true;
      //socket.emit('/replay/#callblock', { targetBlock: block});
      setupVis();
    }
  });

  $(document).ready(function() {
    app.patternView = new app.PatternView();
    app.router = new app.Router();
    Backbone.history.start({ pushState: true });
  });
}());

function cleanArray(actual){
  var newArray = new Array();
  for(var i = 0; i<actual.length; i++){
      if (actual[i].length > 0){
        newArray.push(actual[i]);
    }
  }
  return newArray;
}

/////////////////////////////
// Canvas setup functions
/////////////////////////////

var svg_vis;
var margin = {top: 20, right: 20, bottom: 30, left: 60},
	width = 600 - margin.left - margin.right,
	height = 3600 - margin.top - margin.bottom;

function setupVis(){
    d3.select("#pattern_vis").selectAll("svg")
	.remove();

    svg_vis = d3.select("#pattern_vis").append("svg")
	.attr("width", width + margin.left + margin.right)
	.attr("height", height + margin.top + margin.bottom)
     .append("g")
	.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
}

function drawVis(data){
    var format = d3.time.format("%M:%S");
    var y = d3.time.scale()
	.domain([d3.time.minute.offset(new Date(0), 5), new Date(0)])
	.range([height, 0]);

    var color = d3.scale.category10();

    var yAxis = d3.svg.axis()
	.scale(y)
	.orient("left")
	.ticks(d3.time.seconds, 5)
	.tickFormat(format);

    svg_vis.append("g")
      .attr("class", "y axis")
      .call(yAxis);

    var plot = svg_vis.selectAll('.plot')
	  .data(data)
      .enter().append('rect')
	  .attr('class', 'spot')
	  .attr('x', function(d){
	      //console.log(d.msec-Math.floor(d.msec/5000)*5000);
	      return (d.msec-Math.floor(d.msec/1000)*1000)/2
	  })
	  .attr('y', function(d){
	      //console.log(y(d3.time.second.offset(new Date(0), Math.floor(d.msec/1000))));
	      return  y(d3.time.second.offset(new Date(0), Math.floor(d.msec/1000)))+1
	  })
	  .attr('width', 48)
	  .attr('height', 10);
      plot.append('text')
	  .attr('class', 'arrow')
	  .attr('font-family', 'FontAwesome')
	      .style('font-size', '100%' )
	      .attr("x",0)
	      .attr("y",0)
	      .text(function(d) { return '\uf023' });
	      //.style("display", function(d) {
	          //return d.lock == true ? null : "none";
	      //});

    svg_vis.append("g")
        .attr("class", "grid")
        .attr("transform", "translate(1,0)")
        .call(make_y_axis()
            .tickSize(-width, 0, 0)
            .tickFormat("")
        )

    function make_y_axis() {
	return d3.svg.axis()
	    .scale(y)
	    .orient("left")
	    .ticks(250)
    }
}

 /*   var frame = svg_data_vis.selectAll(".frame")
	    .data(d3data)
    .enter().append("g")
	    .attr("class", "block")
	    .attr("transform", function (d,i)
	    {
		    var dx = (i+1)%100*datavis_x_gap;
		    var dy = 20 + Math.floor((i+1)/100)*datavis_y_gap;
		    return "translate(" + dx + ","+ dy + ")";
	    });
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide);

    frame.append("rect")
	    .attr("class", function (d,i)
	    {
		    var class_name;
		    if(i==current_frame){
		      class_name="current-frame";
		    }
		    else{
		      if (d.ledarray.length>0){
			    class_name="frame-with-led";
		      }else{
			    class_name="frame-no-led";
		      }

		    }
		    return class_name;
	    })
	    .attr("width", 8)
	    .attr("height", 8);*/
	    /*.attr("led", function (d){
		    if (d.ledarray.length>0){
			    return true;
		    }else{
			    return false
		    }
	    });*/
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide)
	    //.on('click', mouseclick);
    /*frame.append("line")
	    .attr("class", function (d,i)
	    {
		    var class_name = "stroke-led";
		    return class_name;
	    })
	    .attr("x1", 4)
	    .attr("y1", 4)
	    .attr("x2", function (d){
	      if (d.ledarray.length>0) {
		var x2=0;

		d.ledarray.forEach(function(ele){
		  x2 = x2 + parseFloat(ele.arrow[1])*8 - parseFloat(ele.arrow[3])*8;
		});

		return 4 + x2/(d.ledarray.length)
	      }else{
		return 4
	      }
	    })
	    .attr("y2",function (d){
	      if (d.ledarray.length>0) {
		var y2=0;

		d.ledarray.forEach(function(ele){
		  y2 = y2 + parseFloat(ele.arrow[0])*8 - parseFloat(ele.arrow[2])*8;
		});

		return 4 + y2/(d.ledarray.length)
	      }else{
		return 4
	      }

	      return 4
	    });
	    */<|endoftext|>