<commit_before>'use strict';
import Promise from "native-promise-only";
import FormioForm from './formio.form';
import Formio from './formio';
import FormioUtils from './utils';
import each from 'lodash/each';
import clone from 'lodash/clone';
export class FormioWizard extends FormioForm {
  constructor(element, options) {
    super(element, options);
    this.wizard = null;
    this.pages = [];
    this.globalComponents = [];
    this.page = 0;
    this.history = [];
    this._nextPage = 0;
  }

  setPage(num) {
    if (!this.wizard.full && num >= 0 && num < this.pages.length) {
      this.page = num;
      return super.setForm(this.currentPage());
    }
    else if (this.wizard.full) {
      return super.setForm(this.getWizard());
    }
    return Promise.reject('Page not found');
  }

  getNextPage(data, currentPage) {
    let form = this.pages[currentPage];
    // Check conditional nextPage
    if (form) {
      let page = ++currentPage;
      if (form.nextPage) {
        // Allow for script execution.
        if (typeof form.nextPage === 'string') {
          try {
            let next = page;
            eval('(function(data) {' + form.nextPage.toString() + '})(data)');
            page = next;
            if (!isNaN(parseInt(page, 10)) && isFinite(page)) {
              return page;
            }
            if (typeof page !== 'string') {
              return page;
            }

            // Assume they passed back the key of the page to go to.
            return this.getPageIndexByKey(page);
          }
          catch (e) {
            console.warn('An error occurred in a custom nextPage function statement for component ' + form.key, e);
            return page;
          }
        }
        // Or use JSON Logic.
        else {
          let result = FormioUtils.jsonLogic.apply(form.nextPage, {
            data: data,
            page: page,
            form: form
          });
          let newPage = parseInt(result, 10);
          if (!isNaN(parseInt(newPage, 10)) && isFinite(newPage)) {
            return newPage;
          }

          return this.getPageIndexByKey(result);
        }
      }

      return page;
    }

    return null;
  }

  getPreviousPage() {
    let prev = this.history.pop();
    if(typeof prev !== 'undefined') {
      return prev;
    }

    return this.page - 1;
  }

  nextPage() {
    // Validate the form builed, before go to the next page
    if (this.checkValidity(this.submission.data, true)) {
      this.checkData(this.submission.data, {
        noValidate: true
      });
      return this.beforeNext().then(() => {
        this.history.push(this.page);
        return this.setPage(this.getNextPage(this.submission.data, this.page)).then(() => {
          this._nextPage = this.getNextPage(this.submission.data, this.page);
          this.emit('nextPage', {page: this.page, submission: this.submission});
        });
      });
    }
    else {
      return Promise.reject(this.showErrors());
    }
  }

  prevPage() {
    let prevPage = this.getPreviousPage();
    return this.setPage(prevPage).then(() => {
      this.emit('prevPage', {page: this.page, submission: this.submission});
    });
  }

  cancel() {
    super.cancel();
    this.history = [];
    return this.setPage(0);
  }

  getPageIndexByKey(key) {
    let pageIndex = 0;
    each(this.pages, (_page, index) => {
      if (_page.key === key) {
        pageIndex = index;
        return false;
      }
    });
    return pageIndex;
  }

  addGlobalComponents(page) {
    // If there are non-page components, then add them here. This is helpful to allow for hidden fields that
    // can propogate between pages.
    if (this.globalComponents.length) {
      page.components = this.globalComponents.concat(page.components);
    }
    return page;
  }

  getPage(pageNum) {
    if ((pageNum >= 0) && (pageNum < this.pages.length)) {
      return this.addGlobalComponents(this.pages[pageNum]);
    }
    return null;
  }

  getWizard() {
    let pageIndex = 0;
    let page = null;
    let wizard = clone(this.wizard);
    wizard.components = [];
    do {
      page = this.getPage(pageIndex);
      if (page) {
        wizard.components.push(page);
      }
    } while (pageIndex = this.getNextPage(this.submission.data, pageIndex));

    // Add all other components.
    each(this.wizard.components, (component) => {
      if (component.type !== 'panel') {
        wizard.components.push(component);
      }
    });

    return wizard;
  }

  currentPage() {
    return this.getPage(this.page);
  }

  buildPages(form) {
    this.pages = [];
    each(form.components, (component) => {
      if (component.type === 'panel') {
        // Ensure that this page can be seen.
        if (FormioUtils.checkCondition(component, this.data, this.data)) {
          this.pages.push(component);
        }
      }
      else if (component.type === 'hidden') {
        // Global components are hidden components that can propagate between pages.
        this.globalComponents.push(component);
      }
    });
    this.buildWizardHeader();
    this.buildWizardNav();
  }

  setForm(form) {
    if (!form) {
      return;
    }
    this.wizard = form;
    this.buildPages(this.wizard);
    return this.setPage(this.page);
  }

  build() {
    super.build();
    this.formReady.then(() => {
      this.buildWizardHeader();
      this.buildWizardNav();
    });
  }

  hasButton(name, nextPage) {
    if (name === 'previous') {
      return (this.page > 0);
    }
    nextPage = (nextPage === undefined) ? this.getNextPage(this.submission.data, this.page) : nextPage;
    if (name === 'next') {
      return (nextPage !== null) && (nextPage < this.pages.length);
    }
    if (name === 'submit') {
      return (nextPage === null) || (this.page === (this.pages.length - 1));
    }
    return true;
  }

  buildWizardHeader() {
    if (this.wizardHeader) {
      this.wizardHeader.innerHTML = '';
    }

    let currentPage = this.currentPage();
    if (!currentPage || this.wizard.full) {
      return;
    }

    currentPage.breadcrumb = currentPage.breadcrumb || 'default';
    if (currentPage.breadcrumb.toLowerCase() === 'none') {
      return;
    }

    // Check for and initlize breadcrumb settings object
    this.options.breadcrumbSettings = this.options.breadcrumbSettings || {};
    if(this.options.breadcrumbSettings.clickable === undefined) {
      this.options.breadcrumbSettings.clickable = true;
    }

    this.wizardHeader = this.ce('ul', {
      class: 'pagination'
    });

    // Add the header to the beginning.
    this.prepend(this.wizardHeader);

    let showHistory = (currentPage.breadcrumb.toLowerCase() === 'history');
    each(this.pages, (page, i) => {
      // See if this page is in our history.
      if (showHistory && ((this.page !== i) && !this.history.includes(i))) {
        return;
      }

      // Set clickable based on breadcrumb settings
      let clickable = this.page !== i && this.options.breadcrumbSettings.clickable

      let pageButton = this.ce('li', {
        class: (i === this.page) ? 'active' : (clickable ? '' : 'disabled'),
        style: (clickable) ? 'cursor: pointer;' : ''
      });

      // Navigate to the page as they click on it.

      if (clickable) {
        this.addEventListener(pageButton, 'click', (event) => {
          event.preventDefault();
          this.setPage(i);
        });
      }

      let pageLabel = this.ce('span');
      let pageTitle = page.title;
      if (currentPage.breadcrumb.toLowerCase() === 'condensed') {
        pageTitle = ((i === this.page) || showHistory) ? page.title : (i + 1);
        if (!pageTitle) {
          pageTitle = (i + 1);
        }
      }

      pageLabel.appendChild(this.text(pageTitle));
      pageButton.appendChild(pageLabel);
      this.wizardHeader.appendChild(pageButton);
    });
  }

  pageId(page) {
    if (page.key) {
      return page.key;
    }
    else if (
      page.components &&
      page.components.length > 0
    ) {
      return this.pageId(page.components[0]);
    }
    else {
      return page.title;
    }
  }

  onChange(flags, changed) {
    super.onChange(flags, changed);

    // Only rebuild if there is a page change.
    let pageIndex = 0;
    let rebuild = false;
    each(this.wizard.components, (component) => {
      if (component.type !== 'panel') {
        return;
      }

      if (FormioUtils.hasCondition(component)) {
        let hasPage = this.pages && this.pages[pageIndex] && (this.pageId(this.pages[pageIndex]) === this.pageId(component));
        let shouldShow = FormioUtils.checkCondition(component, this.data, this.data);
        if ((shouldShow && !hasPage) || (!shouldShow && hasPage)) {
          rebuild = true;
          return false;
        }
        if (shouldShow) {
          pageIndex++;
        }
      }
      else {
        pageIndex++;
      }
    });

    if (rebuild) {
      this.setForm(this.wizard);
    }

    // Update Wizard Nav
    let nextPage = this.getNextPage(this.submission.data, this.page);
    if (this._nextPage != nextPage) {
      this.buildWizardNav(nextPage);
      this.emit('updateWizardNav', {oldpage: this._nextPage, newpage: nextPage, submission: this.submission});
      this._nextPage = nextPage;
    }
  }

  buildWizardNav(nextPage) {
    if (this.wizardNav) {
      this.wizardNav.innerHTML = '';
      if (this.element.contains(this.wizardNav)) {
        this.element.removeChild(this.wizardNav);
      }
    }
    if (this.wizard.full) {
      return;
    }
    this.wizardNav = this.ce('ul', {
      class: 'list-inline'
    });
    this.element.appendChild(this.wizardNav);
    each([
      {name: 'cancel',    method: 'cancel',   class: 'btn btn-default'},
      {name: 'previous',  method: 'prevPage', class: 'btn btn-primary'},
      {name: 'next',      method: 'nextPage', class: 'btn btn-primary'},
      {name: 'submit',    method: 'submit',   class: 'btn btn-primary'}
    ], (button) => {
      if (!this.hasButton(button.name, nextPage)) {
        return;
      }
      let buttonWrapper = this.ce('li');
      let buttonProp = button.name + 'Button';
      let buttonElement = this[buttonProp] = this.ce('button', {
        class: button.class + ' btn-wizard-nav-' + button.name
      });
      buttonElement.appendChild(this.text(this.t(button.name)));
      this.addEventListener(this[buttonProp], 'click', (event) => {
        event.preventDefault();

        // Disable the button until done.
        buttonElement.setAttribute('disabled', 'disabled');
        this.setLoading(buttonElement, true);

        // Call the button method, then re-enable the button.
        this[button.method]().then(() => {
          buttonElement.removeAttribute('disabled');
          this.setLoading(buttonElement, false);
        }).catch(() => {
          buttonElement.removeAttribute('disabled');
          this.setLoading(buttonElement, false);
        });
      });
      buttonWrapper.appendChild(this[buttonProp]);
      this.wizardNav.appendChild(buttonWrapper);
    });
  }
}

FormioWizard.setBaseUrl = Formio.setBaseUrl;
FormioWizard.setApiUrl = Formio.setApiUrl;
FormioWizard.setAppUrl = Formio.setAppUrl;

module.exports = global.FormioWizard = FormioWizard;
<commit_msg>Adding optional buttonSettings option to hide next and/or previous buttons on the wizard<commit_after>'use strict';
import Promise from "native-promise-only";
import FormioForm from './formio.form';
import Formio from './formio';
import FormioUtils from './utils';
import each from 'lodash/each';
import clone from 'lodash/clone';
export class FormioWizard extends FormioForm {
  constructor(element, options) {
    super(element, options);
    this.wizard = null;
    this.pages = [];
    this.globalComponents = [];
    this.page = 0;
    this.history = [];
    this._nextPage = 0;
  }

  setPage(num) {
    if (!this.wizard.full && num >= 0 && num < this.pages.length) {
      this.page = num;
      return super.setForm(this.currentPage());
    }
    else if (this.wizard.full) {
      return super.setForm(this.getWizard());
    }
    return Promise.reject('Page not found');
  }

  getNextPage(data, currentPage) {
    let form = this.pages[currentPage];
    // Check conditional nextPage
    if (form) {
      let page = ++currentPage;
      if (form.nextPage) {
        // Allow for script execution.
        if (typeof form.nextPage === 'string') {
          try {
            let next = page;
            eval('(function(data) {' + form.nextPage.toString() + '})(data)');
            page = next;
            if (!isNaN(parseInt(page, 10)) && isFinite(page)) {
              return page;
            }
            if (typeof page !== 'string') {
              return page;
            }

            // Assume they passed back the key of the page to go to.
            return this.getPageIndexByKey(page);
          }
          catch (e) {
            console.warn('An error occurred in a custom nextPage function statement for component ' + form.key, e);
            return page;
          }
        }
        // Or use JSON Logic.
        else {
          let result = FormioUtils.jsonLogic.apply(form.nextPage, {
            data: data,
            page: page,
            form: form
          });
          let newPage = parseInt(result, 10);
          if (!isNaN(parseInt(newPage, 10)) && isFinite(newPage)) {
            return newPage;
          }

          return this.getPageIndexByKey(result);
        }
      }

      return page;
    }

    return null;
  }

  getPreviousPage() {
    let prev = this.history.pop();
    if(typeof prev !== 'undefined') {
      return prev;
    }

    return this.page - 1;
  }

  nextPage() {
    // Validate the form builed, before go to the next page
    if (this.checkValidity(this.submission.data, true)) {
      this.checkData(this.submission.data, {
        noValidate: true
      });
      return this.beforeNext().then(() => {
        this.history.push(this.page);
        return this.setPage(this.getNextPage(this.submission.data, this.page)).then(() => {
          this._nextPage = this.getNextPage(this.submission.data, this.page);
          this.emit('nextPage', {page: this.page, submission: this.submission});
        });
      });
    }
    else {
      return Promise.reject(this.showErrors());
    }
  }

  prevPage() {
    let prevPage = this.getPreviousPage();
    return this.setPage(prevPage).then(() => {
      this.emit('prevPage', {page: this.page, submission: this.submission});
    });
  }

  cancel() {
    super.cancel();
    this.history = [];
    return this.setPage(0);
  }

  getPageIndexByKey(key) {
    let pageIndex = 0;
    each(this.pages, (_page, index) => {
      if (_page.key === key) {
        pageIndex = index;
        return false;
      }
    });
    return pageIndex;
  }

  addGlobalComponents(page) {
    // If there are non-page components, then add them here. This is helpful to allow for hidden fields that
    // can propogate between pages.
    if (this.globalComponents.length) {
      page.components = this.globalComponents.concat(page.components);
    }
    return page;
  }

  getPage(pageNum) {
    if ((pageNum >= 0) && (pageNum < this.pages.length)) {
      return this.addGlobalComponents(this.pages[pageNum]);
    }
    return null;
  }

  getWizard() {
    let pageIndex = 0;
    let page = null;
    let wizard = clone(this.wizard);
    wizard.components = [];
    do {
      page = this.getPage(pageIndex);
      if (page) {
        wizard.components.push(page);
      }
    } while (pageIndex = this.getNextPage(this.submission.data, pageIndex));

    // Add all other components.
    each(this.wizard.components, (component) => {
      if (component.type !== 'panel') {
        wizard.components.push(component);
      }
    });

    return wizard;
  }

  currentPage() {
    return this.getPage(this.page);
  }

  buildPages(form) {
    this.pages = [];
    each(form.components, (component) => {
      if (component.type === 'panel') {
        // Ensure that this page can be seen.
        if (FormioUtils.checkCondition(component, this.data, this.data)) {
          this.pages.push(component);
        }
      }
      else if (component.type === 'hidden') {
        // Global components are hidden components that can propagate between pages.
        this.globalComponents.push(component);
      }
    });
    this.buildWizardHeader();
    this.buildWizardNav();
  }

  setForm(form) {
    if (!form) {
      return;
    }
    this.wizard = form;
    this.buildPages(this.wizard);
    return this.setPage(this.page);
  }

  build() {
    super.build();
    this.formReady.then(() => {
      this.buildWizardHeader();
      this.buildWizardNav();
    });
  }

  hasButton(name, nextPage) {
    // Check for and initlize button settings object
    this.options.buttonSettings = this.options.buttonSettings || {};
    if(this.options.buttonSettings.previous === undefined) {
      this.options.buttonSettings.previous = true;
    }
    if(this.options.buttonSettings.next === undefined) {
      this.options.buttonSettings.next = true;
    }

    if (name === 'previous') {
      return (this.page > 0) && this.options.buttonSettings.previous;
    }
    nextPage = (nextPage === undefined) ? this.getNextPage(this.submission.data, this.page) : nextPage;
    if (name === 'next') {
      return (nextPage !== null) && (nextPage < this.pages.length) && this.options.buttonSettings.next;
    }
    if (name === 'submit') {
      return (nextPage === null) || (this.page === (this.pages.length - 1));
    }
    return true;
  }

  buildWizardHeader() {
    if (this.wizardHeader) {
      this.wizardHeader.innerHTML = '';
    }

    let currentPage = this.currentPage();
    if (!currentPage || this.wizard.full) {
      return;
    }

    currentPage.breadcrumb = currentPage.breadcrumb || 'default';
    if (currentPage.breadcrumb.toLowerCase() === 'none') {
      return;
    }

    // Check for and initlize breadcrumb settings object
    this.options.breadcrumbSettings = this.options.breadcrumbSettings || {};
    if(this.options.breadcrumbSettings.clickable === undefined) {
      this.options.breadcrumbSettings.clickable = true;
    }

    this.wizardHeader = this.ce('ul', {
      class: 'pagination'
    });

    // Add the header to the beginning.
    this.prepend(this.wizardHeader);

    let showHistory = (currentPage.breadcrumb.toLowerCase() === 'history');
    each(this.pages, (page, i) => {
      // See if this page is in our history.
      if (showHistory && ((this.page !== i) && !this.history.includes(i))) {
        return;
      }

      // Set clickable based on breadcrumb settings
      let clickable = this.page !== i && this.options.breadcrumbSettings.clickable

      let pageButton = this.ce('li', {
        class: (i === this.page) ? 'active' : (clickable ? '' : 'disabled'),
        style: (clickable) ? 'cursor: pointer;' : ''
      });

      // Navigate to the page as they click on it.

      if (clickable) {
        this.addEventListener(pageButton, 'click', (event) => {
          event.preventDefault();
          this.setPage(i);
        });
      }

      let pageLabel = this.ce('span');
      let pageTitle = page.title;
      if (currentPage.breadcrumb.toLowerCase() === 'condensed') {
        pageTitle = ((i === this.page) || showHistory) ? page.title : (i + 1);
        if (!pageTitle) {
          pageTitle = (i + 1);
        }
      }

      pageLabel.appendChild(this.text(pageTitle));
      pageButton.appendChild(pageLabel);
      this.wizardHeader.appendChild(pageButton);
    });
  }

  pageId(page) {
    if (page.key) {
      return page.key;
    }
    else if (
      page.components &&
      page.components.length > 0
    ) {
      return this.pageId(page.components[0]);
    }
    else {
      return page.title;
    }
  }

  onChange(flags, changed) {
    super.onChange(flags, changed);

    // Only rebuild if there is a page change.
    let pageIndex = 0;
    let rebuild = false;
    each(this.wizard.components, (component) => {
      if (component.type !== 'panel') {
        return;
      }

      if (FormioUtils.hasCondition(component)) {
        let hasPage = this.pages && this.pages[pageIndex] && (this.pageId(this.pages[pageIndex]) === this.pageId(component));
        let shouldShow = FormioUtils.checkCondition(component, this.data, this.data);
        if ((shouldShow && !hasPage) || (!shouldShow && hasPage)) {
          rebuild = true;
          return false;
        }
        if (shouldShow) {
          pageIndex++;
        }
      }
      else {
        pageIndex++;
      }
    });

    if (rebuild) {
      this.setForm(this.wizard);
    }

    // Update Wizard Nav
    let nextPage = this.getNextPage(this.submission.data, this.page);
    if (this._nextPage != nextPage) {
      this.buildWizardNav(nextPage);
      this.emit('updateWizardNav', {oldpage: this._nextPage, newpage: nextPage, submission: this.submission});
      this._nextPage = nextPage;
    }
  }

  buildWizardNav(nextPage) {
    if (this.wizardNav) {
      this.wizardNav.innerHTML = '';
      if (this.element.contains(this.wizardNav)) {
        this.element.removeChild(this.wizardNav);
      }
    }
    if (this.wizard.full) {
      return;
    }
    this.wizardNav = this.ce('ul', {
      class: 'list-inline'
    });
    this.element.appendChild(this.wizardNav);
    each([
      {name: 'cancel',    method: 'cancel',   class: 'btn btn-default'},
      {name: 'previous',  method: 'prevPage', class: 'btn btn-primary'},
      {name: 'next',      method: 'nextPage', class: 'btn btn-primary'},
      {name: 'submit',    method: 'submit',   class: 'btn btn-primary'}
    ], (button) => {
      if (!this.hasButton(button.name, nextPage)) {
        return;
      }
      let buttonWrapper = this.ce('li');
      let buttonProp = button.name + 'Button';
      let buttonElement = this[buttonProp] = this.ce('button', {
        class: button.class + ' btn-wizard-nav-' + button.name
      });
      buttonElement.appendChild(this.text(this.t(button.name)));
      this.addEventListener(this[buttonProp], 'click', (event) => {
        event.preventDefault();

        // Disable the button until done.
        buttonElement.setAttribute('disabled', 'disabled');
        this.setLoading(buttonElement, true);

        // Call the button method, then re-enable the button.
        this[button.method]().then(() => {
          buttonElement.removeAttribute('disabled');
          this.setLoading(buttonElement, false);
        }).catch(() => {
          buttonElement.removeAttribute('disabled');
          this.setLoading(buttonElement, false);
        });
      });
      buttonWrapper.appendChild(this[buttonProp]);
      this.wizardNav.appendChild(buttonWrapper);
    });
  }
}

FormioWizard.setBaseUrl = Formio.setBaseUrl;
FormioWizard.setApiUrl = Formio.setApiUrl;
FormioWizard.setAppUrl = Formio.setAppUrl;

module.exports = global.FormioWizard = FormioWizard;
<|endoftext|>


<commit_before>/**
 * Created by fuhuixiang on 16-5-31.
 */
'use strict';
let express = require('express');
let router = express.Router();

router.get('/get_time', require('../modules/time'));

module.exports = router;
<commit_msg>change route<commit_after>/**
 * Created by fuhuixiang on 16-5-31.
 */
'use strict';
let express = require('express');
let router = express.Router();

router.get('/v1/get_time', require('../modules/time'));

module.exports = router;
<|endoftext|>


<commit_before>module.exports = function (dependency) {
  var pgClient = dependency.pgClient,
      sockets = dependency.sockets,
      moment = dependency.moment;

  return function (request, response, next) {
    switch(request.method) {
      /**
       * 200 --- accepted
       * 400 --- bad request
       */
      case 'GET':
        var players = [],
            messages = [];
        pgClient.query('SELECT player_id, player_username FROM players;', [], function (error, result) {
          if (error === null) {
            players = result.rows;

            pgClient.query('SELECT wall_id, wall_player, wall_message, wall_timestamp FROM wall;', [], function (error, result) {
              if (error === null) {
                messages = result.rows;
                var iMessages = 0,
                    lMessages = messages.length,
                    iPlayers = 0,
                    lPlayers = players.length;

                for (; iMessages < lMessages; iMessages++) {
                  if (moment(messages[iMessages].wall_timestamp).add(14, 'days').isAfter(moment()) === true) {
                    iPlayers = 0;
                    for (; iPlayers < lPlayers; iPlayers++) {
                      if (messages[iMessages].wall_player === players[iPlayers].player_id) {
                        messages[iMessages].wall_player = players[iPlayers];
                        break;
                      }
                    }
                  } else {
                    // wall messages older than 2 weeks are deleted!
                    // PS:
                    // all messages will be returned (stored before deletion)
                    pgClient.query('DELETE FROM wall WHERE wall_id=$1', [messages[iMessages].wall_id]);
                  }
                }

                response.status(200);
                response.json(messages);
              } else {
                response.status(400);
                response.json({});
              }
            });
          } else {
            response.status(400);
            response.json({});
          }
        });
      break;

      /**
       * to get around the stability issue of Internet connection *here*
       * we're going to use the good ol' requests for post and delete
       * we'll only use socket to broadcast new posts
       */
      case 'POST':
        if (request.body.message.length > 2 && request.body.message.length < 500) {
          pgClient.query('INSERT INTO wall (wall_player, wall_message, wall_timestamp) VALUES ($1, $2, $3) RETURNING wall_id, wall_player, wall_message, wall_timestamp;', [request.session.player_id, request.body.message, moment().toDate()], function (error, result) {
            if (error === null) {
              var message = result.rows[0];
              message.wall_player = {
                player_id: request.session.player_id,
                player_username: request.session.player_username
              };

              // broadcasting to whoever is `connected`
              sockets[request.session.player_username].broadcast.emit('message', {mode: 'NEW_MESSAGE', message: message});
            }

            response.status(error === null ? 202 : 409);
            response.json(error === null ? message : {});
          });
        } else {
          response.status(400);
          response.json({});
        }
      break;

      default:
        response.status(405);
        response.json({});
      break;
    }
  };
};
<commit_msg>90 days<commit_after>module.exports = function (dependency) {
  var pgClient = dependency.pgClient,
      sockets = dependency.sockets,
      moment = dependency.moment;

  return function (request, response, next) {
    switch(request.method) {
      /**
       * 200 --- accepted
       * 400 --- bad request
       */
      case 'GET':
        var players = [],
            messages = [];
        pgClient.query('SELECT player_id, player_username FROM players;', [], function (error, result) {
          if (error === null) {
            players = result.rows;

            pgClient.query('SELECT wall_id, wall_player, wall_message, wall_timestamp FROM wall;', [], function (error, result) {
              if (error === null) {
                messages = result.rows;
                var iMessages = 0,
                    lMessages = messages.length,
                    iPlayers = 0,
                    lPlayers = players.length;

                for (; iMessages < lMessages; iMessages++) {
                  if (moment(messages[iMessages].wall_timestamp).add(90, 'days').isAfter(moment()) === true) {
                    iPlayers = 0;
                    for (; iPlayers < lPlayers; iPlayers++) {
                      if (messages[iMessages].wall_player === players[iPlayers].player_id) {
                        messages[iMessages].wall_player = players[iPlayers];
                        break;
                      }
                    }
                  } else {
                    // wall messages older than 2 weeks are deleted!
                    // PS:
                    // all messages will be returned (stored before deletion)
                    pgClient.query('DELETE FROM wall WHERE wall_id=$1', [messages[iMessages].wall_id]);
                  }
                }

                response.status(200);
                response.json(messages);
              } else {
                response.status(400);
                response.json({});
              }
            });
          } else {
            response.status(400);
            response.json({});
          }
        });
      break;

      /**
       * to get around the stability issue of Internet connection *here*
       * we're going to use the good ol' requests for post and delete
       * we'll only use socket to broadcast new posts
       */
      case 'POST':
        if (request.body.message.length > 2 && request.body.message.length < 500) {
          pgClient.query('INSERT INTO wall (wall_player, wall_message, wall_timestamp) VALUES ($1, $2, $3) RETURNING wall_id, wall_player, wall_message, wall_timestamp;', [request.session.player_id, request.body.message, moment().toDate()], function (error, result) {
            if (error === null) {
              var message = result.rows[0];
              message.wall_player = {
                player_id: request.session.player_id,
                player_username: request.session.player_username
              };

              // broadcasting to whoever is `connected`
              sockets[request.session.player_username].broadcast.emit('message', {mode: 'NEW_MESSAGE', message: message});
            }

            response.status(error === null ? 202 : 409);
            response.json(error === null ? message : {});
          });
        } else {
          response.status(400);
          response.json({});
        }
      break;

      default:
        response.status(405);
        response.json({});
      break;
    }
  };
};
<|endoftext|>


<commit_before>import styleBody from 'ghost/mixins/style-body';
import loadingIndicator from 'ghost/mixins/loading-indicator';

var DebugRoute = Ember.Route.extend(Ember.SimpleAuth.AuthenticatedRouteMixin, styleBody, loadingIndicator, {
    classNames: ['settings'],

    model: function () {
        return this.store.find('setting', { type: 'blog,theme' }).then(function (records) {
            return records.get('firstObject');
        });
    }
});

export default DebugRoute;
<commit_msg>Redirect authors and editors away from debug page<commit_after>import styleBody from 'ghost/mixins/style-body';
import loadingIndicator from 'ghost/mixins/loading-indicator';

var DebugRoute = Ember.Route.extend(Ember.SimpleAuth.AuthenticatedRouteMixin, styleBody, loadingIndicator, {
    classNames: ['settings'],

    beforeModel: function () {
        var self = this;
        this.store.find('user', 'me').then(function (user) {
            if (user.get('isAuthor') || user.get('isEditor')) {
                self.transitionTo('posts');
            }
        });
    },

    model: function () {
        return this.store.find('setting', { type: 'blog,theme' }).then(function (records) {
            return records.get('firstObject');
        });
    }

});

export default DebugRoute;
<|endoftext|>


<commit_before>const Keyboard = require('./keyboard');
const Emitters = require('./emitters');

function Mainloop (renderer, sound) {
  if (!(this instanceof Mainloop)) return new Mainloop(renderer, sound);

  this.renderer = renderer;
  this.sound = sound;

  this.timer = null;
}

Mainloop.prototype.init = function () {
  this.key = {
    left: Keyboard(37),
    up: Keyboard(38),
    right: Keyboard(39),
    down: Keyboard(40),
    jump: Keyboard(32)
  };

  // add canvas to DOM
  document.getElementById('main').appendChild(this.renderer.view);

  // add background
  this.stageRoot = new PIXI.Container();

  this.level.addBackgroundToStage(this.stageRoot);

  this.stage = new PIXI.Container();
  this.stageRoot.addChild(this.stage);

  this.level.addSpritesToStage(this.stage);
  this.enemies.addSpritesToStage(this.stage);
  this.hero.addSpritesToStage(this.stage);

  this.emitters = Emitters(this.renderer, this.stage, this.level.levelData);
  this.emitters.hero_jump();
  this.enemies.addEmitter(this.emitters);

  this.g = this.level.g;

  this.nowFunction = () => performance && performance.now() || Date.now();
  this.now = this.nowFunction();
  this.interval = 1000 / 120;
  this.tolerance = 0.1;

  this.sound.playLoopSound('music', this.level.musicFile);
};

Mainloop.prototype.destroy = function (cb) {
  // destroy particle
  this.emitters.destroy();

  // unbind keys
  Object.keys(this.key).forEach((index) => {
    this.key[index].destroy();
  });

  // clear dom
  let myNode = document.getElementById('main');
  while (myNode.firstChild) {
    myNode.removeChild(myNode.firstChild);
  }

  // clear timer
  this.timer && cancelAnimationFrame(this.timer);
  this.timer = null;

  this.sound.stopLoopSound('music', this.level.musicFile);

  cb && cb();
};

Mainloop.prototype.run = function (level, hero, enemies) {
  return new Promise((resolve, reject) => {
    this.level = level;
    this.hero = hero;
    this.enemies = enemies;

    if (PIXI.loader._queue._tasks.length) {

      document.getElementById('loading').style.display = 'block';
      document.getElementById('main').style.display = 'none';

      PIXI.loader.on('progress', (loader) => {
        let element = document.getElementById('progress');
        if (element) {
          element.style.display = 'block';
          element.value = Math.round(loader.progress);
          element.innerHTML = Math.round(loader.progress) + '%';
        }
      }).load(() => {
        document.getElementById('loading').style.display = 'none';
        document.getElementById('main').style.display = 'block';
        this.init();
        this.mainloop(resolve, reject);
      });
    } else {
      this.init();
      this.mainloop(resolve, reject);
    }
  });
};

Mainloop.prototype.mainloop = function (resolve, reject) {
  this.timer = requestAnimationFrame(this.mainloop.bind(this, resolve, reject));
  const now = this.nowFunction(),
    delta = (now - this.now);

  if (delta >= this.interval - this.tolerance) {
    this.now = now - (delta % this.interval);

    for (let calcFrame = 0, frames = Math.floor(delta / this.interval); calcFrame < frames; calcFrame++) {
      // move enemies
      let sound = this.enemies.update(this.level, this.hero);
      sound && this.sound.playSound('sfx', sound);

      // apply schwerkraft
      this.hero.applyAdditionalForce(0, this.g);
      this.hero.updatePositionY();
      this.hero.checkAnimation();

      if (!this.hero.victory) {
        this.hero.checkVictory(this.level) && this.sound.playSound('sfx', 'bionic');
      }

      if (this.hero.victory) {
        if (this.hero.victoryAnimation(this.level)) {
          return this.destroy(resolve);
        }
      } else {
        this.hero.animate(this.key.down.isDown);

        // runterfallen + gegner
        if (!this.hero.dead) {
          this.hero.checkFloorDeath(this.level) && this.sound.playSound('sfx', 'e_laugh');
          let collision = this.enemies.collision(this.hero);
          collision && this.sound.playSound('sfx', collision);
        }

        if (this.hero.dead) {
          if (this.hero.deathAnimation(this.level)) {
            return this.destroy(reject);
          }
        } else {

          // collision detection with level
          this.hero.checkCeiling(this.level);
          this.hero.checkFloor(this.level);

          this.hero.moveInAir();

          if (this.key.right.isDown) {
            if (this.hero.canJump) {
              this.hero.ax = 3;
            } else {
              this.hero.ax = this.hero.ax + 0.25;
            }
          }
          if (this.key.left.isDown) {
            if (this.hero.canJump) {
              this.hero.ax = -3;
            } else {
              this.hero.ax = this.hero.ax - 0.25;
            }
          }

          // jumping
          if ((this.key.jump.isDown || this.key.up.isDown) && this.hero.canJump && this.jumpKey === false) {
            this.sound.playSound('sfx', 'boing');
            this.emitters.play('hero.jump', this.hero.x, this.hero.y + this.hero.height);
            this.jumpKey = true;
            this.hero.ay = -11;
            this.hero.canJump = false;
            //Addpartikel 15, hero.sprite.x - LevelX, hero.sprite.y + 96, hero.sprite.x + 48 - LevelX, hero.sprite.y + 96, False
          } else {
            if (this.key.jump.isUp && this.key.up.isUp) {
              this.jumpKey = false;
            }
          }

          //check links und rechts
          this.hero.updatePositionXY(this.level);

          // scrollen
          if (this.hero.x + this.stage.x > 2 * this.renderer.width / 5) {
            this.stage.x = Math.max(this.renderer.view.width - this.level.width, Math.min(2 * this.renderer.width / 5 - this.hero.x, 0));
          }
          if (this.hero.x + this.stage.x < 150) {
            this.stage.x = Math.max(this.renderer.view.width - this.level.width, Math.min(150 - this.hero.x, 0));
          }
        }
      }

      if (this.level.rumble) {
        this.level.rumble--;
        this.stage.y = Math.random() * 6 - 3;
      } else {
        this.stage.y = 0;
      }
    }

    console.log(delta);

    // The emitter requires the elapsed
    // number of seconds since the last update
    this.emitters.update(delta * 0.001);

    this.renderer.render(this.stageRoot);
  }
};

module.exports = Mainloop;<commit_msg>Update mainloop.js<commit_after>const Keyboard = require('./keyboard');
const Emitters = require('./emitters');

function Mainloop (renderer, sound) {
  if (!(this instanceof Mainloop)) return new Mainloop(renderer, sound);

  this.renderer = renderer;
  this.sound = sound;

  this.timer = null;
}

Mainloop.prototype.init = function () {
  this.key = {
    left: Keyboard(37),
    up: Keyboard(38),
    right: Keyboard(39),
    down: Keyboard(40),
    jump: Keyboard(32)
  };

  // add canvas to DOM
  document.getElementById('main').appendChild(this.renderer.view);

  // add background
  this.stageRoot = new PIXI.Container();

  this.level.addBackgroundToStage(this.stageRoot);

  this.stage = new PIXI.Container();
  this.stageRoot.addChild(this.stage);

  this.level.addSpritesToStage(this.stage);
  this.enemies.addSpritesToStage(this.stage);
  this.hero.addSpritesToStage(this.stage);

  this.emitters = Emitters(this.renderer, this.stage, this.level.levelData);
  this.emitters.hero_jump();
  this.enemies.addEmitter(this.emitters);

  this.g = this.level.g;

  this.nowFunction = () => performance && performance.now() || Date.now();
  this.now = this.nowFunction();
  this.interval = 1000 / 60;
  this.tolerance = 0.1;

  this.sound.playLoopSound('music', this.level.musicFile);
};

Mainloop.prototype.destroy = function (cb) {
  // destroy particle
  this.emitters.destroy();

  // unbind keys
  Object.keys(this.key).forEach((index) => {
    this.key[index].destroy();
  });

  // clear dom
  let myNode = document.getElementById('main');
  while (myNode.firstChild) {
    myNode.removeChild(myNode.firstChild);
  }

  // clear timer
  this.timer && cancelAnimationFrame(this.timer);
  this.timer = null;

  this.sound.stopLoopSound('music', this.level.musicFile);

  cb && cb();
};

Mainloop.prototype.run = function (level, hero, enemies) {
  return new Promise((resolve, reject) => {
    this.level = level;
    this.hero = hero;
    this.enemies = enemies;

    if (PIXI.loader._queue._tasks.length) {

      document.getElementById('loading').style.display = 'block';
      document.getElementById('main').style.display = 'none';

      PIXI.loader.on('progress', (loader) => {
        let element = document.getElementById('progress');
        if (element) {
          element.style.display = 'block';
          element.value = Math.round(loader.progress);
          element.innerHTML = Math.round(loader.progress) + '%';
        }
      }).load(() => {
        document.getElementById('loading').style.display = 'none';
        document.getElementById('main').style.display = 'block';
        this.init();
        this.mainloop(resolve, reject);
      });
    } else {
      this.init();
      this.mainloop(resolve, reject);
    }
  });
};

Mainloop.prototype.mainloop = function (resolve, reject) {
  this.timer = requestAnimationFrame(this.mainloop.bind(this, resolve, reject));
  const now = this.nowFunction(),
    delta = (now - this.now);

  if (delta >= this.interval - this.tolerance) {
    this.now = now - (delta % this.interval);

    for (let calcFrame = 0, frames = Math.floor(delta / this.interval); calcFrame < frames; calcFrame++) {
      // move enemies
      let sound = this.enemies.update(this.level, this.hero);
      sound && this.sound.playSound('sfx', sound);

      // apply schwerkraft
      this.hero.applyAdditionalForce(0, this.g);
      this.hero.updatePositionY();
      this.hero.checkAnimation();

      if (!this.hero.victory) {
        this.hero.checkVictory(this.level) && this.sound.playSound('sfx', 'bionic');
      }

      if (this.hero.victory) {
        if (this.hero.victoryAnimation(this.level)) {
          return this.destroy(resolve);
        }
      } else {
        this.hero.animate(this.key.down.isDown);

        // runterfallen + gegner
        if (!this.hero.dead) {
          this.hero.checkFloorDeath(this.level) && this.sound.playSound('sfx', 'e_laugh');
          let collision = this.enemies.collision(this.hero);
          collision && this.sound.playSound('sfx', collision);
        }

        if (this.hero.dead) {
          if (this.hero.deathAnimation(this.level)) {
            return this.destroy(reject);
          }
        } else {

          // collision detection with level
          this.hero.checkCeiling(this.level);
          this.hero.checkFloor(this.level);

          this.hero.moveInAir();

          if (this.key.right.isDown) {
            if (this.hero.canJump) {
              this.hero.ax = 3;
            } else {
              this.hero.ax = this.hero.ax + 0.25;
            }
          }
          if (this.key.left.isDown) {
            if (this.hero.canJump) {
              this.hero.ax = -3;
            } else {
              this.hero.ax = this.hero.ax - 0.25;
            }
          }

          // jumping
          if ((this.key.jump.isDown || this.key.up.isDown) && this.hero.canJump && this.jumpKey === false) {
            this.sound.playSound('sfx', 'boing');
            this.emitters.play('hero.jump', this.hero.x, this.hero.y + this.hero.height);
            this.jumpKey = true;
            this.hero.ay = -11;
            this.hero.canJump = false;
            //Addpartikel 15, hero.sprite.x - LevelX, hero.sprite.y + 96, hero.sprite.x + 48 - LevelX, hero.sprite.y + 96, False
          } else {
            if (this.key.jump.isUp && this.key.up.isUp) {
              this.jumpKey = false;
            }
          }

          //check links und rechts
          this.hero.updatePositionXY(this.level);

          // scrollen
          if (this.hero.x + this.stage.x > 2 * this.renderer.width / 5) {
            this.stage.x = Math.max(this.renderer.view.width - this.level.width, Math.min(2 * this.renderer.width / 5 - this.hero.x, 0));
          }
          if (this.hero.x + this.stage.x < 150) {
            this.stage.x = Math.max(this.renderer.view.width - this.level.width, Math.min(150 - this.hero.x, 0));
          }
        }
      }

      if (this.level.rumble) {
        this.level.rumble--;
        this.stage.y = Math.random() * 6 - 3;
      } else {
        this.stage.y = 0;
      }
    }

    console.log(delta);

    // The emitter requires the elapsed
    // number of seconds since the last update
    this.emitters.update(delta * 0.001);

    this.renderer.render(this.stageRoot);
  }
};

module.exports = Mainloop;
<|endoftext|>


<commit_before>var express = require('express');
var _ = require('underscore');
var router = express.Router();
//var read = [];
//var reading = [];
var data = [];
var isAppdata =false;
var types=[];
var Client = require("ibmiotf");
var current_type="+";
var current_id="+";

/* GET home page. */
router.get('/', function(req, res, next) {
	 console.log("org id:"+ req.query.org_id)
	 if(req.query.auth_key && req.query.auth_token){
		var obj ={
		  "org": req.query.auth_key.split('-')[1],
		  "id": new Date().getTime()+"",
		  "auth-key": req.query.auth_key,
		  "auth-token": req.query.auth_token
		}
		appClient = new Client.IotfApplication(obj);
		appClient.connect();

		appClient.on("connect", function () {
			res.redirect('/status');
		});

		appClient.on("deviceStatus", function (deviceType, deviceId, payload, topic) {
			var obj = JSON.parse(payload);
			obj.id = deviceId;
			obj.type = deviceType;

			console.log("Device status from :: "+deviceType+" : "+deviceId+" is "+obj.Action+" with Close Code being "+obj.CloseCode+" and Reason being \""+obj.Reason+" "+obj.ClientAddr+"\"");
			var info = _.find(data,function(itm){return itm.id == deviceId && itm.type == deviceType});

			if(!info){
				data.push(obj);
			}
			else
			{
				info.Action = obj.Action;
				info.CloseCode= obj.CloseCode;
				info.Reason=obj.Reason;
				info.ClientAddr=obj.ClientAddr;
			}
		});

		appClient.on("error", function (err) {
				console.log("Error : "+err);
		});
	 }
	 else{
		res.render('user', { title: 'IBM Watson IoT Platform'});//,data,selected:req.query.type});
	 }

});

/* GET Device Status page. */
router.get('/status', function(req, res, next) {
	if(typeof appClient != 'undefined'){
		if (req.query.type && current_type != req.query.type  ){
			data =[];
			appClient.unsubscribeToDeviceStatus(current_type, current_id);
			current_type = req.query.type;
			current_id = "";
		}
		if (req.query.id && current_id != req.query.id ){
			data =[];
			appClient.unsubscribeToDeviceStatus(current_type, current_id);
			current_id = req.query.id;
		}

		appClient.subscribeToDeviceStatus(current_type||"+",current_id||"+",0);
		res.render('status', { title: 'IBM Watson IoT Platform' ,data,types,selected:current_type});
	}
	else{
		res.redirect('/');
	}

});
router.get('/status/data', function(req, res, next) {
    res.json(data);
});
router.get('/status/type', function(req, res, next) {
	appClient.getAllDeviceTypes().then (function onSuccess (response) {

				types = _.pluck(response.results,"id");
				res.json(types);

		}, function onError (error) {

			console.log("Fail");
			console.log(error);
			res.json(types)
		}
		);
});
module.exports = router;
<commit_msg>Edited 19 and 65 to refresh the content at login<commit_after>var express = require('express');
var _ = require('underscore');
var router = express.Router();
//var read = [];
//var reading = [];
var data = [];
var isAppdata =false;
var types=[];
var Client = require("ibmiotf");
var current_type="+";
var current_id="+";

/* GET home page. */
router.get('/', function(req, res, next) {
	 console.log("org id:"+ req.query.org_id)
	 if(req.query.auth_key && req.query.auth_token){
		data =[];
		var obj ={
		  "org": req.query.auth_key.split('-')[1],
		  "id": new Date().getTime()+"",
		  "auth-key": req.query.auth_key,
		  "auth-token": req.query.auth_token
		}
		appClient = new Client.IotfApplication(obj);
		appClient.connect();

		appClient.on("connect", function () {
			res.redirect('/status');
		});

		appClient.on("deviceStatus", function (deviceType, deviceId, payload, topic) {
			var obj = JSON.parse(payload);
			obj.id = deviceId;
			obj.type = deviceType;

			console.log("Device status from :: "+deviceType+" : "+deviceId+" is "+obj.Action+" with Close Code being "+obj.CloseCode+" and Reason being \""+obj.Reason+" "+obj.ClientAddr+"\"");
			var info = _.find(data,function(itm){return itm.id == deviceId && itm.type == deviceType});

			if(!info){
				data.push(obj);
			}
			else
			{
				info.Action = obj.Action;
				info.CloseCode= obj.CloseCode;
				info.Reason=obj.Reason;
				info.ClientAddr=obj.ClientAddr;
			}
		});

		appClient.on("error", function (err) {
				console.log("Error : "+err);
		});
	 }
	 else{
		res.render('user', { title: 'IBM Watson IoT Platform'});//,data,selected:req.query.type});
	 }

});

/* GET Device Status page. */
router.get('/status', function(req, res, next) {
	data =[];
	if(typeof appClient != 'undefined'){
		if (req.query.type && current_type != req.query.type  ){
			data =[];
			appClient.unsubscribeToDeviceStatus(current_type, current_id);
			current_type = req.query.type;
			current_id = "";
		}
		if (req.query.id && current_id != req.query.id ){
			data =[];
			appClient.unsubscribeToDeviceStatus(current_type, current_id);
			current_id = req.query.id;
		}

		appClient.subscribeToDeviceStatus(current_type||"+",current_id||"+",0);
		res.render('status', { title: 'IBM Watson IoT Platform' ,data,types,selected:current_type});
	}
	else{
		res.redirect('/');
	}

});
router.get('/status/data', function(req, res, next) {
    res.json(data);
});
router.get('/status/type', function(req, res, next) {
	appClient.getAllDeviceTypes().then (function onSuccess (response) {

				types = _.pluck(response.results,"id");
				res.json(types);

		}, function onError (error) {

			console.log("Fail");
			console.log(error);
			res.json(types)
		}
		);
});
module.exports = router;
<|endoftext|>


<commit_before>'use strict';

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: [
    'app/account.js',
    'app/action.js',
    'app/app.js',
    'app/config.js',
    'app/connection.js',
    'app/log.js',
    'app/rate.js',
    'app/routes.js',
    'app/schema.js',
    'app/scope.js',
    'app/statistic.js',
    'app/user.js',
    'app/import.js'
  ],
  baseUrl: 'http://127.0.0.1:8008/fusio/index.htm',
  capabilities: {
    browserName: 'firefox'
  },
  onPrepare: function() {
    // login
    browser.driver.get('http://127.0.0.1:8008/fusio/index.htm#/login');
    browser.driver.sleep(2000);
    browser.driver.findElement(by.id('username')).sendKeys('Developer');
    browser.driver.findElement(by.id('password')).sendKeys('qf2vX10Ec3wFZHx0K1eL');
    browser.driver.findElement(by.css('button[type="submit"]')).click();

    return browser.driver.wait(function() {
      return browser.driver.getCurrentUrl().then(function(url) {
        return /#\/dashboard/.test(url);
      });
    }, 10000);
  }
};
<commit_msg>check whether username input is present<commit_after>'use strict';

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: [
    'app/account.js',
    'app/action.js',
    'app/app.js',
    'app/config.js',
    'app/connection.js',
    'app/log.js',
    'app/rate.js',
    'app/routes.js',
    'app/schema.js',
    'app/scope.js',
    'app/statistic.js',
    'app/user.js',
    'app/import.js'
  ],
  baseUrl: 'http://127.0.0.1:8008/fusio/index.htm',
  capabilities: {
    browserName: 'firefox'
  },
  onPrepare: function() {
    // login
    browser.driver.get('http://127.0.0.1:8008/fusio/index.htm#/login');

    var usernameInput = browser.driver.findElement(by.id('username'));
    var passwordInput = browser.driver.findElement(by.id('password'));
    var submitButton = browser.driver.findElement(by.css('button[type="submit"]'));

    return usernameInput.isPresent().then(function(){
      usernameInput.sendKeys('Developer');
      passwordInput.sendKeys('qf2vX10Ec3wFZHx0K1eL');
      submitButton.click();

      return browser.driver.wait(function() {
        return browser.driver.getCurrentUrl().then(function(url) {
          return /#\/dashboard/.test(url);
        });
      }, 10000);
    });
  }
};
<|endoftext|>


<commit_before>var express = require('express')
var router = express.Router()
var multer = require('multer')
var dateFormat = require('dateformat')

var db = require('../db')

var storage = multer.diskStorage({
  destination: function (request, file, callback) {
    callback(null, './public/images/blog')
  },
  filename: function (request, file, callback) {
    callback(null, file.originalname)
  }
})
var upload = multer({storage: storage})

// SITE STRUCTURE

// Frontpage - URL - /
router.get('/', function (req, res) {
  db.getRecentBlogs(req.app.get('connection'))
  .then((results) => {
    const viewData = {
      blog: []
    }
    for (var i = 0; i < results.length; i++) {
      const blogEntry = {
        title: results[i].title,
        published_date: dateFormat(results[i].published_date, 'mmmm dd yyyy'),
        image: results[i].image,
        summary: results[i].summary,
        first_name: results[i].first_name,
        last_name: results[i].last_name,
        profile_id: results[i].profile_id,
        tags: results[i].tags,
        slugs: results[i].slugs}
      viewData.blog.push(blogEntry)
    }
    res.render('index', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Blog section - URL - /blog
router.get('/blog', function (req, res) {
  db.getOldBlogs(req.app.get('connection'))
  .then(results => {
    const viewData = {
      blog: results
    }
    res.render('index', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// BLOG ROUTER

// Add blog router
router.get('/blog/add', function (req, res) {
  res.render('addBlog')
})

router.post('/blog/add', upload.single('image'), function (req, res) {
  const title = req.body.title
  const slug = req.body.title.replace(/ /g, '-').toLowerCase()
  const body = req.body.body
  const author = req.body.typeahead
  const summary = req.body.summary
  const status = req.body.status
  const tags = req.body.tags
  const today = new Date()
  const date = dateFormat(today, 'yyyy-mm-dd 08:00:00')
  const image = req.file.path.replace('public', '')

  db.addBlogPost(title, slug, body, author, summary, image, status, date, tags, req.app.get('connection'))
  .then(results => {
    res.redirect(`/blog/${results[0].id}`)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Get blog router
router.get('/blog/:id', function (req, res) {
  var blogSlug = Number(req.params.id)
  db.getBlogPost(blogSlug, req.app.get('connection'))
  .then((result) => {
    const viewData = {
      title: result[0].title,
      body: result[0].body,
      date: dateFormat(result[0].published_date, 'mmmm dd yyyy'),
      image: result[0].image,
      first_name: result[0].first_name,
      last_name: result[0].last_name,
      profile_id: result[0].profile_id,
      tags: result[0].tags
    }
    res.render('blogPost', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Edit blog router
router.get('/blog/:id/edit', function (req, res) {
  const id = req.params.id
  db.getBlogPost(id, req.app.get('connection'))
  .then((result) => {
    res.render('addBlog', result[0])
  })
})

module.exports = router
<commit_msg>Added helper router for author selection in blog form<commit_after>var express = require('express')
var router = express.Router()
var multer = require('multer')
var dateFormat = require('dateformat')

var db = require('../db')

var storage = multer.diskStorage({
  destination: function (request, file, callback) {
    callback(null, './public/images/blog')
  },
  filename: function (request, file, callback) {
    callback(null, file.originalname)
  }
})
var upload = multer({storage: storage})

// SITE STRUCTURE

// Frontpage - URL - /
router.get('/', function (req, res) {
  db.getRecentBlogs(req.app.get('connection'))
  .then((results) => {
    const viewData = {
      blog: []
    }
    for (var i = 0; i < results.length; i++) {
      const blogEntry = {
        title: results[i].title,
        published_date: dateFormat(results[i].published_date, 'mmmm dd yyyy'),
        image: results[i].image,
        summary: results[i].summary,
        first_name: results[i].first_name,
        last_name: results[i].last_name,
        profile_id: results[i].profile_id,
        tags: results[i].tags,
        slugs: results[i].slugs}
      viewData.blog.push(blogEntry)
    }
    res.render('index', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Blog section - URL - /blog
router.get('/blog', function (req, res) {
  db.getOldBlogs(req.app.get('connection'))
  .then(results => {
    const viewData = {
      blog: results
    }
    res.render('index', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// BLOG ROUTER

// Add blog router
router.get('/blog/add', function (req, res) {
  res.render('addBlog')
})

router.post('/blog/add', upload.single('image'), function (req, res) {
  const title = req.body.title
  const slug = req.body.title.replace(/ /g, '-').toLowerCase()
  const body = req.body.body
  const author = req.body.typeahead
  const summary = req.body.summary
  const status = req.body.status
  const tags = req.body.tags
  const today = new Date()
  const date = dateFormat(today, 'yyyy-mm-dd 08:00:00')
  const image = req.file.path.replace('public', '')

  db.addBlogPost(title, slug, body, author, summary, image, status, date, tags, req.app.get('connection'))
  .then(results => {
    res.redirect(`/blog/${results[0].id}`)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Get blog router
router.get('/blog/:id', function (req, res) {
  var blogSlug = Number(req.params.id)
  db.getBlogPost(blogSlug, req.app.get('connection'))
  .then((result) => {
    const viewData = {
      title: result[0].title,
      body: result[0].body,
      date: dateFormat(result[0].published_date, 'mmmm dd yyyy'),
      image: result[0].image,
      first_name: result[0].first_name,
      last_name: result[0].last_name,
      profile_id: result[0].profile_id,
      tags: result[0].tags
    }
    res.render('blogPost', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Edit blog router
router.get('/blog/:id/edit', function (req, res) {
  const id = req.params.id
  db.getBlogPost(id, req.app.get('connection'))
  .then((result) => {
    res.render('addBlog', result[0])
  })
})

//  HELPER ROUTER
router.get('/search', function (req, res) {
  var author = req.query.key
  db.getAuthor(author, req.app.get('connection'))
  .then(function (results) {
    var data = []
    for(prop in results) {
      data.push(results[prop].name)
    }
    res.end(JSON.stringify(data))
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})
module.exports = router
<|endoftext|>


<commit_before>/* Already defined variable (Before the input)
*
* var chart_1_num_day = 5;
* var chart_2_num_day = 15;
*
*/

/* VARIABLES */
    var pie_threshold = 0.05
    var options = {
             series: {  pie: {  show: true,
                                radius: 3/5,
                                combine: {
                                    color: '#999',
                                    threshold: pie_threshold
                                },
                                label: {
                                    show: true,
                                    radius: 1,
                                    formatter: labelFormatter,
                                    background: {
                                        opacity: 0.5,
                                        color: '#000'
                                    }
                                }
                            }
             },
             grid: { hoverable: true, clickable: true },
             legend: { show: false  },
         };

    /* Linked graph - remember the data */
    var plot_data_old = []
    var plot_old = []

/* FUNCTIONS */

function labelFormatter(label, series) {
    return "
"
               + label + "
" + Math.round(series.percent) + "%
";
}

/* Plot, and bind chart listener */
function plot_top_graph(module_name, init){

    /**** Pie Chart ****/

    // moduleCharts is used the decide the url to request data
    var moduleCharts = "size" == module_name ? "providersChart" : ("num" == module_name ? "providersChart" : "moduleCharts");
    var tot_sum = 0; // used to detect elements placed in 'Other' pie's part
    var data_other = []; // used to detect elements placed in 'Other' pie's part

    var createPie = $.getJSON($SCRIPT_ROOT+"/_"+moduleCharts+"?moduleName="+module_name+"&num_day="+chart_1_num_day,
        function(data) {
                  var temp_data_pie = [];
                  for(i=0; i<data.length; i++){
                      if (i==0 && data[0][0] == "passed_days"){ // If there is no data today, take it from the past
                         if (data[0][1] > 0 && data[0][1] < 7){ // If data is [1:6] day(s) old, put the panel in yellow
                             $("#day-"+module_name).text(data[0][1] + " Day(s) ago ");
                             $("#panel-"+module_name).removeClass("panel-green")
                             $("#panel-"+module_name).addClass("panel-yellow")
                         } else if (data[0][1] > 6) { // data old of more than 7 days, put the panel in red
                             $("#day-"+module_name).text(data[0][1] + " Day(s) ago ");
                             $("#panel-"+module_name).removeClass("panel-green")
                             $("#panel-"+module_name).addClass("panel-red")
                         }
                      } else {
                          temp_data_pie.push({label: data[i][0], data: data[i][1]});
                          tot_sum += data[i][1]
                      }
                  }
                  for(i=0; i<temp_data_pie.length; i++){ // Detect element below a certain threshold
                      if (parseInt(temp_data_pie[i].data) / tot_sum < pie_threshold)
                          data_other.push(temp_data_pie[i].label);
                  }

                  $.plot($("#flot-pie-chart-"+module_name), temp_data_pie, options);

                  if (init){ //prevent multiple binding due to the refresh function
                      $("#flot-pie-chart-"+module_name).bind("plotclick", function (event, pos, item) {
                          if (item == null)
                              return;
                          var clicked_label = item.series.label;

                          if (module_name == "size"){ // if Provider pie chart clicked, draw the two bar charts
                              update_bar_chart(moduleCharts, module_name, "#flot-bar-chart-"+module_name, clicked_label,
                                               item.series.color, "%m/%d", false);
                              update_bar_chart(moduleCharts, "num", "#flot-bar-chart-"+"num", clicked_label,
                                               item.series.color, "%m/%d", true);
                          }
                          else if (module_name == "num"){
                              update_bar_chart(moduleCharts, module_name, "#flot-bar-chart-"+module_name, clicked_label,
                                               item.series.color, "%m/%d", false);
                              update_bar_chart(moduleCharts, "size", "#flot-bar-chart-"+"size", clicked_label,
                                               item.series.color, "%m/%d", true);
                          } else {
                              update_bar_chart(moduleCharts, module_name, "#flot-bar-chart-"+module_name, clicked_label,
                                               item.series.color, "%m/%d", true);
                          }
                      });
                  }
    });

    /**** Bar Chart ****/

    function update_bar_chart(chartUrl, module_name, chartID, involved_item, serie_color, timeformat, can_bind){
        var num_day = chart_1_num_day;
        var barOptions = {
            series: {
                bars: { show: true, barWidth: 82800000 },
                lines: { show: false, fill: true }
            },
            xaxis: {
                mode: "time",
                timeformat: timeformat,
                tickSize: [1, 'day'],
                minTickSize: [1, "day"]
            },
            grid: { hoverable: true },
            legend: { show: true,
                      noColumns: 0,
                      position: "nw"
            },
        };

        var plot; // will contain the current plotting object
        /* If part 'Other' has been clicked */
        if (involved_item == "Other"){

            var all_other_temp_data = []; // the data_bar of all series
            var temp_data_bar; //the data_bar associated with one serie
            var promises = []; // Use to plot when everything has been received
            var involved_item

            for(i=0; i<data_other.length; i++){ // Get data for elements summed up in the part 'Other'
                involved_item = data_other[i];
                var request = $.getJSON($SCRIPT_ROOT+"/_"+chartUrl+"?keywordName="+involved_item+"&moduleName="+module_name+"&bar=true"+"&days="+num_day,
                        function(data) {
                            temp_data_bar = []
                            for(i=1; i<data.length; i++){
                                var curr_date = data[i][0].split('/');
                                var offset = (data_other.length/2 - data_other.indexOf(data[0]))*10000000
                                temp_data_bar.push([new Date(curr_date[0], curr_date[1]-1, curr_date[2]).getTime() + offset, data[i][1].toFixed(2)]);
                            }
                            // Insert temp_data_bar in order so that color and alignement correspond for the provider graphs
                            all_other_temp_data.splice(data_other.indexOf(data[0]), 0, [ data[0], temp_data_bar, data_other.indexOf(data[0])]);
                        }
                )
                promises.push(request);
            }

            /* When everything has been received, start the plotting process */
            $.when.apply($, promises).done( function (arg) {
                var dataBar = []

                for(i=0; i<all_other_temp_data.length; i++) //format data for the plot
                    dataBar.push({bars: { barWidth: 8280000, order: all_other_temp_data[i][2] }, label: all_other_temp_data[i][0], data: all_other_temp_data[i][1]});

                plot = $.plot($(chartID), dataBar, {
                    series: {
                    	stack: false,
                    	lines: { show: false, fill: true, steps: false },
                    	bars: { show: true},
                    },
                    xaxis: {
                        mode: "time",
                        timeformat: timeformat,
                        tickSize: [1, 'day'],
                        minTickSize: [1, "day"]
                    },
                    yaxis: {
                        //transform: function (v) { return v < 1 ? v : Math.log(v); }
                    },
                    grid: { hoverable: true },
                    legend: { show: true,
                      noColumns: 1,
                      position: "nw"
                    },
                    tooltip: true,
                    tooltipOpts: { content: "x: %x, y: %y" },
                    colors: ["#72a555", "#ab62c0", "#c57c3c", "#638ccc", "#ca5670"]
                })

                /* rememeber the data for the two graph */
                if (plot_data_old.length>1){ // avoid adding plot_data for previous clicked pie part
                    plot_data_old = [];
                    plot_old = [];
                }
                plot_data_old.push(plot.getData());
                plot_old.push(plot);

                if (can_bind){ // avoid binding two listener for provider graphs
                    binder(module_name);
                    if (module_name == "size") // bind the linked provider graph
                        binder("num");
                    else if (module_name == "num")
                        binder("size");
                }

            });

        } else { // Normal pie's part clicked

            $.getJSON($SCRIPT_ROOT+"/_"+chartUrl+"?keywordName="+involved_item+"&moduleName="+module_name+"&bar=true"+"&days="+num_day,
                function(data) {
                    var temp_data_bar = []
                    for(i=1; i<data.length; i++){
                        var curr_date = data[i][0].split('/');
                        temp_data_bar.push([new Date(curr_date[0], curr_date[1]-1, curr_date[2]).getTime(), data[i][1].toFixed(2)]);
                    }
                    var barData = {
                        label: involved_item,
                        data: temp_data_bar,
                        color: serie_color
                    };
                    plot = $.plot($(chartID), [barData], barOptions);

                    /* rememeber the data for the two graph */
                    if ((module_name == "size") || (module_name == "num")) { // Add only for the provider graph
                        if (plot_data_old.length>1){ // avoid adding plot_data for previous clicked pie part
                            plot_data_old = [];
                            plot_old = [];
                        }
                        plot_data_old.push(plot.getData());
                        plot_old.push(plot);
                    }

                    if (can_bind){ // avoid binding two listener for provider graphs
                        $("#flot-bar-chart-"+module_name).unbind( "plothover.customHandler" );
                        binder(module_name);
                        if (module_name == "size"){ // bind the linked provider graph
                            $("#flot-bar-chart-"+"num").unbind( "plothover.customHandler" );
                            binder("num");
                        }
                        else if (module_name == "num"){
                            $("#flot-bar-chart-"+"size").unbind( "plothover.customHandler" );
                            binder("size");
                        }
                    }
               });
       }

    }; // end update_bar_chart

} // end plot_top_graph

/* Bind a listener to the graph to display the value under the cursor in the approriate div */
function binder(module_name){
    $("#flot-bar-chart-"+module_name).bind("plothover.customHandler", function (event, pos, item) {
       if (item) { // a correct item is hovered
           var x = item.datapoint[0]
           var y = item.datapoint[1]
           var date = new Date(parseInt(x));
           var formated_date = date.getMonth()+'/'+date.getDate();
           var color = item.series.color;
           var color_opac = "rgba" +  color.slice(3, color.length-1)+",0.15)";

           // display the hovered value in the chart div
           $("#tooltip_graph-"+module_name).html(item.series.label + " of " + formated_date + " = " + y+"")
               .css({padding: "2px", width: 'auto', 'background': color_opac , 'border': "3px solid "+color})
               .fadeIn(200);

           /* If provider bar chart hovered, highlight and display associated value */
           if (module_name == "size" || module_name == "num"){
               new_module_name = module_name == "size" ? "num" : "size";

               /* Used to get the corresponding associated value for providers charts */
               var plot_obj = plot_data_old[0]; //contain series

               for(serie=0; serie<plot_obj.length; serie++){ //for all series
                   var data_other = plot_obj[serie].data;

                   for(i=0; i<data_other.length; i++){ //for all datapoints
                       if (data_other[i][0] == date.getTime()){
                           if(y == data_other[i][1]){ // get the correct data and plot object
                               var other_graph_plot = plot_old[1];
                               var curr_data_other = plot_data_old[1][serie].data[i][1];
                           } else {
                               var other_graph_plot = plot_old[0];
                               var curr_data_other = data_other[i][1];
                           }
                           var datapoint = i;
                           var the_serie = serie;
                       }
                   }
               }

               $("#tooltip_graph-"+new_module_name).html(item.series.label + " of " + formated_date + " = " + curr_data_other+"")
                   .css({padding: "2px", width: 'auto', 'background': color_opac, 'border': "3px solid "+color})
                   .fadeIn(200);

               // clean up other highlighted bar

               for(i=0; i<data_other.length; i++)
                   for(s=0; s<plot_obj.length; s++)
                       other_graph_plot.unhighlight(s, i);

               other_graph_plot.highlight(the_serie, datapoint);

           }

       } else {
           // No correct item hovered, clean up the highlighted one
           for(i=0; i<plot_old.length; i++)
               for(j=0; j<plot_data_old[0][0].data.length; j++)
                   plot_old[i].unhighlight(0, j);
       }
    });
}
function plot_finished(module_name){

    }
<commit_msg>Fixed a bug in the hover of provider graph (happened when there was an 'other' in other graphs)<commit_after>/* Already defined variable (Before the input)
*
* var chart_1_num_day = 5;
* var chart_2_num_day = 15;
*
*/

/* VARIABLES */
    var pie_threshold = 0.05
    var options = {
             series: {  pie: {  show: true,
                                radius: 3/5,
                                combine: {
                                    color: '#999',
                                    threshold: pie_threshold
                                },
                                label: {
                                    show: true,
                                    radius: 1,
                                    formatter: labelFormatter,
                                    background: {
                                        opacity: 0.5,
                                        color: '#000'
                                    }
                                }
                            }
             },
             grid: { hoverable: true, clickable: true },
             legend: { show: false  },
         };

    /* Linked graph - remember the data */
    var plot_data_old = []
    var plot_old = []

/* FUNCTIONS */

function labelFormatter(label, series) {
    return "
"
               + label + "
" + Math.round(series.percent) + "%
";
}

/* Plot, and bind chart listener */
function plot_top_graph(module_name, init){

    /**** Pie Chart ****/

    // moduleCharts is used the decide the url to request data
    var moduleCharts = "size" == module_name ? "providersChart" : ("num" == module_name ? "providersChart" : "moduleCharts");
    var tot_sum = 0; // used to detect elements placed in 'Other' pie's part
    var data_other = []; // used to detect elements placed in 'Other' pie's part

    var createPie = $.getJSON($SCRIPT_ROOT+"/_"+moduleCharts+"?moduleName="+module_name+"&num_day="+chart_1_num_day,
        function(data) {
                  var temp_data_pie = [];
                  for(i=0; i<data.length; i++){
                      if (i==0 && data[0][0] == "passed_days"){ // If there is no data today, take it from the past
                         if (data[0][1] > 0 && data[0][1] < 7){ // If data is [1:6] day(s) old, put the panel in yellow
                             $("#day-"+module_name).text(data[0][1] + " Day(s) ago ");
                             $("#panel-"+module_name).removeClass("panel-green")
                             $("#panel-"+module_name).addClass("panel-yellow")
                         } else if (data[0][1] > 6) { // data old of more than 7 days, put the panel in red
                             $("#day-"+module_name).text(data[0][1] + " Day(s) ago ");
                             $("#panel-"+module_name).removeClass("panel-green")
                             $("#panel-"+module_name).addClass("panel-red")
                         }
                      } else {
                          temp_data_pie.push({label: data[i][0], data: data[i][1]});
                          tot_sum += data[i][1]
                      }
                  }
                  for(i=0; i<temp_data_pie.length; i++){ // Detect element below a certain threshold
                      if (parseInt(temp_data_pie[i].data) / tot_sum < pie_threshold)
                          data_other.push(temp_data_pie[i].label);
                  }

                  $.plot($("#flot-pie-chart-"+module_name), temp_data_pie, options);

                  if (init){ //prevent multiple binding due to the refresh function
                      $("#flot-pie-chart-"+module_name).bind("plotclick", function (event, pos, item) {
                          if (item == null)
                              return;
                          var clicked_label = item.series.label;

                          if (module_name == "size"){ // if Provider pie chart clicked, draw the two bar charts
                              update_bar_chart(moduleCharts, module_name, "#flot-bar-chart-"+module_name, clicked_label,
                                               item.series.color, "%m/%d", false);
                              update_bar_chart(moduleCharts, "num", "#flot-bar-chart-"+"num", clicked_label,
                                               item.series.color, "%m/%d", true);
                          }
                          else if (module_name == "num"){
                              update_bar_chart(moduleCharts, module_name, "#flot-bar-chart-"+module_name, clicked_label,
                                               item.series.color, "%m/%d", false);
                              update_bar_chart(moduleCharts, "size", "#flot-bar-chart-"+"size", clicked_label,
                                               item.series.color, "%m/%d", true);
                          } else {
                              update_bar_chart(moduleCharts, module_name, "#flot-bar-chart-"+module_name, clicked_label,
                                               item.series.color, "%m/%d", true);
                          }
                      });
                  }
    });

    /**** Bar Chart ****/

    function update_bar_chart(chartUrl, module_name, chartID, involved_item, serie_color, timeformat, can_bind){
        var num_day = chart_1_num_day;
        var barOptions = {
            series: {
                bars: { show: true, barWidth: 82800000 },
                lines: { show: false, fill: true }
            },
            xaxis: {
                mode: "time",
                timeformat: timeformat,
                tickSize: [1, 'day'],
                minTickSize: [1, "day"]
            },
            grid: { hoverable: true },
            legend: { show: true,
                      noColumns: 0,
                      position: "nw"
            },
        };

        var plot; // will contain the current plotting object
        /* If part 'Other' has been clicked */
        if (involved_item == "Other"){

            var all_other_temp_data = []; // the data_bar of all series
            var temp_data_bar; //the data_bar associated with one serie
            var promises = []; // Use to plot when everything has been received
            var involved_item

            for(i=0; i<data_other.length; i++){ // Get data for elements summed up in the part 'Other'
                involved_item = data_other[i];
                var request = $.getJSON($SCRIPT_ROOT+"/_"+chartUrl+"?keywordName="+involved_item+"&moduleName="+module_name+"&bar=true"+"&days="+num_day,
                        function(data) {
                            temp_data_bar = []
                            for(i=1; i<data.length; i++){
                                var curr_date = data[i][0].split('/');
                                var offset = (data_other.length/2 - data_other.indexOf(data[0]))*10000000
                                temp_data_bar.push([new Date(curr_date[0], curr_date[1]-1, curr_date[2]).getTime() + offset, data[i][1].toFixed(2)]);
                            }
                            // Insert temp_data_bar in order so that color and alignement correspond for the provider graphs
                            all_other_temp_data.splice(data_other.indexOf(data[0]), 0, [ data[0], temp_data_bar, data_other.indexOf(data[0])]);
                        }
                )
                promises.push(request);
            }

            /* When everything has been received, start the plotting process */
            $.when.apply($, promises).done( function (arg) {
                var dataBar = []

                for(i=0; i<all_other_temp_data.length; i++) //format data for the plot
                    dataBar.push({bars: { barWidth: 8280000, order: all_other_temp_data[i][2] }, label: all_other_temp_data[i][0], data: all_other_temp_data[i][1]});

                plot = $.plot($(chartID), dataBar, {
                    series: {
                    	stack: false,
                    	lines: { show: false, fill: true, steps: false },
                    	bars: { show: true},
                    },
                    xaxis: {
                        mode: "time",
                        timeformat: timeformat,
                        tickSize: [1, 'day'],
                        minTickSize: [1, "day"]
                    },
                    yaxis: {
                        //transform: function (v) { return v < 1 ? v : Math.log(v); }
                    },
                    grid: { hoverable: true },
                    legend: { show: true,
                      noColumns: 1,
                      position: "nw"
                    },
                    tooltip: true,
                    tooltipOpts: { content: "x: %x, y: %y" },
                    colors: ["#72a555", "#ab62c0", "#c57c3c", "#638ccc", "#ca5670"]
                })

                /* rememeber the data for the two provider graph */
                if (chartUrl == "providersChart"){
                    if (plot_data_old.length>1){ // avoid adding plot_data for previous clicked pie part
                        plot_data_old = [];
                        plot_old = [];
                    }
                    plot_data_old.push(plot.getData());
                    plot_old.push(plot);
                }

                if (can_bind){ // avoid binding two listener for provider graphs
                    binder(module_name);
                    if (module_name == "size") // bind the linked provider graph
                        binder("num");
                    else if (module_name == "num")
                        binder("size");
                }

            });

        } else { // Normal pie's part clicked

            $.getJSON($SCRIPT_ROOT+"/_"+chartUrl+"?keywordName="+involved_item+"&moduleName="+module_name+"&bar=true"+"&days="+num_day,
                function(data) {
                    var temp_data_bar = []
                    for(i=1; i<data.length; i++){
                        var curr_date = data[i][0].split('/');
                        temp_data_bar.push([new Date(curr_date[0], curr_date[1]-1, curr_date[2]).getTime(), data[i][1].toFixed(2)]);
                    }
                    var barData = {
                        label: involved_item,
                        data: temp_data_bar,
                        color: serie_color
                    };
                    plot = $.plot($(chartID), [barData], barOptions);

                    /* rememeber the data for the two graph */
                    if ((module_name == "size") || (module_name == "num")) { // Add only for the provider graph
                        if (plot_data_old.length>1){ // avoid adding plot_data for previous clicked pie part
                            plot_data_old = [];
                            plot_old = [];
                        }
                        plot_data_old.push(plot.getData());
                        plot_old.push(plot);
                    }

                    if (can_bind){ // avoid binding two listener for provider graphs
                        $("#flot-bar-chart-"+module_name).unbind( "plothover.customHandler" );
                        binder(module_name);
                        if (module_name == "size"){ // bind the linked provider graph
                            $("#flot-bar-chart-"+"num").unbind( "plothover.customHandler" );
                            binder("num");
                        }
                        else if (module_name == "num"){
                            $("#flot-bar-chart-"+"size").unbind( "plothover.customHandler" );
                            binder("size");
                        }
                    }
               });
       }

    }; // end update_bar_chart

} // end plot_top_graph

/* Bind a listener to the graph to display the value under the cursor in the approriate div */
function binder(module_name){
    $("#flot-bar-chart-"+module_name).bind("plothover.customHandler", function (event, pos, item) {
       if (item) { // a correct item is hovered
           var x = item.datapoint[0]
           var y = item.datapoint[1]
           var date = new Date(parseInt(x));
           var formated_date = date.getMonth()+'/'+date.getDate();
           var color = item.series.color;
           var color_opac = "rgba" +  color.slice(3, color.length-1)+",0.15)";

           // display the hovered value in the chart div
           $("#tooltip_graph-"+module_name).html(item.series.label + " of " + formated_date + " = " + y+"")
               .css({padding: "2px", width: 'auto', 'background': color_opac , 'border': "3px solid "+color})
               .fadeIn(200);

           /* If provider bar chart hovered, highlight and display associated value */
           if (module_name == "size" || module_name == "num"){
               new_module_name = module_name == "size" ? "num" : "size";

               /* Used to get the corresponding associated value for providers charts */
               var plot_obj = plot_data_old[0]; //contain series

               for(serie=0; serie<plot_obj.length; serie++){ //for all series
                   var data_other = plot_obj[serie].data;

                   for(i=0; i<data_other.length; i++){ //for all datapoints
                       if (data_other[i][0] == date.getTime()){
                           if(y == data_other[i][1]){ // get the correct data and plot object
                               var other_graph_plot = plot_old[1];
                               var curr_data_other = plot_data_old[1][serie].data[i][1];
                           } else {
                               var other_graph_plot = plot_old[0];
                               var curr_data_other = data_other[i][1];
                           }
                           var datapoint = i;
                           var the_serie = serie;
                       }
                   }
               }

               $("#tooltip_graph-"+new_module_name).html(item.series.label + " of " + formated_date + " = " + curr_data_other+"")
                   .css({padding: "2px", width: 'auto', 'background': color_opac, 'border': "3px solid "+color})
                   .fadeIn(200);

               // clean up other highlighted bar

               for(i=0; i<data_other.length; i++)
                   for(s=0; s<plot_obj.length; s++)
                       other_graph_plot.unhighlight(s, i);

               other_graph_plot.highlight(the_serie, datapoint);

           }

       } else {
           // No correct item hovered, clean up the highlighted one
           for(i=0; i<plot_old.length; i++)
               for(j=0; j<plot_data_old[0][0].data.length; j++)
                   plot_old[i].unhighlight(0, j);
       }
    });
}
function plot_finished(module_name){

    }
<|endoftext|>


<commit_before>"use strict";

// initialize Hoodie
var hoodie = new Hoodie();

// Poker
// =====
var Card = React.createClass({
  propTypes: {
    value: React.PropTypes.number
  },

  onClick: function(event){
    this.props.onSelect(this.props.value);
  },

  render: function(){
    var value = this.props.isVisible ? this.props.value : '?'
    return
{value}

  }
});

var User = React.createClass({
  render: function(){
    return
{this.props.name}

  }
});

var PlayedCard = React.createClass({
  propTypes: {
    value: React.PropTypes.number,
    userName: React.PropTypes.string,
    isVisible: React.PropTypes.boolean
  },

  render: function(){
    return

      <Card value={this.props.value} isVisible={this.props.isVisible} />
      <User name={this.props.userName} />

  }
});

var Deck = React.createClass({
  render: function(){
    var cards = [1, 2, 3, 4, 5, 8, 13, 21].map(function(cardValue){
      return <Card value={cardValue} key={cardValue} onSelect={this.props.onSelect} isVisible={true} />
    }.bind(this));

    return
{cards}

  }
});

var Table = React.createClass({
  restartRound: function(){
    hoodie.store.updateAll('estimates', {value: null})
  },

  propTypes: {
    estimates: React.PropTypes.array,
    currentUserName: React.PropTypes.string
  },

  render: function(){
    var playedCards = this.props.estimates.map(function(playedCard){
      var isVisible = this.props.currentUserName == playedCard.id;

      return <PlayedCard value={playedCard.value} userName={playedCard.id} key={playedCard.id} isVisible={isVisible} />
    }.bind(this));

    return

        <button className="button-restart" onClick={this.restartRound}>Restart</button>

{playedCards}

  }
});

var SignInForm = React.createClass({
  onSubmit: function(event){
    event.preventDefault();

    var userName = React.findDOMNode(this.refs.userName).value;
    this.props.onSignIn(userName);
  },

  render: function(){
    return

      <form onSubmit={this.onSubmit}>
        <input ref="userName" autofocus />
        <button type="submit">Sign In</button>
      </form>

  }
});

var PokerApp = React.createClass({
  getInitialState: function(){
    return {
      currentUserName: null,
      estimates: []
    }
  },

  signIn: function(userName){
    this.setState({currentUserName: userName});

    hoodie.store.add('estimates', {id: userName, value: null});
  },

  setEstimates: function(){
    hoodie.store.findAll('estimates').then(function(allEstimates) {
      this.setState({estimates: allEstimates});
    }.bind(this));
  },

  selectCard: function(value){
    hoodie.store.updateOrAdd('estimates', this.state.currentUserName, {value: value})
  },

  componentDidMount: function(){
    hoodie.store.on('change', function() {
      this.setEstimates();
    }.bind(this));

    hoodie.account.signIn('poker', 'poker').then(function() {
      this.setEstimates();
    }.bind(this));
  },

  render: function(){
    if (this.state.currentUserName === null) {
      return

        <SignInForm onSignIn={this.signIn} />

    } else {
      return

Hello {this.state.currentUserName}

        <Deck onSelect={this.selectCard} />

    };
  }
});

React.render(<PokerApp />, pokerApp);
<commit_msg>feat(cards): show all values when all estimates are in<commit_after>"use strict";

// initialize Hoodie
var hoodie = new Hoodie();

// Poker
// =====
var Card = React.createClass({
  propTypes: {
    value: React.PropTypes.number
  },

  onClick: function(event){
    this.props.onSelect(this.props.value);
  },

  render: function(){
    var value = this.props.isVisible ? this.props.value : '?'
    return
{value}

  }
});

var User = React.createClass({
  render: function(){
    return
{this.props.name}

  }
});

var PlayedCard = React.createClass({
  propTypes: {
    value: React.PropTypes.number,
    userName: React.PropTypes.string
  },

  render: function(){
    return

      <Card value={this.props.value} isVisible={this.props.isVisible} />
      <User name={this.props.userName} />

  }
});

var Deck = React.createClass({
  render: function(){
    var cards = [1, 2, 3, 4, 5, 8, 13, 21].map(function(cardValue){
      return <Card value={cardValue} key={cardValue} onSelect={this.props.onSelect} isVisible={true} />
    }.bind(this));

    return
{cards}

  }
});

var Table = React.createClass({
  restartRound: function(){
    hoodie.store.updateAll('estimates', {value: null})
  },

  propTypes: {
    estimates: React.PropTypes.array,
    currentUserName: React.PropTypes.string,
  },

  render: function(){
    var isFinished = this.props.estimates.every(function(playedCard){
      return playedCard.value > 0
    });

    var playedCards = this.props.estimates.map(function(playedCard){
      var isVisible = isFinished || this.props.currentUserName == playedCard.id;

      return <PlayedCard value={playedCard.value} userName={playedCard.id} key={playedCard.id} isVisible={isVisible} />
    }.bind(this));

    return

        <button className="button-restart" onClick={this.restartRound}>Restart</button>

{playedCards}

  }
});

var SignInForm = React.createClass({
  onSubmit: function(event){
    event.preventDefault();

    var userName = React.findDOMNode(this.refs.userName).value;
    this.props.onSignIn(userName);
  },

  render: function(){
    return

      <form onSubmit={this.onSubmit}>
        <input ref="userName" autofocus />
        <button type="submit">Sign In</button>
      </form>

  }
});

var PokerApp = React.createClass({
  getInitialState: function(){
    return {
      currentUserName: null,
      estimates: []
    }
  },

  signIn: function(userName){
    this.setState({currentUserName: userName});

    hoodie.store.add('estimates', {id: userName, value: null});
  },

  setEstimates: function(){
    hoodie.store.findAll('estimates').then(function(allEstimates) {
      this.setState({estimates: allEstimates});
    }.bind(this));
  },

  selectCard: function(value){
    hoodie.store.updateOrAdd('estimates', this.state.currentUserName, {value: value})
  },

  componentDidMount: function(){
    hoodie.store.on('change', function() {
      this.setEstimates();
    }.bind(this));

    hoodie.account.signIn('poker', 'poker').then(function() {
      this.setEstimates();
    }.bind(this));
  },

  render: function(){
    if (this.state.currentUserName === null) {
      return

        <SignInForm onSignIn={this.signIn} />

    } else {
      return

Hello {this.state.currentUserName}

        <Deck onSelect={this.selectCard} />

    };
  }
});

React.render(<PokerApp />, pokerApp);
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var database = require('../database');

/* GET home page. */
database.connectDb(function(err) {
  if (err) throw err;
  var db = database.getDb();
  db.collection('items').find({}).toArray(function(err, result) {
    router.get('/', function(req, res, next) {
      res.render('index', {
        title: 'Axisesio',
        latest: getItem(result, 'completed'),
        upcoming: getItem(result, 'in progress')
      });
    });
  });
});

function getItem(data, status) {
  var sortedData = data.sort(function(a,b) {
    a = a.Date.split('/').reverse().join('');
    b = b.Date.split('/').reverse().join('');
    return a > b ? 1 : a < b ? -1 : 0;
  });
  sortedData = sortedData.reverse();
  for (var i = 0; i < sortedData.length; i++) {
    if (sortedData[i].Status.toLowerCase() === status) {
      console.log(sortedData[i]);
      return sortedData[i];
    }
  }
}

module.exports = router;<commit_msg>Removed console helper lines<commit_after>var express = require('express');
var router = express.Router();
var database = require('../database');

/* GET home page. */
database.connectDb(function(err) {
  if (err) throw err;
  var db = database.getDb();
  db.collection('items').find({}).toArray(function(err, result) {
    router.get('/', function(req, res, next) {
      res.render('index', {
        title: 'Axisesio',
        latest: getItem(result, 'completed'),
        upcoming: getItem(result, 'in progress')
      });
    });
  });
});

function getItem(data, status) {
  var sortedData = data.sort(function(a,b) {
    a = a.Date.split('/').reverse().join('');
    b = b.Date.split('/').reverse().join('');
    return a > b ? 1 : a < b ? -1 : 0;
  });
  sortedData = sortedData.reverse();
  for (var i = 0; i < sortedData.length; i++) {
    if (sortedData[i].Status.toLowerCase() === status) {
      return sortedData[i];
    }
  }
}

module.exports = router;<|endoftext|>