<commit_before>// WontoMedia - a wontology web application
// Copyright (C) 2009 - Glen E. Ivey
//    www.wontology.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License version
// 3 as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the file COPYING and/or LICENSE.  If not,
// see <http://www.gnu.org/licenses/>.

// function to highlight help text based on Type <select> element state
function typeSelectOnchange(){
  var sel = $('node_sti_type');
  var tags = [ "category_title", "category_desc",
               "item_title",     "item_desc",
               "property_title", "property_desc" ];

  for (var c=0; c != tags.length; c++)
    $(tags[c]).className = "";

  if (sel.value == "ClassNode"){
    $("category_title").className = "titleSelectedItemDescription";
    $("category_desc").className = "bodySelectedItemDescription";
  }
  else if (sel.value == "ItemNode"){
    $("item_title").className = "titleSelectedItemDescription";
    $("item_desc").className = "bodySelectedItemDescription";
  }
  else if (sel.value == "PropertyNode"){
    $("property_title").className = "titleSelectedItemDescription";
    $("property_desc").className = "bodySelectedItemDescription";
  }
}

// package of code to implement required-inputs-can't-be-empty checks
//   (for nodes/new page)

    // define fields subject to check, order they occur in form
var requiredInputElements = [ "sti_type", "title", "name",
                              "description", "submit" ];
var inputElementNames = [ "Type selector", "Title field", "Name field",
                          "Description box", "Create button" ];

    // encoding: -1    -> haven't checked yet
    //           false -> no error
    //           true  -> required field not filled
var inputRequiredErrors = {};
for (var c=0; c < requiredInputElements.length-2; c++)
  inputRequiredErrors["node_" + requiredInputElements[c]] = -1;

function flagAsRequired(elemName){
  var req = $(elemName + "_required");
  if ( req != null ){
    req.className = "helpTextFlagged";
    $(elemName + "_error_icon").src = "/images/error_error_icon.png";
  }
  else {
    $(elemName + "_recommended").className = "helpTextFlagged";
    $(elemName + "_error_icon").src = "/images/warn_error_icon.png";
  }
}

function clearFlag(elemName){
  var req = $(elemName + "_required");
  if ( req != null )
    req.className = "";
  else
    $(elemName + "_recommended").className = "";
  $(elemName + "_error_icon").src = "/images/blank_error_icon.png";
}

    // validation function
function checkRequiredFields(e){
  var errFlag = false;
  var eId = e.id;
  var c;
  for (c=0; c   <  requiredInputElements.length &&
            eId != "node_" + requiredInputElements[c];    c++)
    ;

  if (c >= requiredInputElements.length)
    return;  // Hmmmm..... maybe not

  var lastToCheck = c-1;
  for (c=0; c <= lastToCheck; c++){
    ck = $("node_" + requiredInputElements[c]);
    if (ck.value == null || ck.value == ""){

      inputRequiredErrors["node_" + requiredInputElements[c]] = true;
      flagAsRequired(requiredInputElements[c]);

      if (c < requiredInputElements.length-2)
        errFlag = true;
    }
    else {
      inputRequiredErrors["node_" + requiredInputElements[c]] = false;
    }
  }

  if (errFlag)
    makeButtonSeemDisabled($('node_submit'));
}

function anyErrors(){
  for (var c=0; c < requiredInputElements.length-2; c++)
    if (inputRequiredErrors["node_" + requiredInputElements[c]])
      return true;
  return false;
}

function checkAField(f){
  var idStr = f.id;
  var idAry = idStr.match(/^node_(.+)$/);
  var name = idAry[1];

  if (f.value == null || f.value == ""){
    flagAsRequired(name);
    inputRequiredErrors[f.id] = true;
    if (anyErrors())
      makeButtonSeemDisabled($('node_submit'));
  }
  else {
    clearFlag(name);
    var oldErr = inputRequiredErrors[f.id];
    inputRequiredErrors[f.id] = false;
    if (oldErr && !anyErrors())
      makeButtonSeemEnabled($('node_submit'));
  }
}

function genDialog(){
  var newDialogText = "
";
  var accum = false;

  for (var c=0; c < requiredInputElements.length-2; c++){
    if (inputRequiredErrors["node_" + requiredInputElements[c]]){
      accum = true;
      newDialogText += "The " + inputElementNames[c] + " is required. ";
    }
  }

  if (accum){
    newDialogText += "
";
    Modalbox.show(newDialogText,
      { title: "Can't create this node yet",
        slideDownDuration: 0.25, slideUpDuration: 0.1 } );
  }
  return accum;
}

function makeButtonSeemEnabled(button){
  button.className = "activeButton";
}
function makeButtonSeemDisabled(button){
  button.className = "inactiveButton";
}

    // plumb validation function to relevant elements
var a = $('node_sti_type');
a.onfocus=  function(){checkRequiredFields(a);};
a.onkeypress= function(){setTimeout(checkAField, 50, a);};
a.onchange= function(){
  typeSelectOnchange();
  checkAField(a);
};

var b = $('node_title');
b.onfocus= function(){checkRequiredFields(b);};
b.onchange= function(){checkAField(b);};
b.onkeypress= function(){setTimeout(checkAField, 50, b);};
var c = $('node_name');
c.onfocus= function(){checkRequiredFields(c);};
c.onchange= function(){checkAField(c);};
c.onkeypress= function(){setTimeout(checkAField, 50, c);};
var d = $('node_description');
d.onfocus= function(){checkRequiredFields(d);};
d.onchange= function(){checkAField(d);};
d.onkeypress= function(){setTimeout(checkAField, 50, d);};

var e = $('node_submit');
e.onfocus= function(){checkRequiredFields(e);};
makeButtonSeemDisabled(e);
e.onclick = function(){
  checkRequiredFields(e);
  var errors = genDialog();

  if (errors)
    makeButtonSeemDisabled(e);
  else
    makeButtonSeemEnabled(e);
  return !errors;
}

<commit_msg>Lengthened time between keypress even for input fields and when we check the field's content.  Prior time was short enough it failed intermittently.<commit_after>// WontoMedia - a wontology web application
// Copyright (C) 2009 - Glen E. Ivey
//    www.wontology.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License version
// 3 as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the file COPYING and/or LICENSE.  If not,
// see <http://www.gnu.org/licenses/>.

// function to highlight help text based on Type <select> element state
function typeSelectOnchange(){
  var sel = $('node_sti_type');
  var tags = [ "category_title", "category_desc",
               "item_title",     "item_desc",
               "property_title", "property_desc" ];

  for (var c=0; c != tags.length; c++)
    $(tags[c]).className = "";

  if (sel.value == "ClassNode"){
    $("category_title").className = "titleSelectedItemDescription";
    $("category_desc").className = "bodySelectedItemDescription";
  }
  else if (sel.value == "ItemNode"){
    $("item_title").className = "titleSelectedItemDescription";
    $("item_desc").className = "bodySelectedItemDescription";
  }
  else if (sel.value == "PropertyNode"){
    $("property_title").className = "titleSelectedItemDescription";
    $("property_desc").className = "bodySelectedItemDescription";
  }
}

// package of code to implement required-inputs-can't-be-empty checks
//   (for nodes/new page)

    // define fields subject to check, order they occur in form
var requiredInputElements = [ "sti_type", "title", "name",
                              "description", "submit" ];
var inputElementNames = [ "Type selector", "Title field", "Name field",
                          "Description box", "Create button" ];

    // encoding: -1    -> haven't checked yet
    //           false -> no error
    //           true  -> required field not filled
var inputRequiredErrors = {};
for (var c=0; c < requiredInputElements.length-2; c++)
  inputRequiredErrors["node_" + requiredInputElements[c]] = -1;

function flagAsRequired(elemName){
  var req = $(elemName + "_required");
  if ( req != null ){
    req.className = "helpTextFlagged";
    $(elemName + "_error_icon").src = "/images/error_error_icon.png";
  }
  else {
    $(elemName + "_recommended").className = "helpTextFlagged";
    $(elemName + "_error_icon").src = "/images/warn_error_icon.png";
  }
}

function clearFlag(elemName){
  var req = $(elemName + "_required");
  if ( req != null )
    req.className = "";
  else
    $(elemName + "_recommended").className = "";
  $(elemName + "_error_icon").src = "/images/blank_error_icon.png";
}

    // validation function
function checkRequiredFields(e){
  var errFlag = false;
  var eId = e.id;
  var c;
  for (c=0; c   <  requiredInputElements.length &&
            eId != "node_" + requiredInputElements[c];    c++)
    ;

  if (c >= requiredInputElements.length)
    return;  // Hmmmm..... maybe not

  var lastToCheck = c-1;
  for (c=0; c <= lastToCheck; c++){
    ck = $("node_" + requiredInputElements[c]);
    if (ck.value == null || ck.value == ""){

      inputRequiredErrors["node_" + requiredInputElements[c]] = true;
      flagAsRequired(requiredInputElements[c]);

      if (c < requiredInputElements.length-2)
        errFlag = true;
    }
    else {
      inputRequiredErrors["node_" + requiredInputElements[c]] = false;
    }
  }

  if (errFlag)
    makeButtonSeemDisabled($('node_submit'));
}

function anyErrors(){
  for (var c=0; c < requiredInputElements.length-2; c++)
    if (inputRequiredErrors["node_" + requiredInputElements[c]])
      return true;
  return false;
}

function checkAField(f){
  var idStr = f.id;
  var idAry = idStr.match(/^node_(.+)$/);
  var name = idAry[1];

  if (f.value == null || f.value == ""){
    flagAsRequired(name);
    inputRequiredErrors[f.id] = true;
    if (anyErrors())
      makeButtonSeemDisabled($('node_submit'));
  }
  else {
    clearFlag(name);
    var oldErr = inputRequiredErrors[f.id];
    inputRequiredErrors[f.id] = false;
    if (oldErr && !anyErrors())
      makeButtonSeemEnabled($('node_submit'));
  }
}

function genDialog(){
  var newDialogText = "
";
  var accum = false;

  for (var c=0; c < requiredInputElements.length-2; c++){
    if (inputRequiredErrors["node_" + requiredInputElements[c]]){
      accum = true;
      newDialogText += "The " + inputElementNames[c] + " is required. ";
    }
  }

  if (accum){
    newDialogText += "
";
    Modalbox.show(newDialogText,
      { title: "Can't create this node yet",
        slideDownDuration: 0.25, slideUpDuration: 0.1 } );
  }
  return accum;
}

function makeButtonSeemEnabled(button){
  button.className = "activeButton";
}
function makeButtonSeemDisabled(button){
  button.className = "inactiveButton";
}

  // after keypress events, have to wait for browser to update the input field
  // before we check it (delay in ms)
var dly = 80;

    // plumb validation function to relevant elements
var a = $('node_sti_type');
a.onfocus=  function(){checkRequiredFields(a);};
a.onkeypress= function(){setTimeout(checkAField, dly, a);};
a.onchange= function(){
  typeSelectOnchange();
  checkAField(a);
};

var b = $('node_title');
b.onfocus= function(){checkRequiredFields(b);};
b.onchange= function(){checkAField(b);};
b.onkeypress= function(){setTimeout(checkAField, dly, b);};
var c = $('node_name');
c.onfocus= function(){checkRequiredFields(c);};
c.onchange= function(){checkAField(c);};
c.onkeypress= function(){setTimeout(checkAField, dly, c);};
var d = $('node_description');
d.onfocus= function(){checkRequiredFields(d);};
d.onchange= function(){checkAField(d);};
d.onkeypress= function(){setTimeout(checkAField, dly, d);};

var e = $('node_submit');
e.onfocus= function(){checkRequiredFields(e);};
makeButtonSeemDisabled(e);
e.onclick = function(){
  checkRequiredFields(e);
  var errors = genDialog();

  if (errors)
    makeButtonSeemDisabled(e);
  else
    makeButtonSeemEnabled(e);
  return !errors;
}

<|endoftext|>


<commit_before>// Dep: [socket.io-client]/socket.io.js
// Dep: [KadOH]/core/stateeventemitter

(function(exports, io) {

  var KadOH             = exports,
      StateEventEmitter = KadOH.core.StateEventEmitter;

  if (!io) {
    KadOH.log.warn('socket.io not defined : no transport');
    return;
  }

  KadOH.transport = KadOH.transport || {};
  KadOH.transport.SimUDP = StateEventEmitter.extend({

    initialize : function(server_name, options) {
      this.supr();

      this.server_name = (server_name || '') + '/SimUDP';
      this.io_options = options;
      this.setState('disconnected');
    },

    connect : function() {
      this.socket = io.connect(this.server_name, this.io_options);
      var self = this;

      this.socket.once('whoami', function(resp) {
        self.iam = resp;
        self.setState('connected', self.iam);
      });

      this.socket.emit('whoami');
    },

    disconnect: function() {
      this.socket.disconnectSync();
      this.setState('disconnected');
    },

    send : function(dst, message) {
      if (this.stateIsNot('connected')) {
        throw new Error('SimUDP transport layer not connected.');
      }

      if ('function' === typeof message.stringify) {
        message = message.stringify();
      }

      message = {
        dst: dst,
        msg: message
      };

      this.socket.emit('packet', message);
    },

    listen : function(fn, context) {
      if (this.stateIsNot('connected')) {
        throw new Error('SimUDP transport layer not connected.');
      }

      context = context || this;
      this.socket.on('packet', function() {
        fn.apply(context, arguments);
      });
    }

  });

})( 'object' === typeof module ? module.exports : (this.KadOH = this.KadOH || {}),
    'object' === typeof this.io ? this.io       : (require ? require('socket.io-client') : false));
<commit_msg>simudp : dat-in data-out event<commit_after>// Dep: [socket.io-client]/socket.io.js
// Dep: [KadOH]/core/stateeventemitter

(function(exports, io) {

  var KadOH             = exports,
      StateEventEmitter = KadOH.core.StateEventEmitter;

  if (!io) {
    KadOH.log.warn('socket.io not defined : no transport');
    return;
  }

  KadOH.transport = KadOH.transport || {};
  KadOH.transport.SimUDP = StateEventEmitter.extend({

    initialize : function(server_name, options) {
      this.supr();

      this.server_name = (server_name || '') + '/SimUDP';
      this.io_options = options;
      this.setState('disconnected');
    },

    connect : function() {
      this.socket = io.connect(this.server_name, this.io_options);
      var self = this;

      this.socket.once('whoami', function(resp) {
        self.iam = resp;
        self.setState('connected', self.iam);
      });

      this.socket.emit('whoami');
    },

    disconnect: function() {
      this.socket.disconnectSync();
      this.setState('disconnected');
    },

    send : function(dst, message) {
      if (this.stateIsNot('connected')) {
        throw new Error('SimUDP transport layer not connected.');
      }

      if ('function' === typeof message.stringify) {
        message = message.stringify();
      }

      message = {
        dst: dst,
        msg: message
      };

      this.emit('data-out', JSON.stringify(message));
      this.socket.emit('packet', message);
    },

    listen : function(fn, context) {
      if (this.stateIsNot('connected')) {
        throw new Error('SimUDP transport layer not connected.');
      }

      context = context || this;
      var self = this;
      this.socket.on('packet', function() {
        self.emit('data-in', JSON.stringify(arguments[0]));
        fn.apply(context, arguments);
      });
    }

  });

})( 'object' === typeof module ? module.exports : (this.KadOH = this.KadOH || {}),
    'object' === typeof this.io ? this.io       : (require ? require('socket.io-client') : false));
<|endoftext|>


<commit_before>var AppView = Backbone.View.extend({

  initialize: function() {
    _.bindAll(this, 'addOne', 'addAll', 'render');

    window.Project.stories.bind('add', this.addOne);
    window.Project.stories.bind('reset', this.addAll);
    window.Project.stories.bind('all', this.render);

    window.Project.stories.fetch();
  },

  addOne: function(story, column) {
    if (typeof column === 'undefined') {
      column = story.column();
    }
    var view = new StoryView({model: story});
    $(column).append(view.render().el);
  },

  addAll: function() {
    $('#done').html("");
    $('#in_progress').html("");
    $('#backlog').html("");
    $('#chilly_bin').html("");

    //
    // Done column
    //
    var that = this;
    var done_iterations = _.groupBy(window.Project.stories.column('#done'),
                                    function(story) {
                                      return story.iterationNumber();
                                    });

    // There will sometimes be gaps in the done iterations, i.e. no work
    // may have been accepted in a given iteration, and it will therefore
    // not appear in the set.  Store this to iterate over those gaps and
    // insert empty iterations.
    var last_iteration = new Iteration({'number': 0});

    _.each(done_iterations, function(stories, iterationNumber) {

      var iteration = new Iteration({
        'number': iterationNumber, 'stories': stories, column: '#done'
      });

      window.Project.iterations.push(iteration);

      that.fillInEmptyIterations('#done', last_iteration, iteration);
      last_iteration = iteration;

      $('#done').append(that.iterationDiv(iteration));
      _.each(stories, function(story) {that.addOne(story)});
    });

    // Fill in any remaining empty iterations in the done column
    var currentIteration = new Iteration({
      'number': window.Project.currentIterationNumber(),
      'stories': window.Project.stories.column('#in_progress')
    });
    this.fillInEmptyIterations('#done', last_iteration, currentIteration);

    //
    // In progress column
    //
    // FIXME - Show completed/total points
    $('#in_progress').append(that.iterationDiv(currentIteration));
    _.each(window.Project.stories.column('#in_progress'), function(story) {
      that.addOne(story);
    });

    //
    // Backlog column
    //
    var backlogIteration = new Iteration({
      'number': currentIteration.get('number') + 1,
      'rendered': false,
      'maximum_points': window.Project.velocity()
    });
    _.each(window.Project.stories.column('#backlog'), function(story) {

      if (currentIteration.canTakeStory(story)) {
        currentIteration.get('stories').push(story);
        that.addOne(story, '#in_progress');
        return;
      }

      if (!backlogIteration.canTakeStory(story)) {
        // The iteration is full, render it
        $('#backlog').append(that.iterationDiv(backlogIteration));
        _.each(backlogIteration.get('stories'), function(iterationStory) {
          that.addOne(iterationStory);
        });
        backlogIteration.set({'rendered': true});

        var nextNumber = backlogIteration.get('number') + 1 + Math.ceil(backlogIteration.overflowsBy() / window.Project.velocity());

        var nextIteration = new Iteration({
          'number': nextNumber,
          'rendered': false,
          'maximum_points': window.Project.velocity()
        });

        // If the iteration overflowed, create enough empty iterations to
        // accommodate the surplus.  For example, if the project velocity
        // is 1, and the last iteration contained 1 5 point story, we'll
        // need 4 empty iterations.
        //
        that.fillInEmptyIterations('#backlog', backlogIteration, nextIteration);
        backlogIteration = nextIteration;
      }

      backlogIteration.get('stories').push(story);
      //that.addOne(story);
    });

    // Render the backlog final backlog iteration if it isn't already
    $('#backlog').append(that.iterationDiv(backlogIteration));
    _.each(backlogIteration.get('stories'), function(story) {
      that.addOne(story);
    });
    backlogIteration.set({'rendered': true});

    _.each(window.Project.stories.column('#chilly_bin'), function(story) {
      that.addOne(story)
    });
  },

  // Creates a set of empty iterations in column, with iteration numbers
  // starting at start and ending at end
  fillInEmptyIterations: function(column, start, end) {
    var el = $(column);
    var missing_range = _.range(
      parseInt(start.get('number')) + 1,
      parseInt(end.get('number'))
    );
    var that = this;
    _.each(missing_range, function(missing_iteration_number) {
      var iteration = new Iteration({
        'number': missing_iteration_number, 'column': column
      });
      window.Project.iterations.push(iteration);
      el.append(that.iterationDiv(iteration));
    });
  },

  scaleToViewport: function() {
    var storyTableTop = $('table.stories tbody').offset().top;
    // Extra for the bottom padding and the
    var extra = 100;
    var height = $(window).height() - (storyTableTop + extra);
    $('.storycolumn').css('height', height + 'px');
  },

  // FIXME - Make a view
  iterationDiv: function(iteration) {
    // FIXME Make a model method
    var iteration_date = window.Project.getDateForIterationNumber(iteration.get('number'));
    var points_markup = '' + iteration.points() + ' points';
    return '
' + iteration.get('number') + ' - ' + iteration_date.toDateString() + points_markup + '
'
  },

  notice: function(message) {
    $.gritter.add(message);
  }
});
<commit_msg>Check column arg is a string in AppView.addOne()<commit_after>var AppView = Backbone.View.extend({

  initialize: function() {
    _.bindAll(this, 'addOne', 'addAll', 'render');

    window.Project.stories.bind('add', this.addOne);
    window.Project.stories.bind('reset', this.addAll);
    window.Project.stories.bind('all', this.render);

    window.Project.stories.fetch();
  },

  addOne: function(story, column) {
    // If column is blank determine it from the story.  When the add event
    // is bound on a collection, the callback send the collection as the
    // second argument, so also check that column is a string and not an
    // object for those cases.
    if (typeof column === 'undefined' || typeof column !== 'string') {
      column = story.column();
    }
    var view = new StoryView({model: story});
    $(column).append(view.render().el);
  },

  addAll: function() {
    $('#done').html("");
    $('#in_progress').html("");
    $('#backlog').html("");
    $('#chilly_bin').html("");

    //
    // Done column
    //
    var that = this;
    var done_iterations = _.groupBy(window.Project.stories.column('#done'),
                                    function(story) {
                                      return story.iterationNumber();
                                    });

    // There will sometimes be gaps in the done iterations, i.e. no work
    // may have been accepted in a given iteration, and it will therefore
    // not appear in the set.  Store this to iterate over those gaps and
    // insert empty iterations.
    var last_iteration = new Iteration({'number': 0});

    _.each(done_iterations, function(stories, iterationNumber) {

      var iteration = new Iteration({
        'number': iterationNumber, 'stories': stories, column: '#done'
      });

      window.Project.iterations.push(iteration);

      that.fillInEmptyIterations('#done', last_iteration, iteration);
      last_iteration = iteration;

      $('#done').append(that.iterationDiv(iteration));
      _.each(stories, function(story) {that.addOne(story)});
    });

    // Fill in any remaining empty iterations in the done column
    var currentIteration = new Iteration({
      'number': window.Project.currentIterationNumber(),
      'stories': window.Project.stories.column('#in_progress')
    });
    this.fillInEmptyIterations('#done', last_iteration, currentIteration);

    //
    // In progress column
    //
    // FIXME - Show completed/total points
    $('#in_progress').append(that.iterationDiv(currentIteration));
    _.each(window.Project.stories.column('#in_progress'), function(story) {
      that.addOne(story);
    });

    //
    // Backlog column
    //
    var backlogIteration = new Iteration({
      'number': currentIteration.get('number') + 1,
      'rendered': false,
      'maximum_points': window.Project.velocity()
    });
    _.each(window.Project.stories.column('#backlog'), function(story) {

      if (currentIteration.canTakeStory(story)) {
        currentIteration.get('stories').push(story);
        that.addOne(story, '#in_progress');
        return;
      }

      if (!backlogIteration.canTakeStory(story)) {
        // The iteration is full, render it
        $('#backlog').append(that.iterationDiv(backlogIteration));
        _.each(backlogIteration.get('stories'), function(iterationStory) {
          that.addOne(iterationStory);
        });
        backlogIteration.set({'rendered': true});

        var nextNumber = backlogIteration.get('number') + 1 + Math.ceil(backlogIteration.overflowsBy() / window.Project.velocity());

        var nextIteration = new Iteration({
          'number': nextNumber,
          'rendered': false,
          'maximum_points': window.Project.velocity()
        });

        // If the iteration overflowed, create enough empty iterations to
        // accommodate the surplus.  For example, if the project velocity
        // is 1, and the last iteration contained 1 5 point story, we'll
        // need 4 empty iterations.
        //
        that.fillInEmptyIterations('#backlog', backlogIteration, nextIteration);
        backlogIteration = nextIteration;
      }

      backlogIteration.get('stories').push(story);
      //that.addOne(story);
    });

    // Render the backlog final backlog iteration if it isn't already
    $('#backlog').append(that.iterationDiv(backlogIteration));
    _.each(backlogIteration.get('stories'), function(story) {
      that.addOne(story);
    });
    backlogIteration.set({'rendered': true});

    _.each(window.Project.stories.column('#chilly_bin'), function(story) {
      that.addOne(story)
    });
  },

  // Creates a set of empty iterations in column, with iteration numbers
  // starting at start and ending at end
  fillInEmptyIterations: function(column, start, end) {
    var el = $(column);
    var missing_range = _.range(
      parseInt(start.get('number')) + 1,
      parseInt(end.get('number'))
    );
    var that = this;
    _.each(missing_range, function(missing_iteration_number) {
      var iteration = new Iteration({
        'number': missing_iteration_number, 'column': column
      });
      window.Project.iterations.push(iteration);
      el.append(that.iterationDiv(iteration));
    });
  },

  scaleToViewport: function() {
    var storyTableTop = $('table.stories tbody').offset().top;
    // Extra for the bottom padding and the
    var extra = 100;
    var height = $(window).height() - (storyTableTop + extra);
    $('.storycolumn').css('height', height + 'px');
  },

  // FIXME - Make a view
  iterationDiv: function(iteration) {
    // FIXME Make a model method
    var iteration_date = window.Project.getDateForIterationNumber(iteration.get('number'));
    var points_markup = '' + iteration.points() + ' points';
    return '
' + iteration.get('number') + ' - ' + iteration_date.toDateString() + points_markup + '
'
  },

  notice: function(message) {
    $.gritter.add(message);
  }
});
<|endoftext|>


<commit_before>const React = require("react");
const { DOM: dom } = React;
const { connect } = require("react-redux");
const { bindActionCreators } = require("redux");
const actions = require("../actions");
const { getSelectedSource } = require("../selectors");

function debugBtn(onClick, type, className = "active") {
  className = `${type} ${className}`;

  return dom.span(
    { onClick, className, key: type },
    dom.img({ src: `images/${type}.svg` })
  );
}

function SourceFooter({ togglePrettyPrint, selectedSource }) {
  const commandsEnabled = selectedSource ? "" : "disabled";

  return dom.div(
    {
      className: "source-footer"
    },
    dom.div({ className: "command-bar" },
      debugBtn(
        () => {},
        "blackBox",
        commandsEnabled
      ),
      debugBtn(
        () => togglePrettyPrint(selectedSource.get("id")),
        "prettyPrint",
        commandsEnabled
      )
    )
  );
}

module.exports = connect(
  state => ({
    selectedSource: getSelectedSource(state),
  }),
  dispatch => bindActionCreators(actions, dispatch)
)(SourceFooter);
<commit_msg>add feature flag for blackbox icon (#437) (#477)<commit_after>const React = require("react");
const { DOM: dom } = React;
const { connect } = require("react-redux");
const { bindActionCreators } = require("redux");
const actions = require("../actions");
const { isEnabled } = require("../feature");
const { getSelectedSource } = require("../selectors");

function debugBtn(onClick, type, className = "active") {
  className = `${type} ${className}`;

  return dom.span(
    { onClick, className, key: type },
    dom.img({ src: `images/${type}.svg` })
  );
}

function SourceFooter({ togglePrettyPrint, selectedSource }) {
  const commandsEnabled = selectedSource ? "" : "disabled";

  return dom.div(
    {
      className: "source-footer"
    },
    dom.div({ className: "command-bar" },
      isEnabled("features.blackbox") ? debugBtn(
        () => {},
        "blackBox",
        commandsEnabled
      ) : null,
      debugBtn(
        () => togglePrettyPrint(selectedSource.get("id")),
        "prettyPrint",
        commandsEnabled
      )
    )
  );
}

module.exports = connect(
  state => ({
    selectedSource: getSelectedSource(state),
  }),
  dispatch => bindActionCreators(actions, dispatch)
)(SourceFooter);
<|endoftext|>


<commit_before>queue()
  .defer(d3.json, "/api/scholar_khan_points")
  // .defer(d3.json, "khan_points.json")
  .await(makeGraphs);

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

function makeGraphs(error, data) {

  khanDataTable = dc.dataTable('#khanDataTable');
  khanRowChart = dc.rowChart('#khanRowChart');

  // filteredRowChart = dc.rowChart('#grade-row-chart-filtered');

  var DTSformat = d3.time.format("%Y-%m-%d");

  // set up data
  data.forEach(function(d) {
    d.formattedDate = DTSformat.parse(d.activity_date.substr(0, 10));
    d.month = d3.time.month(d.formattedDate);
    // d.pointsPerDate = undefined || d.points_per_date;
  });

  // console.log(data);

  var ndx = crossfilter(data);

  var emailDimension = ndx.dimension(function(d) { return d.email; });

  var gradeDimension = ndx.dimension(function(d) { return d.grade; });
  // console.log(gradeDimension.top(10));

  //////  update to count unique students
  var gradeGroup = gradeDimension.group().reduce(
    function (p, d) {
      ++p.count;
      p.totalPoints += +d.points_per_date;
      return p;
    },
    function (p, d) {
      --p.count;
      p.totalPoints -= +d.points_per_date;
      return p;
    },
    function () {
      return {
        count: 0,
        totalPoints: 0,
      };
    });

  // console.log(gradeGroup.top(10));

  khanRowChart
    .width(400)
    .height(200)
    .margins({top: 20, left: 10, right: 10, bottom: 20})
    .dimension(gradeDimension)
    .group(gradeGroup)
    .valueAccessor(function(d) { return d.value.totalPoints; })
    .ordering(function(d) { return -d.value.totalPoints })
    .label(function(d) {
      return 'Total Points for Grade ' +
        d.key + ': ' +
        d.value.totalPoints + ' (' +
        d.value.count + ' students)';
    })
    .elasticX(true)
    .xAxis()
    .ticks(4);

  khanDataTable
    .width(400)
    .height(200)
    .dimension(emailDimension)
    .size(10)
    .group(function(d) { return ''; })
    .columns([
      // function(d) { return '    '; },
      function(d) { return d.student_name; },
      function(d) { return + d.points_per_date; },
      function(d) { return d.grade; }
    ])
    .sortBy(function(d) { return +d.points_per_date; })
    .order(d3.descending);

    //
    // var dateDim = ndx.dimension(
    //   function(x) {
    //     return x.month;
    //   }
    // );

    //
    // var dateDim = {
    //   grade: ndx.dimension(function(d) { return d.grade }),
    //   month: ndx.dimension(function(d) { return d.month }),
    //   id:  ndx.dimension(function(d) { return JSON.stringify([d.grade, d.month]); })
    // }

    // console.log(dateDim.grade.top(10));
    // console.log(dateDim.month.top(10));
    // console.log(dateDim.id.top(10));

    // var gradeMonthGroup = dateDim.id.group();
    // gradeMonthGroup.all().forEach(function(d) {
    //   d.key = JSON.parse(d.key);
    // });

    // var group = dateDim.id.group();
    //
    // group.all().forEach(
    //   function(d) {
    //     d.key = JSON.parse(d.key);
    //   }
    // );
    //
    // var sum = group.reduceSum(function(d) {return d.points_per_date;}).all();

    // console.log('sum');
    // console.log(sum);

    // var gradeMonthGroup = dateDim.id.group().reduce(
    //   function (p, d) {
    //     ++p.count;
    //     p.totalPoints += +d.points_per_date;
    //     return p;
    //   },
    //   function (p, d) {
    //     --p.count;
    //     p.totalPoints -= +d.points_per_date;
    //     return p;
    //   },
    //   function () {
    //     return {
    //       count: 0,
    //       totalPoints: 0,
    //     };
    //   });
    //
    // console.log('gradeMonthGroup');
    // console.log(gradeMonthGroup.top(10));

    //
    // function double_reduce(dim, groupf, firstf) {
    //   return {
    //     all: function() {
    //       var recs = dim.bottom(Infinity);
    //       var hit = {};
    //       var bins = {};
    //       recs.forEach(
    //         function(r) {
    //           console.log(monthf(r));
    //           var fkey = firstf(r);     // points
    //           var gkey = groupf(r);     // grade
    //           hit[fkey] = true;
    //           bins[gkey] = (bins[gkey] || 0) + fkey;
    //         }
    //       );
    //       return Object.keys(bins).map(function(k) {
    //         return {
    //           key: k,
    //           value: bins[k]
    //         };
    //       });
    //     }
    //   }
    // }
    //
    // var dubred_group = double_reduce(
    //   dateDim,
    //   function(r) {
    //     return r.grade;
    //   },
    //   function(r) {
    //     return r.points;
    //   }
    //   ,
    //   function(r) {
    //     return r.month;
    //   }
    // );
    // console.log(dubred_group.all());

    //d3.select('#output1').text(JSON.stringify(dubred_group.all(), null, 2));
    //dateDim.filter([new Date("2017-01-01"), new Date("2017-01-31")]);
    //d3.select('#output2').text(JSON.stringify(dubred_group.all(), null, 2));

    // filteredRowChart
    //   .width(800)
    //   .height(200)
    //   .margins({
    //     top: 20,
    //     left: 10,
    //     right: 10,
    //     bottom: 20
    //   })
    //   .dimension(dateDim)
    //   .group(group)
    // //   .valueAccessor(
    // //     function(d) {
    // //       return d.value.totalPoints;
    // //     })
    // //  .ordinalColors(['#90C3D4', '#21A1CC', '#72C1DB', '#05BBF7', '#0785F2'])
    // //  .label(function(d) {
    // //        return 'Total Points for Grade ' + d.key + ': ' + d.value;
    // //      })
    // //   .title(function(d) { return d.value; })
    //   .elasticX(true)
    //   .xAxis()
    //   .ticks(4);

  dc.renderAll();

  // var timeDimension = ndx.dimension(function(d) { return d.formattedDate; });
  // console.log(timeDimension.top(10));
  //
  // var btns = d3.select(".buttons-container").selectAll("button").data(["3", "2", "Last Month", "Last Week", "This Year", "This Month"])
  //
  // btns = btns.enter().append("button").attr("class", "btn btn-sm btn-success")
  //
  // // fill the buttons with the year from the data assigned to them
  // btns.each(function(d) {
  //     this.innerText = d;
  // })
  //
  // btns.on("click", drawBrush);
  //
  // function drawBrush() {
  //   // our year will this.innerText
  //   if (this.innerText === "This Year") {
  //     thisYear();
  //   }
  //   if (this.innerText === "This Month") {
  //     thisMonth();
  //   }
  //   if (this.innerText === "Last Week") {
  //     lastWeek();
  //   }
  //   if (this.innerText === "Last Month") {
  //     lastMonth();
  //   }
  //   if (this.innerText === "2") {
  //     twoMonths();
  //   }
  //   if (this.innerText === "3") {
  //     threeMonths();
  //   }
    //
    // var st = $('div#start').text();
    // var end = $('div#end').text();
    //
    // console.log(st);
    // console.log(end);

    /*
    // define our brush extent to be begin and end of the year
    //brush.extent([new Date(this.innerText + '2015-01-01'), new Date(this.innerText + '2015-12-31')])
    brush.extent([new Date(st), new Date(end)])

    // now draw the brush to match our extent
    // use transition to slow it down so we can see what is happening
    // remove transition so just d3.select(".brush") to just draw
    brush(khanRowChart.select(".brush").transition().delay(1000));

    // now fire the brushstart, brushmove, and brushend events
    // remove transition so just d3.select(".brush") to just draw
    //d3.select(".brush").transition().delay(1000);
    //$(".brush").transition().delay(1000);
    // khanRowChart.brush.event(khanRowChart.select(".brush").transition().delay(1000))

    dataFiltered = data.filter(function(d, i) {
        var mon2 = d.dtg1;
        if ( (mon2 >= st) && (mon2 <= end) ) {
            return d.dtg;
        }
    });
    //brush.event(khanRowChart.select(".brush").transition().delay(1000))
    //dateFiltered = ndx.dimension(function (d) { return d.dtg; });
    */

    // filteredRowChart.filter(null);
    // filteredRowChart.filter(dc.filters.RangedFilter(new Date(st), new Date(end)));

  	// dateDim.filter([new Date(st), new Date(end)]);
	  // d3.select('#output2').text(JSON.stringify(dubred_group.all(), null, 2));

    // console.log('redrawAll with date filter');

    // dc.redrawAll();
    //rtey = brush.extent();
    //dc.renderAll();
  // }

  function fixed_now() {
    var today = new Date();
    var y = today.getFullYear();
    var m = today.getMonth() + 1;
    var d = today.getDate();
    var ymd = y + "-" + m + "-" + d;
    return Date(ymd);
      // return new Date("2015-04-15")
  }

  function thisWeek() {
      var now = moment(fixed_now());
      var mon = now.startOf('week').add('days', 1);
      var startMoment = mon.format("YYYY-MM-DD");
      var endMoment = mon.add('days', 6).format("YYYY-MM-DD");
      $("#start").text(startMoment);
      $("#end").text(endMoment);
  }

  function thisMonth() {
      var firstOfMonth = moment(fixed_now(), 'YYYY-MM-DD').startOf("month");
      var endOfMonth = moment(fixed_now(), 'YYYY-MM-DD').endOf("month");
      var startMoment = firstOfMonth.format("YYYY-MM-DD");
      var endMoment = endOfMonth.format("YYYY-MM-DD");
      $("#start").text(firstOfMonth);
      $("#end").text(endOfMonth);
  }

  function thisYear() {
    var firstOfYear = moment(fixed_now(), 'YYYY-MM-DD').startOf("year");
    var endOfMonth = moment(fixed_now(), 'YYYY-MM-DD').endOf("month");
    var startMoment = firstOfYear.format("YYYY-MM-DD");
    var endMoment = endOfMonth.format("YYYY-MM-DD");
    $("#start").text(startMoment);
    $("#end").text(endMoment);
  }

  function lastWeek() {
      var now = moment(fixed_now());
      var mon = now.startOf('week').subtract('days', 6)
      var startMoment = mon.format("YYYY-MM-DD");
      var endMoment = mon.add('days', 6).format("YYYY-MM-DD");
      $("#start").text(startMoment);
      $("#end").text(endMoment);
  }

  function lastMonth() {
      var firstOfMonth = moment(fixed_now()).startOf("month").subtract('months', 1);
      var endOfMonth = moment(fixed_now()).endOf("month").subtract('months', 1);
      var startMoment = firstOfMonth.format("YYYY-MM-DD");
      var endMoment = endOfMonth.format("YYYY-MM-DD");
      $("div#start").text(startMoment);
      $("div#end").text(endMoment);
  }

  function twoMonths() {
      var firstOfMonth = moment(fixed_now()).startOf("month").subtract('months', 2);
      var endOfMonth = moment(fixed_now()).endOf("month").subtract('months', 2);
      var startMoment = firstOfMonth.format("YYYY-MM-DD");
      var endMoment = endOfMonth.format("YYYY-MM-DD");
      $("#start").text(startMoment);
      $("#end").text(endMoment);
  }

  function threeMonths() {
      var firstOfMonth = moment(fixed_now()).startOf("month").subtract('months', 3);
      var endOfMonth = moment(fixed_now()).endOf("month").subtract('months', 3);
      var startMoment = firstOfMonth.format("YYYY-MM-DD");
      var endMoment = endOfMonth.format("YYYY-MM-DD");
      $("#start").text(startMoment);
      $("#end").text(endMoment);
  }

  // function brushed() {
  //   console.log('brushed')
  //   khanRowChart.x.domain(brush.empty() ? khanRowChart.x.domain() : brush.extent());
  //     //focus.select("khanRowChart.area").attr("d", area);
  //     //focus.select("khanRowChart.x.axis").call(xAxis);
  // }

  dc.renderAll();

}
<commit_msg>updates to khan points dataset<commit_after>queue()
  .defer(d3.json, "/api/scholar_khan_points")
  // .defer(d3.json, "khan_points.json")
  .await(makeGraphs);

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

function makeGraphs(error, data) {

  khanDataTable = dc.dataTable('#khanDataTable');
  khanRowChart = dc.rowChart('#khanRowChart');

  // filteredRowChart = dc.rowChart('#grade-row-chart-filtered');

  var DTSformat = d3.time.format("%Y-%m-%d");

  // set up data
  data.forEach(function(d) {
    d.formattedDate = DTSformat.parse(d.activity_date.substr(0, 10));
    d.month = d3.time.month(d.formattedDate);
    // d.pointsPerDate = undefined || d.points_per_date;
  });

  // console.log(data);

  var ndx = crossfilter(data);

  var emailDimension = ndx.dimension(function(d) { return d.email; });

  var gradeDimension = ndx.dimension(function(d) { return d.grade; });
  // console.log(gradeDimension.top(10));

  //////  update to count unique students
  var gradeGroup = gradeDimension.group().reduce(
    function (p, d) {
      ++p.count;
      p.totalPoints += +d.points_per_date;
      if(d.student_name in p.student_names){
          p.student_names[d.student_name] += 1
      }
      else{
          p.student_names[d.student_name] = 1;
          p.student_count++;
      }
      return p;
    },
    function (p, d) {
      --p.count;
      p.totalPoints -= +d.points_per_date;
      p.student_names[d.student_name]--;
      if(p.student_names[d.student_name] === 0){
        delete p.student_names[d.student_name];
        p.student_count--;
      }
      return p;
    },
    function () {
      return {
        count: 0,
        totalPoints: 0,
        student_names: {},
        student_count: 0
      };
    });

  // console.log(gradeGroup.top(10));

  khanRowChart
    .width(400)
    .height(200)
    .margins({top: 20, left: 10, right: 10, bottom: 20})
    .dimension(gradeDimension)
    .group(gradeGroup)
    .valueAccessor(function(d) { return d.value.totalPoints; })
    .ordering(function(d) { return -d.value.totalPoints })
    .label(function(d) {
      return 'Total Points for Grade ' +
        d.key + ': ' +
        d.value.totalPoints + ' (' +
        d.value.student_count + ' students)';
    })
    .elasticX(true)
    .xAxis()
    .ticks(4);

  khanDataTable
    .width(400)
    .height(200)
    .dimension(emailDimension)
    .size(10)
    .group(function(d) { return ''; })
    .columns([
      // function(d) { return '    '; },
      function(d) { return d.student_name; },
      function(d) { return + d.points_per_date; },
      function(d) { return d.grade; }
    ])
    .sortBy(function(d) { return +d.points_per_date; })
    .order(d3.descending);

    //
    // var dateDim = ndx.dimension(
    //   function(x) {
    //     return x.month;
    //   }
    // );

    //
    // var dateDim = {
    //   grade: ndx.dimension(function(d) { return d.grade }),
    //   month: ndx.dimension(function(d) { return d.month }),
    //   id:  ndx.dimension(function(d) { return JSON.stringify([d.grade, d.month]); })
    // }

    // console.log(dateDim.grade.top(10));
    // console.log(dateDim.month.top(10));
    // console.log(dateDim.id.top(10));

    // var gradeMonthGroup = dateDim.id.group();
    // gradeMonthGroup.all().forEach(function(d) {
    //   d.key = JSON.parse(d.key);
    // });

    // var group = dateDim.id.group();
    //
    // group.all().forEach(
    //   function(d) {
    //     d.key = JSON.parse(d.key);
    //   }
    // );
    //
    // var sum = group.reduceSum(function(d) {return d.points_per_date;}).all();

    // console.log('sum');
    // console.log(sum);

    // var gradeMonthGroup = dateDim.id.group().reduce(
    //   function (p, d) {
    //     ++p.count;
    //     p.totalPoints += +d.points_per_date;
    //     return p;
    //   },
    //   function (p, d) {
    //     --p.count;
    //     p.totalPoints -= +d.points_per_date;
    //     return p;
    //   },
    //   function () {
    //     return {
    //       count: 0,
    //       totalPoints: 0,
    //     };
    //   });
    //
    // console.log('gradeMonthGroup');
    // console.log(gradeMonthGroup.top(10));

    //
    // function double_reduce(dim, groupf, firstf) {
    //   return {
    //     all: function() {
    //       var recs = dim.bottom(Infinity);
    //       var hit = {};
    //       var bins = {};
    //       recs.forEach(
    //         function(r) {
    //           console.log(monthf(r));
    //           var fkey = firstf(r);     // points
    //           var gkey = groupf(r);     // grade
    //           hit[fkey] = true;
    //           bins[gkey] = (bins[gkey] || 0) + fkey;
    //         }
    //       );
    //       return Object.keys(bins).map(function(k) {
    //         return {
    //           key: k,
    //           value: bins[k]
    //         };
    //       });
    //     }
    //   }
    // }
    //
    // var dubred_group = double_reduce(
    //   dateDim,
    //   function(r) {
    //     return r.grade;
    //   },
    //   function(r) {
    //     return r.points;
    //   }
    //   ,
    //   function(r) {
    //     return r.month;
    //   }
    // );
    // console.log(dubred_group.all());

    //d3.select('#output1').text(JSON.stringify(dubred_group.all(), null, 2));
    //dateDim.filter([new Date("2017-01-01"), new Date("2017-01-31")]);
    //d3.select('#output2').text(JSON.stringify(dubred_group.all(), null, 2));

    // filteredRowChart
    //   .width(800)
    //   .height(200)
    //   .margins({
    //     top: 20,
    //     left: 10,
    //     right: 10,
    //     bottom: 20
    //   })
    //   .dimension(dateDim)
    //   .group(group)
    // //   .valueAccessor(
    // //     function(d) {
    // //       return d.value.totalPoints;
    // //     })
    // //  .ordinalColors(['#90C3D4', '#21A1CC', '#72C1DB', '#05BBF7', '#0785F2'])
    // //  .label(function(d) {
    // //        return 'Total Points for Grade ' + d.key + ': ' + d.value;
    // //      })
    // //   .title(function(d) { return d.value; })
    //   .elasticX(true)
    //   .xAxis()
    //   .ticks(4);

  dc.renderAll();

  // var timeDimension = ndx.dimension(function(d) { return d.formattedDate; });
  // console.log(timeDimension.top(10));
  //
  // var btns = d3.select(".buttons-container").selectAll("button").data(["3", "2", "Last Month", "Last Week", "This Year", "This Month"])
  //
  // btns = btns.enter().append("button").attr("class", "btn btn-sm btn-success")
  //
  // // fill the buttons with the year from the data assigned to them
  // btns.each(function(d) {
  //     this.innerText = d;
  // })
  //
  // btns.on("click", drawBrush);
  //
  // function drawBrush() {
  //   // our year will this.innerText
  //   if (this.innerText === "This Year") {
  //     thisYear();
  //   }
  //   if (this.innerText === "This Month") {
  //     thisMonth();
  //   }
  //   if (this.innerText === "Last Week") {
  //     lastWeek();
  //   }
  //   if (this.innerText === "Last Month") {
  //     lastMonth();
  //   }
  //   if (this.innerText === "2") {
  //     twoMonths();
  //   }
  //   if (this.innerText === "3") {
  //     threeMonths();
  //   }
    //
    // var st = $('div#start').text();
    // var end = $('div#end').text();
    //
    // console.log(st);
    // console.log(end);

    /*
    // define our brush extent to be begin and end of the year
    //brush.extent([new Date(this.innerText + '2015-01-01'), new Date(this.innerText + '2015-12-31')])
    brush.extent([new Date(st), new Date(end)])

    // now draw the brush to match our extent
    // use transition to slow it down so we can see what is happening
    // remove transition so just d3.select(".brush") to just draw
    brush(khanRowChart.select(".brush").transition().delay(1000));

    // now fire the brushstart, brushmove, and brushend events
    // remove transition so just d3.select(".brush") to just draw
    //d3.select(".brush").transition().delay(1000);
    //$(".brush").transition().delay(1000);
    // khanRowChart.brush.event(khanRowChart.select(".brush").transition().delay(1000))

    dataFiltered = data.filter(function(d, i) {
        var mon2 = d.dtg1;
        if ( (mon2 >= st) && (mon2 <= end) ) {
            return d.dtg;
        }
    });
    //brush.event(khanRowChart.select(".brush").transition().delay(1000))
    //dateFiltered = ndx.dimension(function (d) { return d.dtg; });
    */

    // filteredRowChart.filter(null);
    // filteredRowChart.filter(dc.filters.RangedFilter(new Date(st), new Date(end)));

  	// dateDim.filter([new Date(st), new Date(end)]);
	  // d3.select('#output2').text(JSON.stringify(dubred_group.all(), null, 2));

    // console.log('redrawAll with date filter');

    // dc.redrawAll();
    //rtey = brush.extent();
    //dc.renderAll();
  // }

  function fixed_now() {
    var today = new Date();
    var y = today.getFullYear();
    var m = today.getMonth() + 1;
    var d = today.getDate();
    var ymd = y + "-" + m + "-" + d;
    return Date(ymd);
      // return new Date("2015-04-15")
  }

  function thisWeek() {
      var now = moment(fixed_now());
      var mon = now.startOf('week').add('days', 1);
      var startMoment = mon.format("YYYY-MM-DD");
      var endMoment = mon.add('days', 6).format("YYYY-MM-DD");
      $("#start").text(startMoment);
      $("#end").text(endMoment);
  }

  function thisMonth() {
      var firstOfMonth = moment(fixed_now(), 'YYYY-MM-DD').startOf("month");
      var endOfMonth = moment(fixed_now(), 'YYYY-MM-DD').endOf("month");
      var startMoment = firstOfMonth.format("YYYY-MM-DD");
      var endMoment = endOfMonth.format("YYYY-MM-DD");
      $("#start").text(firstOfMonth);
      $("#end").text(endOfMonth);
  }

  function thisYear() {
    var firstOfYear = moment(fixed_now(), 'YYYY-MM-DD').startOf("year");
    var endOfMonth = moment(fixed_now(), 'YYYY-MM-DD').endOf("month");
    var startMoment = firstOfYear.format("YYYY-MM-DD");
    var endMoment = endOfMonth.format("YYYY-MM-DD");
    $("#start").text(startMoment);
    $("#end").text(endMoment);
  }

  function lastWeek() {
      var now = moment(fixed_now());
      var mon = now.startOf('week').subtract('days', 6)
      var startMoment = mon.format("YYYY-MM-DD");
      var endMoment = mon.add('days', 6).format("YYYY-MM-DD");
      $("#start").text(startMoment);
      $("#end").text(endMoment);
  }

  function lastMonth() {
      var firstOfMonth = moment(fixed_now()).startOf("month").subtract('months', 1);
      var endOfMonth = moment(fixed_now()).endOf("month").subtract('months', 1);
      var startMoment = firstOfMonth.format("YYYY-MM-DD");
      var endMoment = endOfMonth.format("YYYY-MM-DD");
      $("div#start").text(startMoment);
      $("div#end").text(endMoment);
  }

  function twoMonths() {
      var firstOfMonth = moment(fixed_now()).startOf("month").subtract('months', 2);
      var endOfMonth = moment(fixed_now()).endOf("month").subtract('months', 2);
      var startMoment = firstOfMonth.format("YYYY-MM-DD");
      var endMoment = endOfMonth.format("YYYY-MM-DD");
      $("#start").text(startMoment);
      $("#end").text(endMoment);
  }

  function threeMonths() {
      var firstOfMonth = moment(fixed_now()).startOf("month").subtract('months', 3);
      var endOfMonth = moment(fixed_now()).endOf("month").subtract('months', 3);
      var startMoment = firstOfMonth.format("YYYY-MM-DD");
      var endMoment = endOfMonth.format("YYYY-MM-DD");
      $("#start").text(startMoment);
      $("#end").text(endMoment);
  }

  // function brushed() {
  //   console.log('brushed')
  //   khanRowChart.x.domain(brush.empty() ? khanRowChart.x.domain() : brush.extent());
  //     //focus.select("khanRowChart.area").attr("d", area);
  //     //focus.select("khanRowChart.x.axis").call(xAxis);
  // }

  dc.renderAll();

}
<|endoftext|>


<commit_before>/**!
 *
 * Copyright (c) 2015 Cisco Systems, Inc. See LICENSE file.
 * @private
 */

import {registerPlugin} from '../../spark-core';
import AuthInterceptor from './auth-interceptor';
import Credentials from './credentials';

registerPlugin(`credentials`, Credentials, {
  proxies: [
    `isAuthenticated`,
    `isAuthenticating`
  ],
  interceptors: {
    AuthInterceptor: AuthInterceptor.create
  }
});

export {Credentials as Credentials};
export {default as Authorization} from './authorization';
export {default as grantErrors} from './grant-errors';
export {AuthInterceptor as AuthInterceptor};
<commit_msg>fix(spark-core): add back missing export<commit_after>/**!
 *
 * Copyright (c) 2015 Cisco Systems, Inc. See LICENSE file.
 * @private
 */

import {registerPlugin} from '../../spark-core';
import AuthInterceptor from './auth-interceptor';
import Credentials from './credentials';

registerPlugin(`credentials`, Credentials, {
  proxies: [
    `isAuthenticated`,
    `isAuthenticating`
  ],
  interceptors: {
    AuthInterceptor: AuthInterceptor.create
  }
});

export {Credentials as default};
export {Credentials as Credentials};
export {default as Authorization} from './authorization';
export {default as grantErrors} from './grant-errors';
export {AuthInterceptor as AuthInterceptor};
<|endoftext|>


<commit_before>/*
	jQuery Extended Mag(nify)
	Author: Caleb O'Leary
	Site: http://caleboleary.com
	Current Version: https://github.com/caleboleary/jQuery-Extended-Mag
	MIT License
*/
!function(t){"use strict";t.fn.extend({extm:function(e){function i(e,i){var s,o=i.width(),n=i.height(),a=i.offset();e.zoomElement?s=e.zoomElement:(s=t("

"),"right"===e.position?(s.appendTo(t("body")),s.css("position","absolute"),s.css("top",a.top),s.css("left",a.left+o)):"overlay"===e.position?(s.appendTo(t("body")),s.css("position","absolute"),s.css("top",a.top),s.css("left",a.left)):s.insertAfter(i));var r,l;e.squareOverlay&&(r=t("

"),t("body").append(r),l=t("

"),r.append(l)),e.lazy||s.css("visibility","hidden");var h=t('');e.imageSrc?h.attr("src",e.imageSrc):h.attr("src",i.attr("src")),h.appendTo(s),function(t,e,i,s,o,n,a,r,l){i.load(function(){t.on("mouseenter",function(){a=t.offset(),"right"===l.position?(e.css("top",a.top),e.css("left",a.left+n)):"overlay"===l.position&&(e.css("top",a.top),e.css("left",a.left)),l.squareOverlay&&(s.css("top",a.top),s.css("left",a.left)),e.css("visibility","visible"),l.squareOverlay&&r.css("visibility","visible")}),t.on("mouseleave",function(){e.css("visibility","hidden"),l.squareOverlay&&r.css("visibility","hidden")});var h=i.width(),c=i.height(),p=h/n,v=c/o,d=0-(h-e.width()),f=0-(c-e.height());if(l.squareOverlay){var u=n/h*n,m=o/c*o;r.css("height",m),r.css("width",u)}t.on("mousemove",function(e){a=t.offset();var s=o/2-(e.pageY-a.top)*v;s=Math.max(s,f),s=Math.min(s,0);var h=n/2-(e.pageX-a.left)*p;if(h=Math.max(h,d),h=Math.min(h,0),i.css("top",s),i.css("left",h),l.squareOverlay){var c=e.pageY-a.top-r.height()/2;c=Math.max(c,0),c=Math.min(c,o-r.height());var u=e.pageX-a.left-r.width()/2;u=Math.max(u,0),u=Math.min(u,n-r.width()),r.css("top",c),r.css("left",u)}})})}(i,s,h,r,n,o,a,l,e),i.on("extmdestroy",function(){s.remove(),e.squareOverlay&&r.remove()})}var s={zoomElement:!1,imageSrc:t(this).attr("src"),squareOverlay:!1,position:!1,lazy:!1},o=t.extend({},s,e||{});o.lazy?t(this).width()&&t(this).height()?t(this).one("mouseenter",function(){i(o,t(this))}):t(this).one("load",function(){t(this).one("mouseenter",function(){i(o,t(this))})}):t(this).width()&&t(this).height()?i(o,t(this)):t(this).one("load",function(){i(o,t(this))})},extmDestroy:function(){t(this).trigger("extmdestroy")}})}(jQuery);
<commit_msg>image loaded fix<commit_after>/*
	jQuery Extended Mag(nify)
	Author: Caleb O'Leary
	Site: http://caleboleary.com
	Current Version: https://github.com/caleboleary/jQuery-Extended-Mag
	MIT License
*/
!function(t){"use strict";t.fn.extend({extm:function(e){function i(e,i){var s,o=i.width(),n=i.height(),a=i.offset();e.zoomElement?s=e.zoomElement:(s=t("

"),"right"===e.position?(s.appendTo(t("body")),s.css("position","absolute"),s.css("top",a.top),s.css("left",a.left+o)):"overlay"===e.position?(s.appendTo(t("body")),s.css("position","absolute"),s.css("top",a.top),s.css("left",a.left)):s.insertAfter(i));var r,l;e.squareOverlay&&(r=t("

"),t("body").append(r),l=t("

"),r.append(l)),e.lazy||s.css("visibility","hidden");var h=t('');e.imageSrc?h.attr("src",e.imageSrc):h.attr("src",i.attr("src")),h.appendTo(s),function(t,e,i,s,o,n,a,r,l){i.load(function(){t.on("mouseenter",function(){a=t.offset(),"right"===l.position?(e.css("top",a.top),e.css("left",a.left+n)):"overlay"===l.position&&(e.css("top",a.top),e.css("left",a.left)),l.squareOverlay&&(s.css("top",a.top),s.css("left",a.left)),e.css("visibility","visible"),l.squareOverlay&&r.css("visibility","visible")}),t.on("mouseleave",function(){e.css("visibility","hidden"),l.squareOverlay&&r.css("visibility","hidden")});var h=i.width(),c=i.height(),p=h/n,v=c/o,d=0-(h-e.width()),f=0-(c-e.height());if(l.squareOverlay){var u=n/h*n,m=o/c*o;r.css("height",m),r.css("width",u)}t.on("mousemove",function(e){a=t.offset();var s=o/2-(e.pageY-a.top)*v;s=Math.max(s,f),s=Math.min(s,0);var h=n/2-(e.pageX-a.left)*p;if(h=Math.max(h,d),h=Math.min(h,0),i.css("top",s),i.css("left",h),l.squareOverlay){var c=e.pageY-a.top-r.height()/2;c=Math.max(c,0),c=Math.min(c,o-r.height());var u=e.pageX-a.left-r.width()/2;u=Math.max(u,0),u=Math.min(u,n-r.width()),r.css("top",c),r.css("left",u)}})})}(i,s,h,r,n,o,a,l,e),i.on("extmdestroy",function(){s.remove(),e.squareOverlay&&r.remove()})}var s={zoomElement:!1,imageSrc:t(this).attr("src"),squareOverlay:!1,position:!1,lazy:!1},o=t.extend({},s,e||{});o.lazy?t(this).width()&&t(this).height()?t(this).one("mouseenter",function(){i(o,t(this))}):t(this).one("load",function(){t(this).one("mouseenter",function(){i(o,t(this))})}):t(this).width()>10&&t(this).height()>10?i(o,t(this)):t(this).one("load",function(){i(o,t(this))})},extmDestroy:function(){t(this).trigger("extmdestroy")}})}(jQuery);
<|endoftext|>


<commit_before>/*jshint ignore:start */
'use strict';

var rewire = require('rewire');

describe('l10n', function() {
    var l10n;

    beforeAll(function() {
        l10n = rewire('../index');
    });

    it('should return month name in nominative when formatting without specifying form',
    () => {
        expect(l10n.formatMonth(1)).toEqual('janvāris');
        expect(l10n.formatMonth(7)).toEqual('jūlijs');
    });

    it('should return month name in specified form when asked to nicely', () => {
        expect(l10n.formatMonth(4, 'genitivs')).toEqual('aprīļa');
        expect(l10n.formatMonth(10, 'akuzativs')).toEqual('oktobri');
    });

    it('should return nothing when asked to format nonexisting month or to an undefined form',
    () => {
        expect(l10n.formatMonth(16)).not.toBeDefined();
        expect(l10n.formatMonth(4, 'deklinativs')).not.toBeDefined();
    });

    it('should format dates without a leading zero', () => {
        expect(l10n.formatDate('6-12-01')).toEqual('6.gada 1.decembris');
        expect(l10n.formatDate('2015-12-01')).toEqual('2015.gada 1.decembris');
        expect(l10n.formatDate('2015-12-11')).toEqual('2015.gada 11.decembris');
    })

    it('should format proper ISO8601-compliant dates to specified form', () => {
        expect(l10n.formatDate('2015-12-01', 'dativs')).toEqual('2015.gada 1.decembrim');
        expect(l10n.formatDate('2000-03-16', 'lokativs')).toEqual('2000.gada 16.martā');
    });

    it('should return "unknown date" when asked to format dates not complying to ISO8601, using the specified form',
    () => {
        expect(l10n.formatDate('03/04/2010')).toEqual('nezināms datums');
        expect(l10n.formatDate('2010.14.21', 'genitivs')).toEqual('nezināma datuma');
        expect(l10n.formatDate('garbageDate', 'akuzativs')).toEqual('nezināmu datumu');
    });

    it('should return nominative form dates when form is not specified', () => {
        expect(l10n.formatDate('2010-01-01')).toEqual('2010.gada 1.janvāris');
        expect(l10n.formatDate('2011-04-04')).toEqual('2011.gada 4.aprīlis');
    });

    it('should return "unknown date" in nominative when an undefined form is specified', () => {
        expect(l10n.formatDate('2015-12-01', 'deklinativs')).toEqual('nezināms datums');
    });

    it('should not accept invalid months, returning "unknown date" instead, in specified form', () => {
        expect(l10n.formatDate('2015-15-01')).toEqual('nezināms datums');
        expect(l10n.formatDate('2015-15-01', 'genitivs')).toEqual('nezināma datuma');
    });

});
<commit_msg>l10n: add tests for weekday formatting<commit_after>/*jshint ignore:start */
'use strict';

var rewire = require('rewire');

describe('l10n', function() {
    var l10n;

    beforeAll(function() {
        l10n = rewire('../index');
    });

    it('should return month name in nominative when formatting without specifying form',
    function() {
        expect(l10n.formatMonth(1)).toEqual('janvāris');
        expect(l10n.formatMonth(7)).toEqual('jūlijs');
    });

    it('should return month name in specified form when asked to nicely', function() {
        expect(l10n.formatMonth(4, 'genitivs')).toEqual('aprīļa');
        expect(l10n.formatMonth(10, 'akuzativs')).toEqual('oktobri');
    });

    it('should return nothing when asked to format nonexisting month or to an undefined form',
    function() {
        expect(l10n.formatMonth(16)).not.toBeDefined();
        expect(l10n.formatMonth(4, 'deklinativs')).not.toBeDefined();
    });

    it('should format dates without a leading zero', function() {
        expect(l10n.formatDate('6-12-01')).toEqual('6.gada 1.decembris');
        expect(l10n.formatDate('2015-12-01')).toEqual('2015.gada 1.decembris');
        expect(l10n.formatDate('2015-12-11')).toEqual('2015.gada 11.decembris');
    })

    it('should format proper ISO8601-compliant dates to specified form', function() {
        expect(l10n.formatDate('2015-12-01', 'dativs')).toEqual('2015.gada 1.decembrim');
        expect(l10n.formatDate('2000-03-16', 'lokativs')).toEqual('2000.gada 16.martā');
    });

    it('should return "unknown date" when asked to format dates not complying to ISO8601, using the specified form',
    function() {
        expect(l10n.formatDate('03/04/2010')).toEqual('nezināms datums');
        expect(l10n.formatDate('2010.14.21', 'genitivs')).toEqual('nezināma datuma');
        expect(l10n.formatDate('garbageDate', 'akuzativs')).toEqual('nezināmu datumu');
    });

    it('should return nominative form dates when form is not specified', function() {
        expect(l10n.formatDate('2010-01-01')).toEqual('2010.gada 1.janvāris');
        expect(l10n.formatDate('2011-04-04')).toEqual('2011.gada 4.aprīlis');
    });

    it('should return "unknown date" in nominative when an undefined form is specified', function() {
        expect(l10n.formatDate('2015-12-01', 'deklinativs')).toEqual('nezināms datums');
    });

    it('should not accept invalid months, returning "unknown date" instead, in specified form', function() {
        expect(l10n.formatDate('2015-15-01')).toEqual('nezināms datums');
        expect(l10n.formatDate('2015-15-01', 'genitivs')).toEqual('nezināma datuma');
    });

    it('should return weekday in an adverb form when asked to format it without specifying a form', function() {
        expect(l10n.formatWeekday(1)).toEqual('pirmdien');
        expect(l10n.formatWeekday(3)).toEqual('trešdien');
    });

    it('should return weekday in an adverb form when asked to format it with an invalid form', function() {
        expect(l10n.formatWeekday(1, 'deklinativs')).toEqual('pirmdien');
        expect(l10n.formatWeekday(3, 'deklinativs')).toEqual('trešdien');
    });

    it('should treat the weekday as a noun when changing its case', function() {
        expect(l10n.formatWeekday(1, 'dativs')).toEqual('pirmdienai');
        expect(l10n.formatWeekday(4, 'genitivs')).toEqual('ceturtdienas');
    });
});
<|endoftext|>