<commit_before>var gameState = {
    votedScore: null,
    objectiveScore: null,
    currentDance: null,
    currentDanceIndex: 0,
    isKeyDown: 0,
    maxScore: 20,
    minScore: 0,
    scoreArrow: null,
    voteBar: null,
    voteMoveWidth: null
};

var rightKey;
var leftKey;

var dancing = function(game) {
    return {
        preload: function() {},

        create: function() {
            console.log("Create called in ", game.state.current);

            drawBackground();
            drawJudges();
            constructDancer();

            //draw the score bar
            gameState.voteBar = game.add.sprite(200, 500, 'voteScoreBar');
            gameState.voteBar.scale.setTo(0.5, 0.75);
            gameState.scoreArrow = game.add.sprite(200, 505, 'meterArrow');
            gameState.scoreArrow.scale.setTo(0.25, 0.36);

            gameState.votedScore = (gameState.maxScore / 2);
            gameState.voteMoveWidth = gameState.voteBar.width / gameState.maxScore;

            repositionScoreBar();

            rightKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
            rightKey.onDown.add(function() {
                if (gameState.votedScore < gameState.maxScore) {
                    gameState.votedScore++;
                    repositionScoreBar();
                }

            });
            leftKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
            leftKey.onDown.add(function() {
                if (gameState.votedScore > gameState.minScore) {
                    gameState.votedScore--;
                    repositionScoreBar();
                }
            });
            gameState.currentDance = createDance();
            gameState.currentDanceIndex = 0;
            var style = {
                font: "32px Arial",
                fill: "#ff0044",
                wordWrap: false,
                align: "center",
            };
            this.danceLabel = game.add.text(10, 460, "Dancing!", style);
            game.time.events.loop(Phaser.Timer.SECOND * 3, function() {
                gameState.currentDanceIndex++;
                    if (gameState.currentDanceIndex > gameState.currentDance.length - 1) {
                        game.state.start("judge_Result");
                    }
            }, this);
            scoreDance();
        },

        update: function() {
            this.danceLabel.text = gameState.currentDance[gameState.currentDanceIndex].name;

            gameState.currentDance.text = gameState.currentDance.name;
        },

    };
};

function constructDancer() {
    var dancer = {};
    var dancerBody = game.add.group();
    dancer.wholeBody = dancerBody;
    dancer.torso = makeBodyPart('dancer-torso', 0, 0, dancerBody);
    dancer.head = makeBodyPart('dancer-head', 0, -80, dancerBody);
    dancer.leftArm = makeBodyPart('dancer-leftArm', -30, -20, dancerBody);
    dancer.rightArm = makeBodyPart('dancer-rightArm', 30, -20, dancerBody);
    dancer.leftHand = makeBodyPart('dancer-leftHand', -30, 30, dancerBody);
    dancer.rightHand = makeBodyPart('dancer-rightHand', 30, 30, dancerBody);
    dancer.leftFoot = makeBodyPart('dancer-leftFoot', -20, 140, dancerBody);
    dancer.rightFoot = makeBodyPart('dancer-rightFoot', 20, 140, dancerBody);
    dancer.leftLeg = makeBodyPart('dancer-leftLeg', -20, 80, dancerBody);
    dancer.rightLeg = makeBodyPart('dancer-rightLeg', 20, 80, dancerBody);
    return dancer;
}

function makeBodyPart(spriteName, offsetX, offsetY, group) {
    var sprite = game.add.sprite(200 + offsetX, 200 + offsetY, spriteName);
    sprite.anchor.setTo(0.5, 0.5);
    group.add(sprite);
    return sprite;
}

function drawBackground() {
    sprite = game.add.tileSprite(0, 200, 800, 300, 'floor');
}

function drawJudges() {
    tmpXJudgePadder = 30;
    tmpXJudgePosition = 0;
    judge2 = game.add.sprite(tmpXJudgePosition, 0, 'judge2');
    tmpXJudgePosition = tmpXJudgePosition + judge2.width + tmpXJudgePadder;
    draftJudge = game.add.sprite(tmpXJudgePosition, 0, 'draftJudge');
    tmpXJudgePosition = tmpXJudgePosition + draftJudge.width + tmpXJudgePadder;
    judge1 = game.add.sprite(tmpXJudgePosition, 0, 'judge1');
    tmpXJudgePosition = tmpXJudgePosition + judge1.width + tmpXJudgePadder * 2;
    russianJudge = game.add.sprite(tmpXJudgePosition, 0, 'russianJudge');

}

function repositionScoreBar() {
    //console.log("Current votedScore: ", gameState.votedScore);
    gameState.scoreArrow.x = (gameState.voteMoveWidth * (gameState.votedScore)) - (gameState.scoreArrow.width / 2) + (gameState.voteBar.x);
}

function scoreDance() {
    gameState.objectiveScore = 0;
    for (var i in gameState.currentDance) {
        gameState.objectiveScore = gameState.objectiveScore + gameState.currentDance[i].score();
    }
}

game.state.add('dancing', dancing);
<commit_msg>Moving the dancer along the screen as he dances<commit_after>var gameState = {
    votedScore: null,
    objectiveScore: null,
    currentDance: null,
    currentDancer: null,
    currentDanceIndex: 0,
    isKeyDown: 0,
    maxScore: 20,
    minScore: 0,
    scoreArrow: null,
    voteBar: null,
    voteMoveWidth: null
};

var rightKey;
var leftKey;

var dancing = function(game) {
    return {
        preload: function() {},

        create: function() {
            console.log("Create called in ", game.state.current);

            drawBackground();
            drawJudges();
            constructDancer();

            //draw the score bar
            gameState.voteBar = game.add.sprite(200, 500, 'voteScoreBar');
            gameState.voteBar.scale.setTo(0.5, 0.75);
            gameState.scoreArrow = game.add.sprite(200, 505, 'meterArrow');
            gameState.scoreArrow.scale.setTo(0.25, 0.36);

            gameState.votedScore = (gameState.maxScore / 2);
            gameState.voteMoveWidth = gameState.voteBar.width / gameState.maxScore;

            repositionScoreBar();

            rightKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
            rightKey.onDown.add(function() {
                if (gameState.votedScore < gameState.maxScore) {
                    gameState.votedScore++;
                    repositionScoreBar();
                }

            });
            leftKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
            leftKey.onDown.add(function() {
                if (gameState.votedScore > gameState.minScore) {
                    gameState.votedScore--;
                    repositionScoreBar();
                }
            });
            gameState.currentDance = createDance();
            gameState.currentDanceIndex = 0;
            var style = {
                font: "32px Arial",
                fill: "#ff0044",
                wordWrap: false,
                align: "center",
            };
            this.danceLabel = game.add.text(10, 460, "Dancing!", style);
            game.time.events.loop(Phaser.Timer.SECOND * 3, function() {
              gameState.currentDanceIndex++;
                  if (gameState.currentDanceIndex > gameState.currentDance.length - 1) {
                      game.state.start("judge_Result");
                  }
                gameState.currentDancer.x = gameState.currentDancer.x + (800/5) - (gameState.currentDancer.width / 2);
            }, this);
            scoreDance();
        },

        update: function() {
            this.danceLabel.text = gameState.currentDance[gameState.currentDanceIndex].name;

            gameState.currentDance.text = gameState.currentDance.name;
        },

    };
};

function constructDancer() {
    var dancer = {};
    gameState.currentDancer = game.add.group();
    dancer.wholeBody = gameState.currentDancer;
    dancer.torso = makeBodyPart('dancer-torso', 0, 0, gameState.currentDancer);
    dancer.head = makeBodyPart('dancer-head', 0, -80, gameState.currentDancer);
    dancer.leftArm = makeBodyPart('dancer-leftArm', -30, -20, gameState.currentDancer);
    dancer.rightArm = makeBodyPart('dancer-rightArm', 30, -20, gameState.currentDancer);
    dancer.leftHand = makeBodyPart('dancer-leftHand', -30, 30, gameState.currentDancer);
    dancer.rightHand = makeBodyPart('dancer-rightHand', 30, 30, gameState.currentDancer);
    dancer.leftFoot = makeBodyPart('dancer-leftFoot', -20, 140, gameState.currentDancer);
    dancer.rightFoot = makeBodyPart('dancer-rightFoot', 20, 140, gameState.currentDancer);
    dancer.leftLeg = makeBodyPart('dancer-leftLeg', -20, 80, gameState.currentDancer);
    dancer.rightLeg = makeBodyPart('dancer-rightLeg', 20, 80, gameState.currentDancer);
    return dancer;
}

function makeBodyPart(spriteName, offsetX, offsetY, group) {
    var sprite = game.add.sprite(200 + offsetX, 200 + offsetY, spriteName);
    sprite.anchor.setTo(0.5, 0.5);
    group.add(sprite);
    return sprite;
}

function drawBackground() {
    sprite = game.add.tileSprite(0, 200, 800, 300, 'floor');
}

function drawJudges() {
    tmpXJudgePadder = 30;
    tmpXJudgePosition = 0;
    judge2 = game.add.sprite(tmpXJudgePosition, 0, 'judge2');
    tmpXJudgePosition = tmpXJudgePosition + judge2.width + tmpXJudgePadder;
    draftJudge = game.add.sprite(tmpXJudgePosition, 0, 'draftJudge');
    tmpXJudgePosition = tmpXJudgePosition + draftJudge.width + tmpXJudgePadder;
    judge1 = game.add.sprite(tmpXJudgePosition, 0, 'judge1');
    tmpXJudgePosition = tmpXJudgePosition + judge1.width + tmpXJudgePadder * 2;
    russianJudge = game.add.sprite(tmpXJudgePosition, 0, 'russianJudge');

}

function repositionScoreBar() {
    //console.log("Current votedScore: ", gameState.votedScore);
    gameState.scoreArrow.x = (gameState.voteMoveWidth * (gameState.votedScore)) - (gameState.scoreArrow.width / 2) + (gameState.voteBar.x);
}

function scoreDance() {
    gameState.objectiveScore = 0;
    for (var i in gameState.currentDance) {
        gameState.objectiveScore = gameState.objectiveScore + gameState.currentDance[i].score();
    }
}

game.state.add('dancing', dancing);
<|endoftext|>


<commit_before>// SIDEBAR
// -----------------------------------

(function(window, document, $, undefined){

  var $win;
  var $html;
  var $body;
  var $sidebar;
  var mq;

  $(function(){

    $win     = $(window);
    $html    = $('html');
    $body    = $('body');
    $sidebar = $('.sidebar');
    mq       = APP_MEDIAQUERY;

    // AUTOCOLLAPSE ITEMS
    // -----------------------------------

    var sidebarCollapse = $sidebar.find('.collapse');
    sidebarCollapse.on('show.bs.collapse', function(event){

      event.stopPropagation();
      if ( $(this).parents('.collapse').length === 0 )
        sidebarCollapse.filter('.in').collapse('hide');

    });

    // SIDEBAR ACTIVE STATE
    // -----------------------------------

    // Find current active item
    var currentItem = $('.sidebar .active').parents('li');

    // hover mode don't try to expand active collapse
    if ( ! useAsideHover() )
      currentItem
        .addClass('active')     // activate the parent
        .children('.collapse')  // find the collapse
        .collapse('show');      // and show it

    // remove this if you use only collapsible sidebar items
    $sidebar.find('li > a + ul').on('show.bs.collapse', function (e) {
      if( useAsideHover() ) e.preventDefault();
    });

    // SIDEBAR COLLAPSED ITEM HANDLER
    // -----------------------------------

    var eventName = isTouch() ? 'click' : 'mouseenter' ;
    var subNav = $();
    $sidebar.on( eventName, '.nav > li', function() {

      if( isSidebarCollapsed() || useAsideHover() ) {

        subNav.trigger('mouseleave');
        subNav = toggleMenuItem( $(this) );

        // Used to detect click and touch events outside the sidebar
        sidebarAddBackdrop();
      }

    });

    var sidebarAnyclickClose = $sidebar.data('sidebarAnyclickClose');

    // Allows to close
    if ( typeof sidebarAnyclickClose !== 'undefined' ) {

      $('.wrapper').on('click.sidebar', function(e){
        // don't check if sidebar not visible
        if( ! $body.hasClass('aside-toggled')) return;

        var $target = $(e.target);
        if( ! $target.parents('.aside').length && // if not child of sidebar
            ! $target.is('#user-block-toggle') && // user block toggle anchor
            ! $target.parent().is('#user-block-toggle') // user block toggle icon
          ) {
                $body.removeClass('aside-toggled');
        }

      });
    }

  });

  function sidebarAddBackdrop() {
    var $backdrop = $('<div/>', { 'class': 'dropdown-backdrop'} );
    $backdrop.insertAfter('.aside').on("click mouseenter", function () {
      removeFloatingNav();
    });
  }

  // Open the collapse sidebar submenu items when on touch devices
  // - desktop only opens on hover
  function toggleTouchItem($element){
    $element
      .siblings('li')
      .removeClass('open')
      .end()
      .toggleClass('open');
  }

  // Handles hover to open items under collapsed menu
  // -----------------------------------
  function toggleMenuItem($listItem) {

    removeFloatingNav();

    var ul = $listItem.children('ul');

    if( !ul.length ) return $();
    if( $listItem.hasClass('open') ) {
      toggleTouchItem($listItem);
      return $();
    }

    var $aside = $('.aside');
    var $asideInner = $('.aside-inner'); // for top offset calculation
    // float aside uses extra padding on aside
    var mar = parseInt( $asideInner.css('padding-top'), 0) + parseInt( $aside.css('padding-top'), 0);

    var subNav = ul.clone().appendTo( $aside );

    toggleTouchItem($listItem);

    var itemTop = ($listItem.position().top + mar) - $sidebar.scrollTop();
    var vwHeight = $win.height();

    subNav
      .addClass('nav-floating')
      .css({
        position: isFixed() ? 'fixed' : 'absolute',
        top:      itemTop,
        bottom:   (subNav.outerHeight(true) + itemTop > vwHeight) ? 0 : 'auto'
      });

    subNav.on('mouseleave', function() {
      toggleTouchItem($listItem);
      subNav.remove();
    });

    return subNav;
  }

  function removeFloatingNav() {
    $('.sidebar-subnav.nav-floating').remove();
    $('.dropdown-backdrop').remove();
    $('.sidebar li.open').removeClass('open');
  }

  function isTouch() {
    return $html.hasClass('touch');
  }
  function isSidebarCollapsed() {
    return $body.hasClass('aside-collapsed');
  }
  function isSidebarToggled() {
    return $body.hasClass('aside-toggled');
  }
  function isMobile() {
    return $win.width() < mq.tablet;
  }
  function isFixed(){
    return $body.hasClass('layout-fixed');
  }
  function useAsideHover() {
    return $body.hasClass('aside-hover');
  }

})(window, document, window.jQuery);<commit_msg>Clean up newlines<commit_after>// SIDEBAR
// -----------------------------------

(function(window, document, $, undefined){

  var $win;
  var $html;
  var $body;
  var $sidebar;
  var mq;

  $(function(){

    $win     = $(window);
    $html    = $('html');
    $body    = $('body');
    $sidebar = $('.sidebar');
    mq       = APP_MEDIAQUERY;

    // AUTOCOLLAPSE ITEMS
    // -----------------------------------

    var sidebarCollapse = $sidebar.find('.collapse');
    sidebarCollapse.on('show.bs.collapse', function(event){

      event.stopPropagation();
      if ( $(this).parents('.collapse').length === 0 )
        sidebarCollapse.filter('.in').collapse('hide');

    });

    // SIDEBAR ACTIVE STATE
    // -----------------------------------

    // Find current active item
    var currentItem = $('.sidebar .active').parents('li');

    // hover mode don't try to expand active collapse
    if ( ! useAsideHover() )
      currentItem
        .addClass('active')     // activate the parent
        .children('.collapse')  // find the collapse
        .collapse('show');      // and show it

    // remove this if you use only collapsible sidebar items
    $sidebar.find('li > a + ul').on('show.bs.collapse', function (e) {
      if( useAsideHover() ) e.preventDefault();
    });

    // SIDEBAR COLLAPSED ITEM HANDLER
    // -----------------------------------

    var eventName = isTouch() ? 'click' : 'mouseenter' ;
    var subNav = $();
    $sidebar.on( eventName, '.nav > li', function() {

      if( isSidebarCollapsed() || useAsideHover() ) {

        subNav.trigger('mouseleave');
        subNav = toggleMenuItem( $(this) );

        // Used to detect click and touch events outside the sidebar
        sidebarAddBackdrop();
      }

    });

    var sidebarAnyclickClose = $sidebar.data('sidebarAnyclickClose');

    // Allows to close
    if ( typeof sidebarAnyclickClose !== 'undefined' ) {

      $('.wrapper').on('click.sidebar', function(e){
        // don't check if sidebar not visible
        if( ! $body.hasClass('aside-toggled')) return;

        var $target = $(e.target);
        if( ! $target.parents('.aside').length && // if not child of sidebar
            ! $target.is('#user-block-toggle') && // user block toggle anchor
            ! $target.parent().is('#user-block-toggle') // user block toggle icon
          ) {
                $body.removeClass('aside-toggled');
        }

      });
    }

  });

  function sidebarAddBackdrop() {
    var $backdrop = $('<div/>', { 'class': 'dropdown-backdrop'} );
    $backdrop.insertAfter('.aside').on("click mouseenter", function () {
      removeFloatingNav();
    });
  }

  // Open the collapse sidebar submenu items when on touch devices
  // - desktop only opens on hover
  function toggleTouchItem($element){
    $element
      .siblings('li')
      .removeClass('open')
      .end()
      .toggleClass('open');
  }

  // Handles hover to open items under collapsed menu
  // -----------------------------------
  function toggleMenuItem($listItem) {

    removeFloatingNav();

    var ul = $listItem.children('ul');

    if( !ul.length ) return $();
    if( $listItem.hasClass('open') ) {
      toggleTouchItem($listItem);
      return $();
    }

    var $aside = $('.aside');
    var $asideInner = $('.aside-inner'); // for top offset calculation
    // float aside uses extra padding on aside
    var mar = parseInt( $asideInner.css('padding-top'), 0) + parseInt( $aside.css('padding-top'), 0);

    var subNav = ul.clone().appendTo( $aside );

    toggleTouchItem($listItem);

    var itemTop = ($listItem.position().top + mar) - $sidebar.scrollTop();
    var vwHeight = $win.height();

    subNav
      .addClass('nav-floating')
      .css({
        position: isFixed() ? 'fixed' : 'absolute',
        top:      itemTop,
        bottom:   (subNav.outerHeight(true) + itemTop > vwHeight) ? 0 : 'auto'
      });

    subNav.on('mouseleave', function() {
      toggleTouchItem($listItem);
      subNav.remove();
    });

    return subNav;
  }

  function removeFloatingNav() {
    $('.sidebar-subnav.nav-floating').remove();
    $('.dropdown-backdrop').remove();
    $('.sidebar li.open').removeClass('open');
  }

  function isTouch() {
    return $html.hasClass('touch');
  }
  function isSidebarCollapsed() {
    return $body.hasClass('aside-collapsed');
  }
  function isSidebarToggled() {
    return $body.hasClass('aside-toggled');
  }
  function isMobile() {
    return $win.width() < mq.tablet;
  }
  function isFixed(){
    return $body.hasClass('layout-fixed');
  }
  function useAsideHover() {
    return $body.hasClass('aside-hover');
  }

})(window, document, window.jQuery);

<|endoftext|>


<commit_before>var redis = require('redis');
var url = require('url');

/*
 * GET admin page.
 */

exports.admin = function(req, res){
  redis.client.multi().keys('messages.*', function (err, replies) {
    // NOTE: code in this callback is NOT atomic
    // this only happens after the the .exec call finishes.]

    redis.client.mget(replies, function(err, result) {
      var json = new Array();
      for (var i = 0; i < result.length; i++){
        json.push(result[i])
      }
      res.render('index', {guestMessages:json});
    });
  })
  .exec(function (err, replies) {
    replies.forEach(function (reply, index) {

    });
  });
};

exports.approve = function(req, res) {
  var message = redis.client.get("messages." + req.query.id);
  message.approved = true;
  res.send(redis.client.set("messages." + req.query.id, message));
}

exports.unapprove = function(req, res) {
  var message = redis.client.get("messages." + req.query.id);
  message.approved = false;
  res.send(redis.client.set("messages." + req.query.id, message));
}<commit_msg>Fix again<commit_after>var redis = require('redis');
var url = require('url');

/*
 * GET admin page.
 */

exports.admin = function(req, res){
  redis.client.multi().keys('messages.*', function (err, replies) {
    // NOTE: code in this callback is NOT atomic
    // this only happens after the the .exec call finishes.]

    redis.client.mget(replies, function(err, result) {
      var json = new Array();
      for (var i = 0; i < result.length; i++){
        json.push(result[i])
      }
      res.render('admin', {guestMessages:json});
    });
  })
  .exec(function (err, replies) {
    replies.forEach(function (reply, index) {

    });
  });
};

exports.approve = function(req, res) {
  var message = redis.client.get("messages." + req.query.id);
  message.approved = true;
  res.send(redis.client.set("messages." + req.query.id, message));
}

exports.unapprove = function(req, res) {
  var message = redis.client.get("messages." + req.query.id);
  message.approved = false;
  res.send(redis.client.set("messages." + req.query.id, message));
}<|endoftext|>


<commit_before>import CodeMirror from 'codemirror';
import Ember from 'ember';

export default Ember.Component.extend({
  /**
   * The value of the editor.
   *
   * @property value
   * @type {String}
   * @default null
   */
  value: null,

  autofocus: false,
  coverGutterNextToScrollbar: false,
  electricChars: true,
  extraKeys: null,
  firstLineNumber: 1,
  fixedGutter: true,
  historyEventDelay: 1250,
  indentUnit: 2,
  indentWithTabs: false,
  keyMap: 'default',
  lineNumbers: false,
  lineWrapping: false,
  mode: null,
  readOnly: false,
  rtlMoveVisually: true,
  showCursorWhenSelecting: false,
  smartIndent: true,
  tabSize: 4,
  tabindex: null,
  theme: 'default',
  undoDepth: 200,

  tagName: 'textarea',

  /**
   * Force CodeMirror to refresh.
   *
   * @method refresh
   */
  refresh() {
    this.get('codeMirror').refresh();
  },

  _initCodemirror: Ember.on('didInsertElement', function() {
    const codeMirror = CodeMirror.fromTextArea(this.get('element'));

    // Stash away the CodeMirror instance.
    this.set('codeMirror', codeMirror);

    // Set up handlers for CodeMirror events.
    this._bindCodeMirrorEvent('change', this, '_updateValue');

    // Set up bindings for CodeMirror options.
    this._bindCodeMirrorOption('autofocus');
    this._bindCodeMirrorOption('coverGutterNextToScrollbar');
    this._bindCodeMirrorOption('electricChars');
    this._bindCodeMirrorOption('extraKeys');
    this._bindCodeMirrorOption('firstLineNumber');
    this._bindCodeMirrorOption('fixedGutter');
    this._bindCodeMirrorOption('historyEventDelay');
    this._bindCodeMirrorOption('indentUnit');
    this._bindCodeMirrorOption('indentWithTabs');
    this._bindCodeMirrorOption('keyMap');
    this._bindCodeMirrorOption('lineNumbers');
    this._bindCodeMirrorOption('lineWrapping');
    this._bindCodeMirrorOption('mode');
    this._bindCodeMirrorOption('readOnly');
    this._bindCodeMirrorOption('rtlMoveVisually');
    this._bindCodeMirrorOption('showCursorWhenSelecting');
    this._bindCodeMirrorOption('smartIndent');
    this._bindCodeMirrorOption('tabSize');
    this._bindCodeMirrorOption('tabindex');
    this._bindCodeMirrorOption('theme');
    this._bindCodeMirrorOption('undoDepth');

    this._bindCodeMirrorProperty('value', this, '_valueDidChange');
    this._valueDidChange();

    // Force a refresh on `becameVisible`, since CodeMirror won't render itself
    // onto a hidden element.
    this.on('becameVisible', this, 'refresh');

    // Private action used by tests. Do not rely on this in your apps.
    this.sendAction('_onReady', codeMirror);
  }),

  /**
   * Bind a handler for `event`, to be torn down in `willDestroyElement`.
   *
   * @private
   * @method _bindCodeMirrorEvent
   */
  _bindCodeMirrorEvent(event, target, method) {
    const callback = Ember.run.bind(target, method);

    this.get('codeMirror').on(event, callback);

    this.on('willDestroyElement', this, function() {
      this.get('codeMirror').off(event, callback);
    });
  },

  /**
   * @private
   * @method _bindCodeMirrorProperty
   */
  _bindCodeMirrorOption(key) {
    this._bindCodeMirrorProperty(key, this, '_optionDidChange');

    // Set the initial option synchronously.
    this._optionDidChange(this, key);
  },

  /**
   * Bind an observer on `key`, to be torn down in `willDestroyElement`.
   *
   * @private
   * @method _bindCodeMirrorProperty
   */
  _bindCodeMirrorProperty(key, target, method) {
    this.addObserver(key, target, method);

    this.on('willDestroyElement', this, function() {
      this.removeObserver(key, target, method);
    });
  },

  /**
   * Sync a local option value with CodeMirror.
   *
   * @private
   * @method _optionDidChange
   */
  _optionDidChange(sender, key) {
    this.get('codeMirror').setOption(key, this.get(key));
  },

  /**
   * Update the `value` property when a CodeMirror `change` event occurs.
   *
   * @private
   * @method _updateValue
   */
  _updateValue(instance, changeObj) {
    const value = instance.getValue();
    this.set('value', value);
    this.sendAction('valueUpdated', value, instance, changeObj);
  },

  _valueDidChange() {
    const codeMirror = this.get('codeMirror'),
        value = this.get('value');

    if (value !== codeMirror.getValue()) {
      codeMirror.setValue(value || '');
    }
  }
});
<commit_msg>Use method form of `didInsertElement`<commit_after>import CodeMirror from 'codemirror';
import Ember from 'ember';

export default Ember.Component.extend({
  /**
   * The value of the editor.
   *
   * @property value
   * @type {String}
   * @default null
   */
  value: null,

  autofocus: false,
  coverGutterNextToScrollbar: false,
  electricChars: true,
  extraKeys: null,
  firstLineNumber: 1,
  fixedGutter: true,
  historyEventDelay: 1250,
  indentUnit: 2,
  indentWithTabs: false,
  keyMap: 'default',
  lineNumbers: false,
  lineWrapping: false,
  mode: null,
  readOnly: false,
  rtlMoveVisually: true,
  showCursorWhenSelecting: false,
  smartIndent: true,
  tabSize: 4,
  tabindex: null,
  theme: 'default',
  undoDepth: 200,

  tagName: 'textarea',

  /**
   * Force CodeMirror to refresh.
   *
   * @method refresh
   */
  refresh() {
    this.get('codeMirror').refresh();
  },

  didInsertElement() {
    this._super(...arguments);

    const codeMirror = CodeMirror.fromTextArea(this.get('element'));

    // Stash away the CodeMirror instance.
    this.set('codeMirror', codeMirror);

    // Set up handlers for CodeMirror events.
    this._bindCodeMirrorEvent('change', this, '_updateValue');

    // Set up bindings for CodeMirror options.
    this._bindCodeMirrorOption('autofocus');
    this._bindCodeMirrorOption('coverGutterNextToScrollbar');
    this._bindCodeMirrorOption('electricChars');
    this._bindCodeMirrorOption('extraKeys');
    this._bindCodeMirrorOption('firstLineNumber');
    this._bindCodeMirrorOption('fixedGutter');
    this._bindCodeMirrorOption('historyEventDelay');
    this._bindCodeMirrorOption('indentUnit');
    this._bindCodeMirrorOption('indentWithTabs');
    this._bindCodeMirrorOption('keyMap');
    this._bindCodeMirrorOption('lineNumbers');
    this._bindCodeMirrorOption('lineWrapping');
    this._bindCodeMirrorOption('mode');
    this._bindCodeMirrorOption('readOnly');
    this._bindCodeMirrorOption('rtlMoveVisually');
    this._bindCodeMirrorOption('showCursorWhenSelecting');
    this._bindCodeMirrorOption('smartIndent');
    this._bindCodeMirrorOption('tabSize');
    this._bindCodeMirrorOption('tabindex');
    this._bindCodeMirrorOption('theme');
    this._bindCodeMirrorOption('undoDepth');

    this._bindCodeMirrorProperty('value', this, '_valueDidChange');
    this._valueDidChange();

    // Force a refresh on `becameVisible`, since CodeMirror won't render itself
    // onto a hidden element.
    this.on('becameVisible', this, 'refresh');

    // Private action used by tests. Do not rely on this in your apps.
    this.sendAction('_onReady', codeMirror);
  },

  /**
   * Bind a handler for `event`, to be torn down in `willDestroyElement`.
   *
   * @private
   * @method _bindCodeMirrorEvent
   */
  _bindCodeMirrorEvent(event, target, method) {
    const callback = Ember.run.bind(target, method);

    this.get('codeMirror').on(event, callback);

    this.on('willDestroyElement', this, function() {
      this.get('codeMirror').off(event, callback);
    });
  },

  /**
   * @private
   * @method _bindCodeMirrorProperty
   */
  _bindCodeMirrorOption(key) {
    this._bindCodeMirrorProperty(key, this, '_optionDidChange');

    // Set the initial option synchronously.
    this._optionDidChange(this, key);
  },

  /**
   * Bind an observer on `key`, to be torn down in `willDestroyElement`.
   *
   * @private
   * @method _bindCodeMirrorProperty
   */
  _bindCodeMirrorProperty(key, target, method) {
    this.addObserver(key, target, method);

    this.on('willDestroyElement', this, function() {
      this.removeObserver(key, target, method);
    });
  },

  /**
   * Sync a local option value with CodeMirror.
   *
   * @private
   * @method _optionDidChange
   */
  _optionDidChange(sender, key) {
    this.get('codeMirror').setOption(key, this.get(key));
  },

  /**
   * Update the `value` property when a CodeMirror `change` event occurs.
   *
   * @private
   * @method _updateValue
   */
  _updateValue(instance, changeObj) {
    const value = instance.getValue();
    this.set('value', value);
    this.sendAction('valueUpdated', value, instance, changeObj);
  },

  _valueDidChange() {
    const codeMirror = this.get('codeMirror'),
        value = this.get('value');

    if (value !== codeMirror.getValue()) {
      codeMirror.setValue(value || '');
    }
  }
});
<|endoftext|>


<commit_before><commit_msg>fully use StructureColors definition in sstruc color scheme<commit_after><|endoftext|>


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

require('app/scripts/application');
require('app/templates/compiled');
require('app/lib/bootstrap/alert');
require('app/lib/codemirror/lib/codemirror');
require('app/scripts/codemirror.lua.li');

'use strict';

var STATUS_CODE_TO_ERROR_MESSAGE = {
    401: 'Either you have not entered an API token or the one you have entered is not valid.',
    409: 'You already have a user scenario with the specified name.',
    429: 'You have made too many requests to the Load Impact API, please try again in a few minutes.'
};

LI.Router.map(function() {
    this.route('editor');
});

LI.IndexRoute = Ember.Route.extend({
    beforeModel: function() {
        this.transitionTo('editor');
    }
});

LI.EditorRoute = Ember.Route.extend({
    model: function () {
        TEST_1234 = 2;
        TEST_5678 = 2;
        return this.get('store').find('options', 1);
    },

    setupController: function(controller, model) {
        controller.set('model', model);
    }
});

LI.EditorController = Ember.ObjectController.extend({
    errorMsg: null,
    savedUserScenarioId: null,

    actions: {
        save: function() {
            var self = this;
            $.ajax({
                type: 'POST',
                url: this.get('apiUrl') + 'user-scenarios/',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(self.get('apiToken') + ':'));
                },
                contentType: 'application/json; charset=UTF-8',
                dataType: 'json',
                data: JSON.stringify({
                    name: $('#name').val(),
                    load_script: $('#load-script').val()
                }),
                success: function(data, textStatus, jqXHR) {
                    $('#editor-form').hide();
                    self.set('savedUserScenarioId', data['id']);
                    $('#success').removeClass('hidden');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    var errorMsg = '',
                        statusCode = jqXHR.status,
                        msgText = function() {
                            var msg = '';
                            if (textStatus) {
                                msg += textStatus;
                            }
                            if (errorThrown) {
                                if (msg) {
                                    msg += ', ';
                                }
                                msg += errorThrown;
                            }
                            return msg;
                        };
                    if (400 <= statusCode && 599 >= statusCode) {
                        var msg = STATUS_CODE_TO_ERROR_MESSAGE[statusCode];
                        if (!msg) {
                            msg = jqXHR.responseText;
                            if (msg) {
                                try {
                                    var apiResponse = JSON.parse(msg);
                                    if (apiResponse.message) {
                                        msg = apiResponse.message;
                                    }
                                } catch (e) {
                                    // Ignore JSON parse errors.
                                }
                            } else {
                                msg = msgText();
                            }
                        }
                        errorMsg = msg + ' (' + statusCode + ')';
                    } else {
                        errorMsg = msgText();
                    }
                    self.set('errorMsg', errorMsg);
                }
            });
            return false;
        },

        continueEditingOnSite: function() {
            window.location.href = ('https://loadimpact.com/test/user-scenario/list?s=' +
                                    this.get('savedUserScenarioId'));
        }
    },
});

LI.EditorView = Ember.View.extend({
    didInsertElement: function() {
        var msg = {
            'type': 'get-last-recorded-script',
        };
        chrome.extension.sendRequest(msg, function(response) {
            console.log(response.loadScript);
            $('#name').val('Recorded (' + (new Date()).toString() + ')');
            var textarea = $('#load-script');
            textarea.val(response.loadScript);
            window.Editor = CodeMirror.fromTextArea(textarea.get(0), {
                mode: 'lua',
                lineNumbers: true,
                lineWrapping: true,
                tabMode: 'indent'
            });
        });
    }
});

/**
 * If the editor has any content, prompt the user before navigating to another page.
 */
window.onbeforeunload = function() {
    if (window.Editor.getValue()) {
        return "The recorded scenario will be lost if you navigate to another page.";
    }
};
<commit_msg>Fix issue that ignored edits to recorded user scenario.<commit_after>/*
 * Copyright 2014 Load Impact
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require('app/scripts/application');
require('app/templates/compiled');
require('app/lib/bootstrap/alert');
require('app/lib/codemirror/lib/codemirror');
require('app/scripts/codemirror.lua.li');

'use strict';

var STATUS_CODE_TO_ERROR_MESSAGE = {
    401: 'Either you have not entered an API token or the one you have entered is not valid.',
    409: 'You already have a user scenario with the specified name.',
    429: 'You have made too many requests to the Load Impact API, please try again in a few minutes.'
};

window.continueEditingOnSite = false;

LI.Router.map(function() {
    this.route('editor');
});

LI.IndexRoute = Ember.Route.extend({
    beforeModel: function() {
        this.transitionTo('editor');
    }
});

LI.EditorRoute = Ember.Route.extend({
    model: function () {
        TEST_1234 = 2;
        TEST_5678 = 2;
        return this.get('store').find('options', 1);
    },

    setupController: function(controller, model) {
        controller.set('model', model);
    }
});

LI.EditorController = Ember.ObjectController.extend({
    errorMsg: null,
    savedUserScenarioId: null,

    actions: {
        save: function() {
            var self = this;
            $.ajax({
                type: 'POST',
                url: this.get('apiUrl') + 'user-scenarios/',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(self.get('apiToken') + ':'));
                },
                contentType: 'application/json; charset=UTF-8',
                dataType: 'json',
                data: JSON.stringify({
                    name: $('#name').val(),
                    load_script: window.Editor.getValue()
                }),
                success: function(data, textStatus, jqXHR) {
                    $('#editor-form').hide();
                    self.set('savedUserScenarioId', data['id']);
                    $('#success').removeClass('hidden');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    var errorMsg = '',
                        statusCode = jqXHR.status,
                        msgText = function() {
                            var msg = '';
                            if (textStatus) {
                                msg += textStatus;
                            }
                            if (errorThrown) {
                                if (msg) {
                                    msg += ', ';
                                }
                                msg += errorThrown;
                            }
                            return msg;
                        };
                    if (400 <= statusCode && 599 >= statusCode) {
                        var msg = STATUS_CODE_TO_ERROR_MESSAGE[statusCode];
                        if (!msg) {
                            msg = jqXHR.responseText;
                            if (msg) {
                                try {
                                    var apiResponse = JSON.parse(msg);
                                    if (apiResponse.message) {
                                        msg = apiResponse.message;
                                    }
                                } catch (e) {
                                    // Ignore JSON parse errors.
                                }
                            } else {
                                msg = msgText();
                            }
                        }
                        errorMsg = msg + ' (' + statusCode + ')';
                    } else {
                        errorMsg = msgText();
                    }
                    self.set('errorMsg', errorMsg);
                }
            });
            return false;
        },

        continueEditingOnSite: function() {
            window.continueEditingOnSite = true;
            window.location.href = ('https://loadimpact.com/test/user-scenario/list?s=' +
                                    this.get('savedUserScenarioId'));
        }
    },
});

LI.EditorView = Ember.View.extend({
    didInsertElement: function() {
        var msg = {
            'type': 'get-last-recorded-script',
        };
        chrome.extension.sendRequest(msg, function(response) {
            $('#name').val('Recorded (' + (new Date()).toString() + ')');
            var textarea = $('#load-script');
            textarea.val(response.loadScript);
            window.Editor = CodeMirror.fromTextArea(textarea.get(0), {
                mode: 'lua',
                lineNumbers: true,
                lineWrapping: true,
                tabMode: 'indent'
            });
        });
    }
});

/**
 * If the editor has any content, prompt the user before navigating to another page.
 */
window.onbeforeunload = function() {
    if (window.Editor.getValue() && !window.continueEditingOnSite) {
        return "The recorded scenario will be lost if you navigate to another page.";
    }
};
<|endoftext|>


<commit_before>/**
 * Requires ComplexFunctions (in solver.js)
 */

/* Defined functions */
/* Arithmetic */
Functions["+"] = new ComplexFunction(0,false,
        function(a,b) {
            return a + b;
        });
Functions["-"] = new ComplexFunction(0,false,
        function(a,b) {
            return a - b;
        });
Functions["*"] = new ComplexFunction(1,false,
        function(a,b) {
            return a * b;
        });
Functions["/"] = new ComplexFunction(1,false,
        function(a,b) {
            return a / b;
        });
Functions["^"] = new ComplexFunction(2,false,
        function(a,b) {
            return Math.pow(a,b);
        });
Functions["sqrt"] = new ComplexFunction(1,true,
        function(a) {
            return Math.sqrt(a);
        });

/* Sinusoidal */
Functions["sin"] = new ComplexFunction(1,true,
        function(a) {
            var result = Math.sin(a);
            return result;
        });
Functions["cos"] = new ComplexFunction(1,true,
        function(a) {
            return Math.cos(a);
        });
Functions["tan"] = new ComplexFunction(1,true,
        function(a) {
            return Math.tan(a);
        });
Functions["asin"] = new ComplexFunction(1,true,
        function(a) {
            return Math.asin(a);
        });
Functions["acos"] = new ComplexFunction(1,true,
        function(a) {
            return Math.acos(a);
        });
Functions["atan"] = new ComplexFunction(1,true,
        function(a) {
            return Math.atan(a);
        });

/* Logarithms */
// Log-10
Functions["log"] = new ComplexFunction(1,true,
        function(a) {
            return Math.log(a)/Math.LN10;
        });
// Log-e
Functions["ln"] = new ComplexFunction(1,true,
        function(a) {
            return Math.log(a);
        });

/* Rectifiers */
Functions["abs"] = new ComplexFunction(1,true,
        function(a) {
            return Math.abs(a);
        });
Functions["ceil"] = new ComplexFunction(1,true,
        function(a) {
            return Math.ceil(a);
        });
Functions["floor"] = new ComplexFunction(1,true,
        function(a) {
            return Math.floor(a);
        });
Functions["average"] = new ComplexFunction(1,true,
        function() {
            var results = 0,
              len = arguments.length;
            for(var i = 0; i < len; i++)
            {
                results += arguments[i];
            }
            if(len > 0)
            {
                results /= len;
            }
            return result;
        },true);

/* Combinators */
Functions["sum"] = new ComplexFunction(1,true,
        function() {
            var results = 0,
              len = arguments.length;
            for(var i = 0; i < len; i++)
            {
                results += arguments[i];
            }

            return result;
        },true);
Functions["product"] = new ComplexFunction(1,true,
        function() {
            var results = 1,
              len = arguments.length;
            for(var i = 0; i < len; i++)
            {
                results *= arguments[i];
            }

            return result;
        },true);

/* Defined constants */
// PI : ~3.14159
Constants["pi"] = new Constant(Math.PI);
// E : ~2.71828
Constants["e"] = new Constant(Math.E);

/* Custom functions */
Functions["cheese"] = new ComplexFunction(1,true,
        function(a,b,c,d,e,f) {
            return a * b * c * d * e * f;
        });
<commit_msg>Fixing typos<commit_after>/**
 * Requires ComplexFunctions (in solver.js)
 */

/* Defined functions */
/* Arithmetic */
Functions["+"] = new ComplexFunction(0,false,
        function(a,b) {
            return a + b;
        });
Functions["-"] = new ComplexFunction(0,false,
        function(a,b) {
            return a - b;
        });
Functions["*"] = new ComplexFunction(1,false,
        function(a,b) {
            return a * b;
        });
Functions["/"] = new ComplexFunction(1,false,
        function(a,b) {
            return a / b;
        });
Functions["^"] = new ComplexFunction(2,false,
        function(a,b) {
            return Math.pow(a,b);
        });
Functions["sqrt"] = new ComplexFunction(1,true,
        function(a) {
            return Math.sqrt(a);
        });

/* Sinusoidal */
Functions["sin"] = new ComplexFunction(1,true,
        function(a) {
            var result = Math.sin(a);
            return result;
        });
Functions["cos"] = new ComplexFunction(1,true,
        function(a) {
            return Math.cos(a);
        });
Functions["tan"] = new ComplexFunction(1,true,
        function(a) {
            return Math.tan(a);
        });
Functions["asin"] = new ComplexFunction(1,true,
        function(a) {
            return Math.asin(a);
        });
Functions["acos"] = new ComplexFunction(1,true,
        function(a) {
            return Math.acos(a);
        });
Functions["atan"] = new ComplexFunction(1,true,
        function(a) {
            return Math.atan(a);
        });

/* Logarithms */
// Log-10
Functions["log"] = new ComplexFunction(1,true,
        function(a) {
            return Math.log(a)/Math.LN10;
        });
// Log-e
Functions["ln"] = new ComplexFunction(1,true,
        function(a) {
            return Math.log(a);
        });

/* Rectifiers */
Functions["abs"] = new ComplexFunction(1,true,
        function(a) {
            return Math.abs(a);
        });
Functions["ceil"] = new ComplexFunction(1,true,
        function(a) {
            return Math.ceil(a);
        });
Functions["floor"] = new ComplexFunction(1,true,
        function(a) {
            return Math.floor(a);
        });
Functions["average"] = new ComplexFunction(1,true,
        function() {
            var results = 0,
              len = arguments.length;
            for(var i = 0; i < len; i++)
            {
                results += arguments[i];
            }
            if(len > 0)
            {
                results /= len;
            }
            return results;
        },true);

/* Combinators */
Functions["sum"] = new ComplexFunction(1,true,
        function() {
            var results = 0,
              len = arguments.length;
            for(var i = 0; i < len; i++)
            {
                results += arguments[i];
            }

            return results;
        },true);
Functions["product"] = new ComplexFunction(1,true,
        function() {
            var results = 1,
              len = arguments.length;
            for(var i = 0; i < len; i++)
            {
                results *= arguments[i];
            }

            return results;
        },true);

/* Defined constants */
// PI : ~3.14159
Constants["pi"] = new Constant(Math.PI);
// E : ~2.71828
Constants["e"] = new Constant(Math.E);

/* Custom functions */
Functions["cheese"] = new ComplexFunction(1,true,
        function(a,b,c,d,e,f) {
            return a * b * c * d * e * f;
        });
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import moment from 'moment';
import {toMomentFromRailsDate} from '../helpers/toMoment';
import ExperimentalBanner from '../components/ExperimentalBanner';

// Renders ed plan data (504)
export default class EdPlansPanel extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      showRaw: false,
      showAll: false
    };
    this.onShowRawClicked = this.onShowRawClicked.bind(this);
    this.onShowMore = this.onShowMore.bind(this);
  }

  onShowRawClicked(e) {
    e.preventDefault();
    this.setState({showRaw: true});
  }

  onShowMore(e) {
    e.preventDefault();
    this.setState({showAll: true});
  }

  render() {
    const {edPlans} = this.props;
    const {showAll, showRaw} = this.state;

    const sortedEdPlans = _.sortBy(edPlans, 'sep_effective_date').reverse();
    const visibleEdPlans = (showAll) ? sortedEdPlans : sortedEdPlans.slice(0, 1);
    return (

        <ExperimentalBanner />
        {visibleEdPlans.map(this.renderEdPlan, this)}
        {showAll
          ? null
          : Show older 504 plans
        }
        {showRaw
          ?
{JSON.stringify(edPlans, null, 2)}

          : Show raw data
        }

    );
  }

  // Might not be active or effective
  renderEdPlan(edPlan) {
    return (

504 plan id:{edPlan.sep_oid}

Status

Effective dates {reformatDate(edPlan.sep_effective_date, highlight('(missing)'))} - {reformatDate(edPlan.sep_end_date, highlight('(missing)'))}

Last review on {reformatDate(edPlan.sep_review_date, highlight('(none)'))}

Last meeting on {reformatDate(edPlan.sep_last_meeting_date, highlight('(none)'))}

Last modified on {(edPlan.sep_last_modified)
              ? moment.utc(edPlan.sep_last_modified/1000)
              : highlight('(none)')}

{reformatDate(edPlan.sep_parent_signed_date, highlight('Not signed'))} by family

{reformatDate(edPlan.sep_district_signed_date, highlight('Not signed'))} by district

Document text

            {this.renderSubstance(edPlan)}

Accommodations

            {edPlan.ed_plan_accommodations.map(accommodation => (

{accommodation.iac_description}

            ))}
            {edPlan.ed_plan_accommodations.length === 0 &&
No accommodations.
}

    );
  }

  renderSubstance(edPlan) {
    const lines = [
      edPlan.sep_fieldd_001,
      edPlan.sep_fieldd_002,
      edPlan.sep_fieldd_003,
      edPlan.sep_fieldd_004,
      edPlan.sep_fieldd_005,
      edPlan.sep_fieldd_006,
      edPlan.sep_fieldd_007,
      edPlan.sep_fieldd_008,
      edPlan.sep_fieldd_009,
      edPlan.sep_fieldd_010,
      edPlan.sep_fieldd_011,
      edPlan.sep_fieldd_012,
      edPlan.sep_fieldd_013,
      edPlan.sep_fieldd_014
    ];
    const cleanedLines = _.compact(lines.map(field => field === 'N' ? null : field));
    return
{cleanedLines.map(line =>
{line}
)}
;
  }
}
EdPlansPanel.propTypes = {
  edPlans: PropTypes.arrayOf(PropTypes.shape({
    sep_effective_date: PropTypes.string,
    sep_review_date: PropTypes.string,
    sep_last_meeting_date: PropTypes.string,
    sep_district_signed_date: PropTypes.string,
    sep_parent_signed_date: PropTypes.string,
    sep_end_date: PropTypes.string,
    sep_last_modified: PropTypes.string,
    ed_plan_accommodations: PropTypes.arrayOf(PropTypes.shape({
      iac_content_area: PropTypes.string,
      iac_category: PropTypes.string,
      iac_type: PropTypes.string,
      iac_description: PropTypes.string,
      iac_field: PropTypes.string,
      iac_name: PropTypes.string,
      iac_last_modified: PropTypes.string
    })).isRequired
  })).isRequired
};

const styles = {
  substance: {
    whiteSpace: 'pre-wrap'
  },
  link: {
    display: 'block',
    fontSize: 14,
    marginTop: 10,
    marginBottom: 10
  }
};

function reformatDate(maybeDateText, elseValue = null) {
  if (!maybeDateText) return elseValue;
  return toMomentFromRailsDate(maybeDateText).format('M/D/YY');
}

function highlight(el) {
  return {el};
}
<commit_msg>Update JS parsing of last modified for 504 records<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import moment from 'moment';
import {toMomentFromRailsDate} from '../helpers/toMoment';
import ExperimentalBanner from '../components/ExperimentalBanner';

// Renders ed plan data (504)
export default class EdPlansPanel extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      showRaw: false,
      showAll: false
    };
    this.onShowRawClicked = this.onShowRawClicked.bind(this);
    this.onShowMore = this.onShowMore.bind(this);
  }

  onShowRawClicked(e) {
    e.preventDefault();
    this.setState({showRaw: true});
  }

  onShowMore(e) {
    e.preventDefault();
    this.setState({showAll: true});
  }

  render() {
    const {edPlans} = this.props;
    const {showAll, showRaw} = this.state;

    const sortedEdPlans = _.sortBy(edPlans, 'sep_effective_date').reverse();
    const visibleEdPlans = (showAll) ? sortedEdPlans : sortedEdPlans.slice(0, 1);
    return (

        <ExperimentalBanner />
        {visibleEdPlans.map(this.renderEdPlan, this)}
        {showAll
          ? null
          : Show older 504 plans
        }
        {showRaw
          ?
{JSON.stringify(edPlans, null, 2)}

          : Show raw data
        }

    );
  }

  // Might not be active or effective
  renderEdPlan(edPlan) {
    return (

504 plan id:{edPlan.sep_oid}

Status

Effective dates {reformatDate(edPlan.sep_effective_date, highlight('(missing)'))} - {reformatDate(edPlan.sep_end_date, highlight('(missing)'))}

Last review on {reformatDate(edPlan.sep_review_date, highlight('(none)'))}

Last meeting on {reformatDate(edPlan.sep_last_meeting_date, highlight('(none)'))}

Last modified on {reformatDate(edPlan.sep_last_modified, highlight('(none)'))}

{reformatDate(edPlan.sep_parent_signed_date, highlight('Not signed'))} by family

{reformatDate(edPlan.sep_district_signed_date, highlight('Not signed'))} by district

Document text

            {this.renderSubstance(edPlan)}

Accommodations

            {edPlan.ed_plan_accommodations.map(accommodation => (

{accommodation.iac_description}

            ))}
            {edPlan.ed_plan_accommodations.length === 0 &&
No accommodations.
}

    );
  }

  renderSubstance(edPlan) {
    const lines = [
      edPlan.sep_fieldd_001,
      edPlan.sep_fieldd_002,
      edPlan.sep_fieldd_003,
      edPlan.sep_fieldd_004,
      edPlan.sep_fieldd_005,
      edPlan.sep_fieldd_006,
      edPlan.sep_fieldd_007,
      edPlan.sep_fieldd_008,
      edPlan.sep_fieldd_009,
      edPlan.sep_fieldd_010,
      edPlan.sep_fieldd_011,
      edPlan.sep_fieldd_012,
      edPlan.sep_fieldd_013,
      edPlan.sep_fieldd_014
    ];
    const cleanedLines = _.compact(lines.map(field => field === 'N' ? null : field));
    return
{cleanedLines.map(line =>
{line}
)}
;
  }
}
EdPlansPanel.propTypes = {
  edPlans: PropTypes.arrayOf(PropTypes.shape({
    sep_effective_date: PropTypes.string,
    sep_review_date: PropTypes.string,
    sep_last_meeting_date: PropTypes.string,
    sep_district_signed_date: PropTypes.string,
    sep_parent_signed_date: PropTypes.string,
    sep_end_date: PropTypes.string,
    sep_last_modified: PropTypes.string,
    ed_plan_accommodations: PropTypes.arrayOf(PropTypes.shape({
      iac_content_area: PropTypes.string,
      iac_category: PropTypes.string,
      iac_type: PropTypes.string,
      iac_description: PropTypes.string,
      iac_field: PropTypes.string,
      iac_name: PropTypes.string,
      iac_last_modified: PropTypes.string
    })).isRequired
  })).isRequired
};

const styles = {
  substance: {
    whiteSpace: 'pre-wrap'
  },
  link: {
    display: 'block',
    fontSize: 14,
    marginTop: 10,
    marginBottom: 10
  }
};

function reformatDate(maybeDateText, elseValue = null) {
  if (!maybeDateText) return elseValue;
  return toMomentFromRailsDate(maybeDateText).format('M/D/YY');
}

function highlight(el) {
  return {el};
}
<|endoftext|>


<commit_before>'use strict';
import React from 'react';

import GMap from './GMap';
import ContactInfo from '../constants/json/ContactInfoData.json';
import LocationInfo from '../constants/json/LocationInfoData.json';
// import vCard from '../../public/resources/Ralph Isenrich CFA.vcf';

const INFO_MAP = new Map([
  ['name', 'user-circle'],
  ['email', 'envelope'],
  ['phone', 'phone-square']
]);

const renderContactIcons = (datum) => datum.scheme ? (

    <i className={ `fa fa-${INFO_MAP.get(datum.type)}` } />

) : datum.type ? (
  <i className={ `fa fa-${INFO_MAP.get(datum.type)}` } />
) : null;

const renderContactInfo = (data) => data.map((datum, index) =>
  <p key={ `ContactInfo_${index}` }>
    {[
      renderContactIcons(datum),
      datum.hasOwnProperty('value') ? datum.value : datum
    ]}

);

const Contact = () => (

Please contact us to discuss investment opportunities

{ renderContactInfo(ContactInfo) }

            {[
              <i
                key={ `FAIcon_AddressCard` }
                className="fa fa-address-card invert" />,
              'Download vCard'
            ]}

            { renderContactInfo(LocationInfo) }

            {[
              <i
                key={ `FAIcon_Newspaper` }
                className="fa fa-newspaper-o invert" />,
              'Subscribe for News & Updates'
            ]}

    <GMap />

);

export default Contact;

// Download vCard

// G-Maps URL:  https://www.google.com/maps/place/
// Ferro+Management+Group,+185+Wind+Chime+Ct+%23+201,+Raleigh,+NC+27615/@35.8761861,-78.6425212,19z/data=!3m1!4b1!4m2!3m1!1s0x89ac58133cd16d47:0xb239755f849eed8d?hl=en
<commit_msg>refactor: Map location info using existing utility functions<commit_after>'use strict';
import React from 'react';

import GMap from './partials/GMap';
import ContactInfo from '../constants/json/ContactInfoData.json';
import LocationInfo from '../constants/json/LocationInfoData.json';
// import vCard from '../../public/resources/Ralph Isenrich CFA.vcf';

const INFO_MAP = new Map([
  ['name', 'user-circle'],
  ['email', 'envelope'],
  ['phone', 'phone-square']
]);

const renderContactIcons = (datum) => datum.scheme ? (

    <i className={ `fa fa-${INFO_MAP.get(datum.type)}` } />

) : datum.type ? (
  <i className={ `fa fa-${INFO_MAP.get(datum.type)}` } />
) : null;

const renderContactInfo = (data) => data.map((datum, index) =>
  <p key={ `ContactInfo_${index}` }>
    {[
      renderContactIcons(datum),
      datum.hasOwnProperty('value') ? datum.value : datum
    ]}

);

const Contact = () => (

Please contact us to discuss investment opportunities

{ renderContactInfo(ContactInfo) }

            {[
              <i
                key={ `FAIcon_AddressCard` }
                className="fa fa-address-card invert" />,
              'Download vCard'
            ]}

            { renderContactInfo(LocationInfo) }

            {[
              <i
                key={ `FAIcon_Newspaper` }
                className="fa fa-newspaper-o invert" />,
              'Subscribe for News & Updates'
            ]}

    <GMap />

);

export default Contact;

// Download vCard

// G-Maps URL:  https://www.google.com/maps/place/
// Ferro+Management+Group,+185+Wind+Chime+Ct+%23+201,+Raleigh,+NC+27615/@35.8761861,-78.6425212,19z/data=!3m1!4b1!4m2!3m1!1s0x89ac58133cd16d47:0xb239755f849eed8d?hl=en
<|endoftext|>


<commit_before>import { indexOfItemContainingTarget } from "../core/dom.js";
import ReactiveElement from "../core/ReactiveElement.js"; // eslint-disable-line no-unused-vars
import {
  firstRender,
  raiseChangeEvents,
  render,
  setState,
  state,
  tap,
} from "./internal.js";

/**
 * A tap/mousedown on a list item makes that item current.
 *
 * This simple mixin is useful in list-like elements like [ListBox](ListBox),
 * where a tap/mousedown on a list item implicitly selects it.
 *
 * The standard use for this mixin is in list-like elements. Native list
 * boxes don't appear to be consistent with regard to whether they select
 * on mousedown or click/mouseup. This mixin assumes the use of mousedown.
 * On touch devices, that event appears to trigger when the touch is *released*.
 *
 * This mixin only listens to mousedown events for the primary mouse button
 * (typically the left button). Right clicks are ignored so that the browser may
 * display a context menu.
 *
 * This mixin expects the component to provide an `state.items` member. It also
 * expects the component to define a `state.currentIndex` member; you can
 * provide that yourself, or use [ItemsCursorMixin](ItemsCursorMixin).
 *
 * If the component receives an event that doesn't correspond to an item (e.g.,
 * the user taps on the element background visible between items), the cursor
 * will be removed. However, if the component sets `state.currentItemRequired` to
 * true, a background tap will *not* remove the cursor.
 *
 * @module TapCursorMixin
 * @param {Constructor<ReactiveElement>} Base
 */
export default function TapCursorMixin(Base) {
  // The class prototype added by the mixin.
  return class TapCursor extends Base {
    constructor() {
      // @ts-ignore
      super();
      this.addEventListener("mousedown", (event) => {
        // Only process events for the main (usually left) button.
        if (event.button !== 0) {
          return;
        }
        this[raiseChangeEvents] = true;
        this[tap](event);
        this[raiseChangeEvents] = false;
      });
    }

    [render](/** @type {ChangedFlags} */ changed) {
      if (super[render]) {
        super[render](changed);
      }
      if (this[firstRender]) {
        Object.assign(this.style, {
          touchAction: "manipulation", // for iOS Safari
          mozUserSelect: "none",
          msUserSelect: "none",
          webkitUserSelect: "none",
          userSelect: "none",
        });
      }
    }

    [tap](/** @type {MouseEvent} */ event) {
      // In some situations, the event target will not be the child which was
      // originally clicked on. E.g., if the item clicked on is a button, the
      // event seems to be raised in phase 2 (AT_TARGET) — but the event target
      // will be the component, not the item that was clicked on. Instead of
      // using the event target, we get the first node in the event's composed
      // path.
      // @ts-ignore
      const target = event.composedPath
        ? event.composedPath()[0]
        : event.target;

      // Find which item was clicked on and, if found, make it current. For
      // elements which don't require a cursor, a background click will
      // determine the item was null, in which we case we'll remove the cursor.
      const { items, currentIndex, currentItemRequired } = this[state];
      if (items && target instanceof Node) {
        const targetIndex = indexOfItemContainingTarget(items, target);
        if (
          targetIndex >= 0 ||
          (!currentItemRequired && currentIndex !== targetIndex)
        ) {
          this[setState]({
            currentIndex: targetIndex,
          });
          event.stopPropagation();
        }
      }
    }
  };
}
<commit_msg>Ignore taps/clicks on disabled items.<commit_after>import { indexOfItemContainingTarget } from "../core/dom.js";
import ReactiveElement from "../core/ReactiveElement.js"; // eslint-disable-line no-unused-vars
import {
  firstRender,
  raiseChangeEvents,
  render,
  setState,
  state,
  tap,
} from "./internal.js";

/**
 * A tap/mousedown on a list item makes that item current.
 *
 * This simple mixin is useful in list-like elements like [ListBox](ListBox),
 * where a tap/mousedown on a list item implicitly selects it.
 *
 * The standard use for this mixin is in list-like elements. Native list
 * boxes don't appear to be consistent with regard to whether they select
 * on mousedown or click/mouseup. This mixin assumes the use of mousedown.
 * On touch devices, that event appears to trigger when the touch is *released*.
 *
 * This mixin only listens to mousedown events for the primary mouse button
 * (typically the left button). Right clicks are ignored so that the browser may
 * display a context menu.
 *
 * This mixin expects the component to provide an `state.items` member. It also
 * expects the component to define a `state.currentIndex` member; you can
 * provide that yourself, or use [ItemsCursorMixin](ItemsCursorMixin).
 *
 * If the component receives an event that doesn't correspond to an item (e.g.,
 * the user taps on the element background visible between items), the cursor
 * will be removed. However, if the component sets `state.currentItemRequired` to
 * true, a background tap will *not* remove the cursor.
 *
 * @module TapCursorMixin
 * @param {Constructor<ReactiveElement>} Base
 */
export default function TapCursorMixin(Base) {
  // The class prototype added by the mixin.
  return class TapCursor extends Base {
    constructor() {
      // @ts-ignore
      super();
      this.addEventListener("mousedown", (event) => {
        // Only process events for the main (usually left) button.
        if (event.button !== 0) {
          return;
        }
        this[raiseChangeEvents] = true;
        this[tap](event);
        this[raiseChangeEvents] = false;
      });
    }

    [render](/** @type {ChangedFlags} */ changed) {
      if (super[render]) {
        super[render](changed);
      }
      if (this[firstRender]) {
        Object.assign(this.style, {
          touchAction: "manipulation", // for iOS Safari
          mozUserSelect: "none",
          msUserSelect: "none",
          webkitUserSelect: "none",
          userSelect: "none",
        });
      }
    }

    [tap](/** @type {MouseEvent} */ event) {
      // In some situations, the event target will not be the child which was
      // originally clicked on. E.g., if the item clicked on is a button, the
      // event seems to be raised in phase 2 (AT_TARGET) — but the event target
      // will be the component, not the item that was clicked on. Instead of
      // using the event target, we get the first node in the event's composed
      // path.
      // @ts-ignore
      const target = event.composedPath
        ? event.composedPath()[0]
        : event.target;

      // Find which item was clicked on and, if found, make it current. Ignore
      // clicks on disabled items.
      //
      // For elements which don't require a cursor, a background click will
      // determine the item was null, in which we case we'll remove the cursor.
      const { items, currentItemRequired } = this[state];
      if (items && target instanceof Node) {
        const targetIndex = indexOfItemContainingTarget(items, target);
        const item = targetIndex >= 0 ? items[targetIndex] : null;
        if ((item && !item.disabled) || (!item && !currentItemRequired)) {
          this[setState]({
            currentIndex: targetIndex,
          });
          event.stopPropagation();
        }
      }
    }
  };
}
<|endoftext|>


<commit_before>// @flow

import ForerunnerDB from 'forerunnerdb';

import { parseMatch, parsePerson } from 'utils/parsers';

import type { MessageType } from 'types/message';
import type { MatchType } from 'types/match';
import type { PersonType } from 'types/person';
import type { ActionType } from 'types/action';

const fdb = new ForerunnerDB();
let db;

export function load() {
  let loaded = 0;
  db = fdb.db('tind3r');

  window.db = db;

  return new Promise(resolve => {
    const checkIfLoaded = () => (loaded === 4 ? resolve() : null);
    const loadedCallback = () => {
      loaded += 1;
      checkIfLoaded();
    };

    db.collection('matches').load(loadedCallback);
    db.collection('persons').load(loadedCallback);
    db.collection('messages').load(loadedCallback);
    db.collection('actions').load(loadedCallback);
  });
}

function create() {
  if (!db) {
    db = fdb.db('tind3r');
  }

  window.db = db;

  return db;
}

export function matchCollection(): Array<MatchType> {
  const matches: Array<MatchType> = db.collection('matches').find({}, {
    $join: [{
      persons: {
        _id: 'person_id',
        $as: 'person',
        $require: false,
        $multi: false,
      },
    }],
  });

  matches.forEach(match => {
    const lastMessage: MessageType = db.collection('messages').find({
      match_id: match._id,
    }, {
      $limit: 1,
      $orderBy: {
        date: -1,
      },
    })[0];

    match.last_msg_from_db = lastMessage || {}; // eslint-disable-line
  });

  return matches;
}

export function getMessages(matchId: string): Array<MessageType> {
  const messages = db.collection('messages').find({
    match_id: matchId,
  });

  return messages;
}

export function getMatch(matchId: string): MatchType {
  return db.collection('matches').find({
    _id: matchId,
  })[0];
}

export function getMatchByPerson(personId: string): MatchType {
  return db.collection('matches').find({
    person_id: personId,
  })[0];
}

export function getPerson(personId: string): PersonType {
  return db.collection('persons').find({
    _id: personId,
  })[0];
}

export function createAction(payload: ActionType) {
  db.collection('actions').insert(payload);
  db.collection('actions').save();
}

export function getActions(personId?: string): Array<ActionType> {
  let query = {};

  if (personId) {
    query = { person_id: personId };
  }

  return db.collection('actions').find(query);
}

export function removeActions() {
  db.collection('actions').remove();
  db.collection('actions').save();
}

export function removeAction(personId: string) {
  db.collection('actions').remove({ person_id: personId });
  db.collection('actions').save();
}

export function createPersons(persons: Array<PersonType>) {
  const collection = db.collection('persons');
  collection.insert(persons);
  collection.save();
}

export function createMatches(data: Array<MatchType>) {
  const collection = db.collection('matches');
  collection.insert(data);
  collection.save();
}

export function createMatch(match: Object) {
  const parsedMatch: MatchType = parseMatch(match, true);
  const parsedPerson: PersonType = parsePerson(match.person);

  createMatches([parsedMatch]);
  createPersons([parsedPerson]);
}

export function updateMatch(matchId: string, payload: Object) {
  console.log('update', matchId, payload);
  db.collection('matches').updateById(matchId, payload);
  db.collection('matches').save();
}

export function updatePerson(personId: string, payload: Object) {
  db.collection('persons').updateById(personId, parsePerson(payload));
  db.collection('persons').save();
}

export function removeMessage(_id: string) {
  db.collection('messages').remove({ _id });
  db.collection('messages').save();
}

export function removeMatch(_id: string) {
  const removedMatch = db.collection('matches').remove({ _id });
  db.collection('messages').remove({ match_id: _id });
  db.collection('persons').remove({ _id: removedMatch.person_id });

  db.collection('matches').save();
  db.collection('messages').save();
  db.collection('persons').save();
}

export function purge() {
  db.collection('matches').remove();
  db.collection('messages').remove();
  db.collection('persons').remove();

  db.collection('matches').save();
  db.collection('messages').save();
  db.collection('persons').save();

  removeActions();
}

export default create;
<commit_msg>Require person to success join<commit_after>// @flow

import ForerunnerDB from 'forerunnerdb';

import { parseMatch, parsePerson } from 'utils/parsers';

import type { MessageType } from 'types/message';
import type { MatchType } from 'types/match';
import type { PersonType } from 'types/person';
import type { ActionType } from 'types/action';

const fdb = new ForerunnerDB();
let db;

export function load() {
  let loaded = 0;
  db = fdb.db('tind3r');

  window.db = db;

  return new Promise(resolve => {
    const checkIfLoaded = () => (loaded === 4 ? resolve() : null);
    const loadedCallback = () => {
      loaded += 1;
      checkIfLoaded();
    };

    db.collection('matches').load(loadedCallback);
    db.collection('persons').load(loadedCallback);
    db.collection('messages').load(loadedCallback);
    db.collection('actions').load(loadedCallback);
  });
}

function create() {
  if (!db) {
    db = fdb.db('tind3r');
  }

  window.db = db;

  return db;
}

export function matchCollection(): Array<MatchType> {
  const matches: Array<MatchType> = db.collection('matches').find({}, {
    $join: [{
      persons: {
        _id: 'person_id',
        $as: 'person',
        $require: true,
        $multi: false,
      },
    }],
  });

  matches.forEach(match => {
    const lastMessage: MessageType = db.collection('messages').find({
      match_id: match._id,
    }, {
      $limit: 1,
      $orderBy: {
        date: -1,
      },
    })[0];

    match.last_msg_from_db = lastMessage || {}; // eslint-disable-line
  });

  return matches;
}

export function getMessages(matchId: string): Array<MessageType> {
  const messages = db.collection('messages').find({
    match_id: matchId,
  });

  return messages;
}

export function getMatch(matchId: string): MatchType {
  return db.collection('matches').find({
    _id: matchId,
  })[0];
}

export function getMatchByPerson(personId: string): MatchType {
  return db.collection('matches').find({
    person_id: personId,
  })[0];
}

export function getPerson(personId: string): PersonType {
  return db.collection('persons').find({
    _id: personId,
  })[0];
}

export function createAction(payload: ActionType) {
  db.collection('actions').insert(payload);
  db.collection('actions').save();
}

export function getActions(personId?: string): Array<ActionType> {
  let query = {};

  if (personId) {
    query = { person_id: personId };
  }

  return db.collection('actions').find(query);
}

export function removeActions() {
  db.collection('actions').remove();
  db.collection('actions').save();
}

export function removeAction(personId: string) {
  db.collection('actions').remove({ person_id: personId });
  db.collection('actions').save();
}

export function createPersons(persons: Array<PersonType>) {
  const collection = db.collection('persons');
  collection.insert(persons);
  collection.save();
}

export function createMatches(data: Array<MatchType>) {
  const collection = db.collection('matches');
  collection.insert(data);
  collection.save();
}

export function createMatch(match: Object) {
  const parsedMatch: MatchType = parseMatch(match, true);
  const parsedPerson: PersonType = parsePerson(match.person);

  createMatches([parsedMatch]);
  createPersons([parsedPerson]);
}

export function updateMatch(matchId: string, payload: Object) {
  console.log('update', matchId, payload);
  db.collection('matches').updateById(matchId, payload);
  db.collection('matches').save();
}

export function updatePerson(personId: string, payload: Object) {
  db.collection('persons').updateById(personId, parsePerson(payload));
  db.collection('persons').save();
}

export function removeMessage(_id: string) {
  db.collection('messages').remove({ _id });
  db.collection('messages').save();
}

export function removeMatch(_id: string) {
  const removedMatch = db.collection('matches').remove({ _id });
  db.collection('messages').remove({ match_id: _id });
  db.collection('persons').remove({ _id: removedMatch.person_id });

  db.collection('matches').save();
  db.collection('messages').save();
  db.collection('persons').save();
}

export function purge() {
  db.collection('matches').remove();
  db.collection('messages').remove();
  db.collection('persons').remove();

  db.collection('matches').save();
  db.collection('messages').save();
  db.collection('persons').save();

  removeActions();
}

export default create;
<|endoftext|>


<commit_before>import Ember from 'ember';
import Util from 'ember-cli-pagination/util';
import LockToRange from 'ember-cli-pagination/watch/lock-to-range';
import { QueryParamsForBackend, ChangeMeta } from './mapping';
import PageMixin from '../page-mixin';

var ArrayProxyPromiseMixin = Ember.Mixin.create(Ember.PromiseProxyMixin, {
  then: function(success,failure) {
    var promise = this.get('promise');
    var me = this;

    promise.then(function() {
      success(me);
    }, failure);
  }
});

export default Ember.ArrayProxy.extend(PageMixin, Ember.Evented, ArrayProxyPromiseMixin, {
  page: 1,
  paramMapping: Ember.computed(() => {
    return {};
  }),

  init: function() {
    var initCallback = this.get('initCallback');
    if (initCallback) {
      initCallback(this);
    }

    try {
      this.get('promise');
    }
    catch (e) {
      this.set('promise', this.fetchContent());
    }
  },

  addParamMapping: function(key,mappedKey,mappingFunc) {
    var paramMapping = this.get('paramMapping') || {};
    if (mappingFunc) {
      paramMapping[key] = [mappedKey,mappingFunc];
    }
    else {
      paramMapping[key] = mappedKey;
    }
    this.set('paramMapping',paramMapping);
    this.incrementProperty('paramsForBackendCounter');
    //this.pageChanged();
  },

  addQueryParamMapping: function(key,mappedKey,mappingFunc) {
    return this.addParamMapping(key,mappedKey,mappingFunc);
  },

  addMetaResponseMapping: function(key,mappedKey,mappingFunc) {
    return this.addParamMapping(key,mappedKey,mappingFunc);
  },

  paramsForBackend: Ember.computed('page','perPage','paramMapping','paramsForBackendCounter', function() {
    var paramsObj = QueryParamsForBackend.create({page: this.getPage(),
                                                  perPage: this.getPerPage(),
                                                  paramMapping: this.get('paramMapping')});
    var ops = paramsObj.make();

    // take the otherParams hash and add the values at the same level as page/perPage
    ops = Util.mergeHashes(ops,this.get('otherParams')||{});

    return ops;
  }),

  rawFindFromStore: function() {
    var store = this.get('store');
    var modelName = this.get('modelName');

    var ops = this.get('paramsForBackend');
    var res = store.query(modelName, ops);

    return res;
  },

  fetchContent: function() {
    this.set("loading",true);
    var res = this.rawFindFromStore();
    this.incrementProperty("numRemoteCalls");
    var me = this;

    res.then(function(rows) {
      var metaObj = ChangeMeta.create({paramMapping: me.get('paramMapping'),
                                       meta: rows.meta,
                                       page: me.getPage(),
                                       perPage: me.getPerPage()});

      me.set("loading",false);
      return me.set("meta", metaObj.make());

    }, function(error) {
      Util.log("PagedRemoteArray#fetchContent error " + error);
      me.set("loading",false);
    });

    return res;
  },

  totalPages: Ember.computed.alias("meta.total_pages"),

  pageChanged: Ember.observer("page", "perPage", function() {
    this.set("promise", this.fetchContent());
  }),

  lockToRange: function() {
    LockToRange.watch(this);
  },

  watchPage: Ember.observer('page','totalPages', function() {
    var page = this.get('page');
    var totalPages = this.get('totalPages');
    if (parseInt(totalPages) <= 0) {
      return;
    }

    this.trigger('pageChanged',page);

    if (page < 1 || page > totalPages) {
      this.trigger('invalidPage',{page: page, totalPages: totalPages, array: this});
    }
  }),

  setOtherParam: function(k,v) {
    if (!this.get('otherParams')) {
      this.set('otherParams',{});
    }

    this.get('otherParams')[k] = v;
    this.incrementProperty('paramsForBackendCounter');
    Ember.run.once(this,"pageChanged");
  }
});
<commit_msg>Rebase fix double request bug<commit_after>import Ember from 'ember';
import Util from 'ember-cli-pagination/util';
import LockToRange from 'ember-cli-pagination/watch/lock-to-range';
import { QueryParamsForBackend, ChangeMeta } from './mapping';
import PageMixin from '../page-mixin';

var ArrayProxyPromiseMixin = Ember.Mixin.create(Ember.PromiseProxyMixin, {
  then: function(success,failure) {
    var promise = this.get('promise');
    var me = this;

    promise.then(function() {
      success(me);
    }, failure);
  }
});

export default Ember.ArrayProxy.extend(PageMixin, Ember.Evented, ArrayProxyPromiseMixin, {
  page: 1,
  paramMapping: Ember.computed(() => {
    return {};
  }),

  init: function() {
    var initCallback = this.get('initCallback');
    if (initCallback) {
      initCallback(this);
    }

    try {
      this.get('promise');
    }
    catch (e) {
      this.set('promise', this.fetchContent());
    }
  },

  addParamMapping: function(key,mappedKey,mappingFunc) {
    var paramMapping = this.get('paramMapping') || {};
    if (mappingFunc) {
      paramMapping[key] = [mappedKey,mappingFunc];
    }
    else {
      paramMapping[key] = mappedKey;
    }
    this.set('paramMapping',paramMapping);
    this.incrementProperty('paramsForBackendCounter');
    //this.pageChanged();
  },

  addQueryParamMapping: function(key,mappedKey,mappingFunc) {
    return this.addParamMapping(key,mappedKey,mappingFunc);
  },

  addMetaResponseMapping: function(key,mappedKey,mappingFunc) {
    return this.addParamMapping(key,mappedKey,mappingFunc);
  },

  paramsForBackend: Ember.computed('page','perPage','paramMapping','paramsForBackendCounter', function() {
    var paramsObj = QueryParamsForBackend.create({page: this.getPage(),
                                                  perPage: this.getPerPage(),
                                                  paramMapping: this.get('paramMapping')});
    var ops = paramsObj.make();

    // take the otherParams hash and add the values at the same level as page/perPage
    ops = Util.mergeHashes(ops,this.get('otherParams')||{});

    return ops;
  }),

  rawFindFromStore: function() {
    var store = this.get('store');
    var modelName = this.get('modelName');

    var ops = this.get('paramsForBackend');
    var res = store.query(modelName, ops);

    return res;
  },

  fetchContent: function() {
    this.set("loading",true);
    var res = this.rawFindFromStore();
    this.incrementProperty("numRemoteCalls");
    var me = this;

    res.then(function(rows) {
      var metaObj = ChangeMeta.create({paramMapping: me.get('paramMapping'),
                                       meta: rows.meta,
                                       page: me.getPage(),
                                       perPage: me.getPerPage()});

      me.set("loading",false);
      return me.set("meta", metaObj.make());

    }, function(error) {
      Util.log("PagedRemoteArray#fetchContent error " + error);
      me.set("loading",false);
    });

    return res;
  },

  totalPages: Ember.computed.alias("meta.total_pages"),

  lastPage: null,

  pageChanged: Ember.observer("page", "perPage", function() {
    var page = this.get('page');
    var lastPage = this.get('lastPage');
    if (lastPage !== page) {
      this.set('lastPage', page);
      this.set("promise", this.fetchContent());
    }
  }),

  lockToRange: function() {
    LockToRange.watch(this);
  },

  watchPage: Ember.observer('page','totalPages', function() {
    var page = this.get('page');
    var totalPages = this.get('totalPages');
    if (parseInt(totalPages) <= 0) {
      return;
    }

    this.trigger('pageChanged',page);

    if (page < 1 || page > totalPages) {
      this.trigger('invalidPage',{page: page, totalPages: totalPages, array: this});
    }
  }),

  setOtherParam: function(k,v) {
    if (!this.get('otherParams')) {
      this.set('otherParams',{});
    }

    this.get('otherParams')[k] = v;
    this.incrementProperty('paramsForBackendCounter');
    Ember.run.once(this,"pageChanged");
  }
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Route, Switch } from 'react-router'

import {
  isAdmin,
  isAuthenticated,
  isParticipant,
  shouldNotBeAuthenticated,
} from './auth'

import { withConfig } from './containers'

import {
  Activity,
  Admin,
  Calendar,
  ConversationsIndex,
  ConversationsNew,
  ConversationsShow,
  EventsEdit,
  EventsNew,
  EventsShow,
  ForgotPassword,
  Home,
  Login,
  NotFound,
  Page,
  PlacesEdit,
  PlacesIndex,
  PlacesNew,
  PlacesShow,
  Profile,
  Register,
  ResetPassword,
  ResourcesEdit,
  ResourcesIndex,
  ResourcesNew,
  Stream,
  Tickets,
} from './views'

export default class Routes extends Component {
  render() {
    return (
      <main role="main">
        <Switch>
          <Route component={Home} exact={true} path="/" />
          <Route component={shouldNotBeAuthenticated(Login)} path="/login" />
          <Route component={withConfig('isSignUpParticipantEnabled', shouldNotBeAuthenticated(Register))} path="/register" />
          <Route component={withConfig('isSignUpVisitorEnabled', shouldNotBeAuthenticated(Tickets))} path="/tickets" />
          <Route component={shouldNotBeAuthenticated(ForgotPassword)} path="/forgot" />
          <Route component={shouldNotBeAuthenticated(ResetPassword)} path="/reset/:token" />
          <Route component={Page} path="/pages/:slug" />
          <Route component={Calendar} path="/calendar" />
          <Route component={isAuthenticated(Profile)} path="/profile" />
          <Route component={withConfig('gifStreamServerUrl', isAuthenticated(Stream))} path="/stream" />
          <Route component={withConfig('isActivityStreamEnabled', isParticipant(Activity))} path="/activity" />
          <Route component={isParticipant(EventsNew)} path="/new/event" />
          <Route component={isParticipant(PlacesNew)} path="/new/place" />
          <Route component={isParticipant(ResourcesNew)} path="/new/resource" />
          <Route component={isParticipant(EventsEdit)} path="/events/:slug/edit" />
          <Route component={isAuthenticated(EventsShow)} path="/events/:slug" />
          <Route component={isParticipant(PlacesEdit)} path="/places/:slug/edit" />
          <Route component={isParticipant(PlacesShow)} path="/places/:slug" />
          <Route component={isParticipant(PlacesIndex)} path="/places" />
          <Route component={isParticipant(ResourcesEdit)} path="/resources/:slug/edit" />
          <Route component={isParticipant(ResourcesIndex)} path="/resources" />
          <Route component={withConfig('isInboxEnabled', isParticipant(ConversationsNew))} path="/inbox/new" />
          <Route component={withConfig('isInboxEnabled', isParticipant(ConversationsShow))} path="/inbox/conversations/:id" />
          <Route component={withConfig('isInboxEnabled', isParticipant(ConversationsIndex))} path="/inbox" />
          <Route component={isAdmin(Admin)} path="/admin" />
          <Route component={NotFound} />
        </Switch>
      </main>
    )
  }
}
<commit_msg>Use new free festival auth checks in routes<commit_after>import React, { Component } from 'react'
import { Route, Switch } from 'react-router'

import {
  isAdmin,
  isAuthenticated,
  isAuthenticatedOrFestivalIsFree,
  isParticipant,
  isParticipantOrFestivalIsFree,
  shouldNotBeAuthenticated,
} from './auth'

import { withConfig } from './containers'

import {
  Activity,
  Admin,
  Calendar,
  ConversationsIndex,
  ConversationsNew,
  ConversationsShow,
  EventsEdit,
  EventsNew,
  EventsShow,
  ForgotPassword,
  Home,
  Login,
  NotFound,
  Page,
  PlacesEdit,
  PlacesIndex,
  PlacesNew,
  PlacesShow,
  Profile,
  Register,
  ResetPassword,
  ResourcesEdit,
  ResourcesIndex,
  ResourcesNew,
  Stream,
  Tickets,
} from './views'

export default class Routes extends Component {
  render() {
    return (
      <main role="main">
        <Switch>
          <Route component={Home} exact={true} path="/" />
          <Route component={shouldNotBeAuthenticated(Login)} path="/login" />
          <Route component={withConfig('isSignUpParticipantEnabled', shouldNotBeAuthenticated(Register))} path="/register" />
          <Route component={withConfig('isSignUpVisitorEnabled', shouldNotBeAuthenticated(Tickets))} path="/tickets" />
          <Route component={shouldNotBeAuthenticated(ForgotPassword)} path="/forgot" />
          <Route component={shouldNotBeAuthenticated(ResetPassword)} path="/reset/:token" />
          <Route component={Page} path="/pages/:slug" />
          <Route component={Calendar} path="/calendar" />
          <Route component={isAuthenticated(Profile)} path="/profile" />
          <Route component={withConfig('gifStreamServerUrl', isAuthenticated(Stream))} path="/stream" />
          <Route component={withConfig('isActivityStreamEnabled', isParticipant(Activity))} path="/activity" />
          <Route component={isParticipant(EventsNew)} path="/new/event" />
          <Route component={isParticipant(PlacesNew)} path="/new/place" />
          <Route component={isParticipant(ResourcesNew)} path="/new/resource" />
          <Route component={isParticipant(EventsEdit)} path="/events/:slug/edit" />
          <Route component={isAuthenticatedOrFestivalIsFree(EventsShow)} path="/events/:slug" />
          <Route component={isAuthenticatedOrFestivalIsFree(EventsShow)} path="/eventisfree/:slug" />
          <Route component={isParticipant(PlacesEdit)} path="/places/:slug/edit" />
          <Route component={isParticipantOrFestivalIsFree(PlacesShow)} path="/places/:slug" />
          <Route component={isParticipantOrFestivalIsFree(PlacesIndex)} path="/places" />
          <Route component={isParticipant(ResourcesEdit)} path="/resources/:slug/edit" />
          <Route component={isParticipant(ResourcesIndex)} path="/resources" />
          <Route component={withConfig('isInboxEnabled', isParticipant(ConversationsNew))} path="/inbox/new" />
          <Route component={withConfig('isInboxEnabled', isParticipant(ConversationsShow))} path="/inbox/conversations/:id" />
          <Route component={withConfig('isInboxEnabled', isParticipant(ConversationsIndex))} path="/inbox" />
          <Route component={isAdmin(Admin)} path="/admin" />
          <Route component={NotFound} />
        </Switch>
      </main>
    )
  }
}
<|endoftext|>