<commit_before>/**
 * Narrative data cell.
 *
 * Uses kbaseNarrativeViewers.js to "view" itself.
 *
 * @public
 */

// Viewer methods
// --------------

function KBaseNarrativeViewer(o) {
  var vnames = KBaseNarrativeViewerNames;
  var name = vnames.default;
  var key = o.bare_type;
  if (_.has(vnames, key)) {
    name = vnames[key];
  }
  return KBaseNarrativeViewers[name];
}

// Mapping from KBase types to viewer names.
// XXX: This could be configured from an external source.
var KBaseNarrativeViewerNames = {
  default: "genericViewer",
  "KBaseGenomes.Genome": "genomeViewer",
  "KBaseTrees.Tree": "treeViewer",
}

// Viewer functions.
var KBaseNarrativeViewers = {
  /**
   * Generic viewer.
   */
  genericViewer: function(elt, self) {
    var o = self.obj_info;
    var md_desc = self.shortMarkdownDesc(o);
    if (!_.isEmpty(o.meta)) {
      md_desc += "\n\nMetadata: ";
      this.prev = false;
      _.each(_.pairs(o.meta), function(p) {
        if (this.prev) {
          md_desc += ", ";
        }
        md_desc += p[0] + "=" + p[1];
        this.prev = true;
      });
    }
    self.ip_cell.edit();
    self.ip_cell.set_text(md_desc);
    self.ip_cell.unselect();
    return elt;
  },
  /**
   * Genome viewer.
   */
  genomeViewer: function(elt, self) {
    var o = self.obj_info;
    return elt.kbaseGenomeView({'id': o['id'], 'ws': o['ws_id']});
  },
  /**
   * Species tree viewer.
   */
  treeViewer: function(elt, self) {
    var o = self.obj_info;
    return elt.kbaseTree({'treeID': o['id'],
                          'workspaceID': o['ws_id'],
                           'height': '1000' // need for scroll
                         });
  }
};

// Widget
// -------

(function($, undefined) {
    $.KBWidget({
        name: 'kbaseNarrativeDataCell',
        parent: 'kbaseNarrativeCell',
        version: '0.0.1',
        options: {
            info: null, // object info
            cell: null, // IPython cell
        },
        obj_info: null,
        // for 'method_store' service
        method_client: null,

        /**
         * Initialize
         */
        init: function(options) {
            console.debug("kbaseNarrativeDataCell.init");
            this._super(options);
            this.obj_info = options.info;
            this.obj_info.bare_type = /[^-]*/.exec(this.obj_info.type);
            this.obj_info.simple_date = /[^+]*/.exec(this.obj_info.save_date);
            this.ip_cell = options.cell;
            //this._initMethodStoreClient();
            return this.render(options.info);
        },

        _initMethodStoreClient: function() {
            if (this.method_client === null) {
              this.method_client = new NarrativeMethodStore(this._getMethodStoreURL());
            }
        },

        _getMethodStoreURL: function() { return window.kbconfig.urls.narrative_method_store },

        /**
         * Instantiate viewer widget for a data object.
         *
         * @param object_info (object) Object with info about data item
         * @return Whatever the 'viewer' function returns.
         */
        render: function() {
          var viewer = new KBaseNarrativeViewer(this.obj_info);
          // Run viewer at this point in the narrative
          var $view = viewer(this.$elem, this);
          // Prepend the short description if nec.
          if (viewer != KBaseNarrativeViewers.genericViewer) {
            var html = $(marked.parser(marked.lexer(
              this.shortMarkdownDesc(this.obj_info))));
            html.find("a[href]").not('[href^="#"]').attr("target", "_blank");
            this.$elem.before(html);
          }
          // Make sure that we have unselected the cell
          this.ip_cell.unselect();
          // Return the rendered widget
          return $view;
        },

        shortMarkdownDesc: function(o) {
          var link = "https://"; // force https
          if (window.location.hostname == '0.0.0.0' ||
              window.location.hostname == '127.0.0.1') {
            link += "narrative-dev.kbase.us"; // for testing
          }
          else {
            link += window.location.host;
          }
          link += "/functional-site/#/fbas/" + o.ws_name + "/" + o.name;
          return "[" + o.name + "](" + link + ")"  +
               " (" + o.bare_type + "v" + o.version + ")." +
               " Last saved: " +
               "*" + o.saved_by + "*  " + o.simple_date;
        }

    })
})(jQuery);

<commit_msg>code cleanup and docs<commit_after>/**
 * Narrative data cell.
 *
 * Uses kbaseNarrativeViewers.js to "view" itself.
 *
 * @public
 */

// Factory function for viewer methods
// -----------------------------------

/**
 * Factory function to get viewer object (class)
 * based on object 'bare_type'.
 */
function KBaseNarrativeViewer(o) {
  var vnames = KBaseNarrativeViewerNames;
  var name = vnames.default;
  var key = o.bare_type;
  if (_.has(vnames, key)) {
    name = vnames[key];
  }
  // Return found object
  return KBaseNarrativeViewers[name];
}

// Mapping from KBase types to viewer names.
// XXX: This could be configured from an external source.
var KBaseNarrativeViewerNames = {
  default: "genericViewer",
  "KBaseGenomes.Genome": "genomeViewer",
  "KBaseTrees.Tree": "treeViewer",
}

// Viewer functions.
// Arguments:
//  elt - jQuery element that the viewer should be attached to
//  data_cell - The kbaseNarrativeDataCell widget with the data, etc.
var KBaseNarrativeViewers = {
  /**
   * Generic viewer.
   */
  genericViewer: function(elt, data_cell) {
    var o = data_cell.obj_info;
    var md_desc = data_cell.shortMarkdownDesc(o);
    if (!_.isEmpty(o.meta)) {
      md_desc += "\n\nMetadata: ";
      this.prev = false;
      _.each(_.pairs(o.meta), function(p) {
        if (this.prev) {
          md_desc += ", ";
        }
        md_desc += p[0] + "=" + p[1];
        this.prev = true;
      });
    }
    data_cell.ip_cell.edit();
    data_cell.ip_cell.set_text(md_desc);
    data_cell.ip_cell.unselect();
    return elt;
  },
  /**
   * Genome viewer.
   */
  genomeViewer: function(elt, data_cell) {
    var o = data_cell.obj_info;
    return elt.kbaseGenomeView({'id': o['id'], 'ws': o['ws_id']});
  },
  /**
   * Species tree viewer.
   */
  treeViewer: function(elt, data_cell) {
    var o = data_cell.obj_info;
    return elt.kbaseTree({'treeID': o['id'],
                          'workspaceID': o['ws_id'],
                           'height': '1000' // need for scroll
                         });
  }
};

// NarrativeDataCell widget.
// This is the widget passed into
// the viewer.

(function($, undefined) {
    $.KBWidget({
        name: 'kbaseNarrativeDataCell',
        parent: 'kbaseNarrativeCell',
        version: '0.0.1',
        options: {
            info: null, // object info
            cell: null, // IPython cell
        },
        obj_info: null,
        // for 'method_store' service
        method_client: null,
        // IPython cell
        ip_cell: null,

        /**
         * Initialize
         */
        init: function(options) {
            console.debug("kbaseNarrativeDataCell.init");
            this._super(options);
            this.obj_info = options.info;
            this.obj_info.bare_type = /[^-]*/.exec(this.obj_info.type);
            this.obj_info.simple_date = /[^+]*/.exec(this.obj_info.save_date);
            this.ip_cell = options.cell;
            //this._initMethodStoreClient();
            return this.render(options.info);
        },

        _initMethodStoreClient: function() {
            if (this.method_client === null) {
              this.method_client = new NarrativeMethodStore(this._getMethodStoreURL());
            }
        },

        _getMethodStoreURL: function() { return window.kbconfig.urls.narrative_method_store },

        /**
         * Instantiate viewer widget for a data object.
         *
         * @param object_info (object) Object with info about data item
         * @return Whatever the 'viewer' function returns.
         */
        render: function() {
          var viewer = new KBaseNarrativeViewer(this.obj_info);
          // Run viewer at this point in the narrative
          var $view = viewer(this.$elem, this);
          // Prepend the short description if nec.
          if (viewer != KBaseNarrativeViewers.genericViewer) {
            var html = $(marked.parser(marked.lexer(
              this.shortMarkdownDesc(this.obj_info))));
            html.find("a[href]").not('[href^="#"]').attr("target", "_blank");
            this.$elem.before(html);
          }
          // Make sure that we have unselected the cell
          this.ip_cell.unselect();
          // Return the rendered widget
          return $view;
        },

        shortMarkdownDesc: function(o) {
          var link = "https://"; // force https
          if (window.location.hostname == '0.0.0.0' ||
              window.location.hostname == '127.0.0.1') {
            link += "narrative-dev.kbase.us"; // for testing
          }
          else {
            link += window.location.host;
          }
          link += "/functional-site/#/fbas/" + o.ws_name + "/" + o.name;
          return "[" + o.name + "](" + link + ")"  +
               " (" + o.bare_type + "v" + o.version + ")." +
               " Last saved: " +
               "*" + o.saved_by + "*  " + o.simple_date;
        }

    })
})(jQuery);

<|endoftext|>


<commit_before>//It's called basilisk.js, but this is all for /game

var scrolled_ew = 0;
var scrolled_ns = 0; //up is -
var stones_clickable = 0;
var space_clickable = 0; //up is -

var selectedNode;
var selectedNode_original_cell;
var Caleb; //var selectedNode_replacement_cell = too long. so Caleb.

var cell_swap_set_up = 0;
function setup_cell_swap_if_need_be(){
   if (cell_swap_set_up==1){return;} //only do this once
   cell_swap_set_up==1;

   var my_stone_img = document.createElement("img");
   my_stone_img.setAttribute('src', img_base + '/' + side + "m.gif");

   Caleb = document.createElement('td');
      Caleb.setAttribute('id', 'caleb_the_ripper');
      Caleb.appendChild(my_stone_img);
}
function retire_caleb_clone(){
   if (selectedNode_original_cell){
      var caleb_clone = document.getElementById ('caleb_clone');
      caleb_clone.parentNode.replaceChild (selectedNode_original_cell, caleb_clone);
      selectedNode_original_cell = null;
   }
}

function select(node){
   setup_cell_swap_if_need_be();
   retire_caleb_clone();

   var cell = document.getElementById ('cell ' + node);
   selectedNode_original_cell = cell.cloneNode(true);
   var caleb_clone = Caleb.cloneNode(true);
   caleb_clone.setAttribute('id', 'caleb_clone');
   cell.parentNode.replaceChild (caleb_clone, cell);

   //set form element for submission
   selectedNode = node; //string, such as '4-2'
   var submit_form = document.getElementById ('move_submit_form');
   submit_form.setAttribute ('action', url_base +'/game/' + gameid + '/move/'+ selectedNode);
   document.getElementById ('mv_subm_but').style.display='';
   document.getElementById ('mv_subm_but').value= 'Submit move';
}

$(document).ready(function() {
   if (!gameid) {return;}
   //TODO: make these work.
   //document.getElementById ('resign_button').onClick = "select_resign();return false;";
   //document.getElementById ('pass_button').onClick = "select_pass();return false;";
});
function select_resign(){ //prepares same submit button as submit()
   retire_caleb_clone();
   var submit_form = document.getElementById ('move_submit_form');
   submit_form.setAttribute ('action', url_base +'/game/' + gameid + '/resign');
   document.getElementById ('mv_subm_but').style.display= '';
   document.getElementById ('mv_subm_but').value= 'Submit resignation';
}
function select_pass(){ //prepares same submit button as submit()
   retire_caleb_clone();
   var submit_form = document.getElementById ('move_submit_form');
   submit_form.setAttribute ('action', url_base +'/game/' + gameid + '/pass');
   document.getElementById ('mv_subm_but').style.display= '';
   document.getElementById ('mv_subm_but').value= 'Submit pass';
}

var groups_loaded = false;
var groups; //array of arrays of nodestrings
var group_side; //object: 1stnode=>char
var group_selected; //object: 1stnode=>bool
var group_of_node; //object: nodestring=>1stnode

function select_group(node){
   if (!groups_loaded) return null;
   var group = group_of_node[node];
   if (group==null)
   group_selected[group] = group_selected[group] ? 0 : 1; //flip selected

   //replace images
   var img = img_base + '/' + group_side[group] +  group_selected[group] ? 'd.gif' : '.gif';
   for (n in groups[group]){
      var img = document.getElementById('img ' + n);
      img.setAttribute('src', img);
   }
   //adjust action for submit form:
   var action = "";
   for (g in groups){
      if (!groups_selected[g]) continue;
      if (!action=='') action += '_'; //separator
      action += g[0];
   }
   var submit_form = document.getElementById ('move_submit_form');
   submit_form.setAttribute ('action', url_base +'/game/' + gameid + '/think/' + action);
   document.getElementById ('mv_subm_but').style.display= '';
   document.getElementById ('mv_subm_but').value= 'Submit selection';
}

function scroll (direction){
   var board = document.getElementById('board');
   if (direction=='up'){
      scrolled_ns --;
      scrolled_ns += (w*2);
      scrolled_ns %= (w*2);
      if (twist_ns) render_board();
      else {
         var row = board.rows[h];
         row.parentNode.insertBefore (row, board.rows[1]);
      }
   }
   else if (direction=='down'){
      scrolled_ns ++;
      scrolled_ns %= (w*2);
      if (twist_ns) render_board();
      else {
         var row = board.rows[1];
         row.parentNode.insertBefore (row, board.rows[h+1]);
      }
   }
   else {
      if (direction=='left'){
         scrolled_ew += w-1;
         scrolled_ew %= w;
      }
      else{ //right
         scrolled_ew ++;
         scrolled_ew %= w;
      }
      for(var i = 0; i < h+2; i++){ //shift each row l or r
         var row = board.rows[i];
         if (direction=='left'){
            var cell = row.cells[w];
            cell.parentNode.insertBefore (cell, row.cells[1]);
         }
         else{ //right
            var cell = row.cells[1];
            cell.parentNode.insertBefore(cell, row.cells[w+1]);
         }
      }
   }
}

//delay until
//var tomato=setTimeout ('render_board()', 50);
//render_board();

//replacement board renderer. redraw after every scroll,
//using h,w,wraps_(..),twist_(..),scrolled_(..)
var foolog='';
function render_board(){
   if (typeof (w) == "undefined") return;
   var board_table = document.getElementById ('board');
   if (!board_table) return;
   //clearTimeout(tomato);

   var old_tbody = document.getElementById ('board_tbody');
   if (old_tbody)  board_table.removeChild (old_tbody);

   var new_tbody = document.createElement ('tbody');
   new_tbody.setAttribute ('id', 'board_tbody');

   new_tbody.appendChild (board_letter_row('forwards'));
   var i=0;
   foolog=''
   while (i<h){
      var r = (i + scrolled_ns);
      r %= (h*2);
      var row;
      if ((r >= h) && twist_ns)
         row = board_row (r, 'reverse');
      else
         row = board_row (r, 'forward');
      new_tbody.appendChild (row);
      i++
   }
   new_tbody.appendChild (board_letter_row (twist_ns ?'reverse' : 'forward'));
   board_table.appendChild(new_tbody);
}

function board_row (r, direction){
   r %= h;
   var row = document.createElement ('tr');
   var num = h - r;
   row.appendChild (board_cell ('c'+num+'.gif',null, false));

   var i=0;
   foolog += "\n";
   while (i<w) {
      var c = i + scrolled_ew;
      c %= w;
      if (direction=='reverse')
         c = w-c-1;
      var stone = board_position[r][c];
      foolog += r+'-'+c+',';
      var img;

      clickable = stones_clickable;
      if (stone == 0){
         img = 'e.gif';
         clickable = space_clickable;
      }
      else
         img = stone + '.gif';
      var node = r +'-'+ c;
      row.appendChild (board_cell (img,node, clickable));
      i ++;
   }
   row.appendChild (board_cell ('c'+num+'.gif',null, false));
   return row;
}

//skip i
var letters = ['a','b','c','d','e','f','g','h','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

function board_letter_row (direction){
   var row = document.createElement ('tr');

   var blank_cell = board_cell ('blank.gif',null, false);
   blank_cell.firstChild.setAttribute ('height', 25);
   blank_cell.firstChild.setAttribute ('width', 31);
   row.appendChild (blank_cell);

   var i=0;
   while (i<w) {
      var col = i + scrolled_ew;
      col %= w;
      if (direction=='reverse')
         col = w-col-1;
      row.appendChild (board_cell ('c'+letters[col]+'.gif',null, false));
      i ++;
   }

   row.appendChild (blank_cell.cloneNode(true));
   return row;
}
function board_cell (img_src, node, clickable){
   var cell  = document.createElement ('td');
   var img = document.createElement ('img');
   img.setAttribute ('src', img_base + "/" + img_src);
   cell.appendChild(img);
   if (node){
      cell.setAttribute('id', 'cell '+node);
      img.setAttribute('img', 'img '+node);
   }
   if (clickable)
      cell.setAttribute('onClick', "select('" + node + "')");
   return cell;
}

// populate comments
function render_comment_table(data){
   var c_table = document.getElementById("comments_table");
   var comment_tbody = document.createElement("tbody");
   if (data.length == 0) {
      comment_tbody.innerHTML = "
 No comments.
";
   }
   else{
      var head_row = document.createElement("tr");
      var cell = document.createElement("td");
      //head_row.innerHTML = "#	comment	";
      cell.innerHTML = '#';
      head_row.appendChild(cell);cell = document.createElement("td");
      cell.innerHTML = 'comment';
      head_row.appendChild(cell);
      head_row.setAttribute('class', 'headrow');
      comment_tbody.appendChild (head_row);
      for (i in data){
         var c_row = document.createElement("tr");
         cell = document.createElement("td");
         cell.innerHTML = data[i].movenum;
         c_row.appendChild(cell);
         cell = document.createElement("td");
         cell.innerHTML = ""+ data[i].commentator +': ' + data[i].comment;
         c_row.appendChild(cell);
         comment_tbody.appendChild (c_row);
      }
   }
   c_table.replaceChild (comment_tbody, c_table.tBodies[0]);
   if (logged_in){
      //clear comment textfield, msg on successful comment
      var comment_field = document.getElementById("Leocorno");
      comment_field.value= "";
      var comment_badness = document.getElementById("cBadness");
      comment_badness.innerHTML = "";
   }
}

//appends moves to empty <select>, and highlights latest move.
function render_moves_list (moves){
   var moves_select = document.getElementById('moves_select');
   for (i in moves){
      //var move    = moves[i].move;
      var move    = moves[i].pretty_node;
      var side    = moves[i].side;
      var movenum = moves[i].movenum;
      var option = new Option (movenum +": "+ side +', '+ move, movenum);
      moves_select.add (option, null);
   }
}

function highlight_node (move){
   var node_pattern = /^\{([^{}]+)\}$/;
   var match_node = node_pattern.exec(move.move);
   if (!match_node) return; //something like 'pass' or 'resign', i guess

   var img = document.getElementById ('img ' + match_node[1]);
   if (!img) return; //something wrong
   var special_src = img_base +'/'+ move.side + 'm.gif';
   img.setAttribute('src', special_src);
}

$(document).ready(function() {
   if (!gameid) {return}//something wrong

   stones_clickable = 0;
   space_clickable = board_clickable;
   render_board();

   //dl & display comments
   $.getJSON (
      url_base +"/comments/"+ gameid,
      function (data) {render_comment_table(data[1])}
      //data is ['success', game_comments]
   );

   //dl & display move list
   $.getJSON ( url_base +"/game/"+ gameid +"/allmoves",
      function (data) {
         if (data[0] == 'success'){
            var moves = data[1];
            if (moves.length){
               render_moves_list (moves);
               highlight_node (moves[moves.length-1]);
               document.getElementById('moves_pecan').style.display= '';
            }
            else{
               document.getElementById('moves_pecan').style.display= 'none';
            }
         }
         else
            alert (data[0]);
      }
      //data is ['success', game_moves]
   );

   //set up comment submission form
   //by binding 'new_comment' form and provide a simple callback function
   $('#new_comment').ajaxForm(function(json, success, object) {
      var msg_plus_data = eval ('('+json+')');
      var msg = msg_plus_data [0];
      if (msg == 'success'){
         var comments_data = msg_plus_data[1];
         render_comment_table (comments_data);
         return;
      }
      //failure
      var comment_badness = document.getElementById("cBadness");
      comment_badness.innerHTML = msg;
   });
});

<commit_msg>latest move highlight fix<commit_after>//It's called basilisk.js, but this is all for /game

var scrolled_ew = 0;
var scrolled_ns = 0; //up is -
var stones_clickable = 0;
var space_clickable = 0; //up is -

var selectedNode;
var selectedNode_original_cell;
var Caleb; //var selectedNode_replacement_cell = too long. so Caleb.

var cell_swap_set_up = 0;
function setup_cell_swap_if_need_be(){
   if (cell_swap_set_up==1){return;} //only do this once
   cell_swap_set_up==1;

   var my_stone_img = document.createElement("img");
   my_stone_img.setAttribute('src', img_base + '/' + side + "m.gif");

   Caleb = document.createElement('td');
      Caleb.setAttribute('id', 'caleb_the_ripper');
      Caleb.appendChild(my_stone_img);
}
function retire_caleb_clone(){
   if (selectedNode_original_cell){
      var caleb_clone = document.getElementById ('caleb_clone');
      caleb_clone.parentNode.replaceChild (selectedNode_original_cell, caleb_clone);
      selectedNode_original_cell = null;
   }
}

function select(node){
   setup_cell_swap_if_need_be();
   retire_caleb_clone();

   var cell = document.getElementById ('cell ' + node);
   selectedNode_original_cell = cell.cloneNode(true);
   var caleb_clone = Caleb.cloneNode(true);
   caleb_clone.setAttribute('id', 'caleb_clone');
   cell.parentNode.replaceChild (caleb_clone, cell);

   //set form element for submission
   selectedNode = node; //string, such as '4-2'
   var submit_form = document.getElementById ('move_submit_form');
   submit_form.setAttribute ('action', url_base +'/game/' + gameid + '/move/'+ selectedNode);
   document.getElementById ('mv_subm_but').style.display='';
   document.getElementById ('mv_subm_but').value= 'Submit move';
}

$(document).ready(function() {
   if (!gameid) {return;}
   //TODO: make these work.
   //document.getElementById ('resign_button').onClick = "select_resign();return false;";
   //document.getElementById ('pass_button').onClick = "select_pass();return false;";
});
function select_resign(){ //prepares same submit button as submit()
   retire_caleb_clone();
   var submit_form = document.getElementById ('move_submit_form');
   submit_form.setAttribute ('action', url_base +'/game/' + gameid + '/resign');
   document.getElementById ('mv_subm_but').style.display= '';
   document.getElementById ('mv_subm_but').value= 'Submit resignation';
}
function select_pass(){ //prepares same submit button as submit()
   retire_caleb_clone();
   var submit_form = document.getElementById ('move_submit_form');
   submit_form.setAttribute ('action', url_base +'/game/' + gameid + '/pass');
   document.getElementById ('mv_subm_but').style.display= '';
   document.getElementById ('mv_subm_but').value= 'Submit pass';
}

var groups_loaded = false;
var groups; //array of arrays of nodestrings
var group_side; //object: 1stnode=>char
var group_selected; //object: 1stnode=>bool
var group_of_node; //object: nodestring=>1stnode

function select_group(node){
   if (!groups_loaded) return null;
   var group = group_of_node[node];
   if (group==null)
   group_selected[group] = group_selected[group] ? 0 : 1; //flip selected

   //replace images
   var img = img_base + '/' + group_side[group] +  group_selected[group] ? 'd.gif' : '.gif';
   for (n in groups[group]){
      var img = document.getElementById('img ' + n);
      img.setAttribute('src', img);
   }
   //adjust action for submit form:
   var action = "";
   for (g in groups){
      if (!groups_selected[g]) continue;
      if (!action=='') action += '_'; //separator
      action += g[0];
   }
   var submit_form = document.getElementById ('move_submit_form');
   submit_form.setAttribute ('action', url_base +'/game/' + gameid + '/think/' + action);
   document.getElementById ('mv_subm_but').style.display= '';
   document.getElementById ('mv_subm_but').value= 'Submit selection';
}

function scroll (direction){
   var board = document.getElementById('board');
   if (direction=='up'){
      scrolled_ns --;
      scrolled_ns += (w*2);
      scrolled_ns %= (w*2);
      if (twist_ns) render_board();
      else {
         var row = board.rows[h];
         row.parentNode.insertBefore (row, board.rows[1]);
      }
   }
   else if (direction=='down'){
      scrolled_ns ++;
      scrolled_ns %= (w*2);
      if (twist_ns) render_board();
      else {
         var row = board.rows[1];
         row.parentNode.insertBefore (row, board.rows[h+1]);
      }
   }
   else {
      if (direction=='left'){
         scrolled_ew += w-1;
         scrolled_ew %= w;
      }
      else{ //right
         scrolled_ew ++;
         scrolled_ew %= w;
      }
      for(var i = 0; i < h+2; i++){ //shift each row l or r
         var row = board.rows[i];
         if (direction=='left'){
            var cell = row.cells[w];
            cell.parentNode.insertBefore (cell, row.cells[1]);
         }
         else{ //right
            var cell = row.cells[1];
            cell.parentNode.insertBefore(cell, row.cells[w+1]);
         }
      }
   }
}

//delay until
//var tomato=setTimeout ('render_board()', 50);
//render_board();

//replacement board renderer. redraw after every scroll,
//using h,w,wraps_(..),twist_(..),scrolled_(..)
function render_board(){
   if (typeof (w) == "undefined") return;
   var board_table = document.getElementById ('board');
   if (!board_table) return;
   //clearTimeout(tomato);

   var old_tbody = document.getElementById ('board_tbody');
   if (old_tbody)  board_table.removeChild (old_tbody);

   var new_tbody = document.createElement ('tbody');
   new_tbody.setAttribute ('id', 'board_tbody');

   new_tbody.appendChild (board_letter_row('forwards'));
   var i=0;
   while (i<h){
      var r = (i + scrolled_ns);
      r %= (h*2);
      var row;
      if ((r >= h) && twist_ns)
         row = board_row (r, 'reverse');
      else
         row = board_row (r, 'forward');
      new_tbody.appendChild (row);
      i++
   }
   new_tbody.appendChild (board_letter_row (twist_ns ?'reverse' : 'forward'));
   board_table.appendChild(new_tbody);
}

function board_row (r, direction){
   r %= h;
   var row = document.createElement ('tr');
   var num = h - r;
   row.appendChild (board_cell ('c'+num+'.gif',null, false));

   var i=0;
   while (i<w) {
      var c = i + scrolled_ew;
      c %= w;
      if (direction=='reverse')
         c = w-c-1;
      var stone = board_position[r][c];
      var img;

      clickable = stones_clickable;
      if (stone == 0){
         img = 'e.gif';
         clickable = space_clickable;
      }
      else
         img = stone + '.gif';
      var node = r +'-'+ c;
      row.appendChild (board_cell (img,node, clickable));
      i ++;
   }
   row.appendChild (board_cell ('c'+num+'.gif',null, false));
   return row;
}

//skip i
var letters = ['a','b','c','d','e','f','g','h','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

function board_letter_row (direction){
   var row = document.createElement ('tr');

   var blank_cell = board_cell ('blank.gif',null, false);
   blank_cell.firstChild.setAttribute ('height', 25);
   blank_cell.firstChild.setAttribute ('width', 31);
   row.appendChild (blank_cell);

   var i=0;
   while (i<w) {
      var col = i + scrolled_ew;
      col %= w;
      if (direction=='reverse')
         col = w-col-1;
      row.appendChild (board_cell ('c'+letters[col]+'.gif',null, false));
      i ++;
   }

   row.appendChild (blank_cell.cloneNode(true));
   return row;
}
function board_cell (img_src, node, clickable){
   var cell  = document.createElement ('td');
   var img = document.createElement ('img');
   img.setAttribute ('src', img_base + "/" + img_src);
   cell.appendChild(img);
   if (node){
      cell.setAttribute('id', 'cell '+node);
      img.setAttribute('id', 'img '+node);
   }
   if (clickable)
      cell.setAttribute('onClick', "select('" + node + "')");
   return cell;
}

// populate comments
function render_comment_table(data){
   var c_table = document.getElementById("comments_table");
   var comment_tbody = document.createElement("tbody");
   if (data.length == 0) {
      comment_tbody.innerHTML = "
 No comments.
";
   }
   else{
      var head_row = document.createElement("tr");
      var cell = document.createElement("td");
      //head_row.innerHTML = "#	comment	";
      cell.innerHTML = '#';
      head_row.appendChild(cell);cell = document.createElement("td");
      cell.innerHTML = 'comment';
      head_row.appendChild(cell);
      head_row.setAttribute('class', 'headrow');
      comment_tbody.appendChild (head_row);
      for (i in data){
         var c_row = document.createElement("tr");
         cell = document.createElement("td");
         cell.innerHTML = data[i].movenum;
         c_row.appendChild(cell);
         cell = document.createElement("td");
         cell.innerHTML = ""+ data[i].commentator +': ' + data[i].comment;
         c_row.appendChild(cell);
         comment_tbody.appendChild (c_row);
      }
   }
   c_table.replaceChild (comment_tbody, c_table.tBodies[0]);
   if (logged_in){
      //clear comment textfield, msg on successful comment
      var comment_field = document.getElementById("Leocorno");
      comment_field.value= "";
      var comment_badness = document.getElementById("cBadness");
      comment_badness.innerHTML = "";
   }
}

//appends moves to empty <select>, and highlights latest move.
function render_moves_list (moves){
   var moves_select = document.getElementById('moves_select');
   for (i in moves){
      //var move    = moves[i].move;
      var move    = moves[i].pretty_node;
      var side    = moves[i].side;
      var movenum = moves[i].movenum;
      var option = new Option (movenum +": "+ side +', '+ move, movenum);
      moves_select.add (option, null);
   }
}

function highlight_node (move){
   var node_pattern = /^\{([^{}]+)\}$/;
   var match_node = node_pattern.exec(move.move);
   if (!match_node) return; //something like 'pass' or 'resign', i guess

   var img = document.getElementById ('img ' + match_node[1]);
   if (!img) return; //something wrong
   var special_src = img_base +'/'+ move.side + 'm.gif';
   img.setAttribute('src', special_src);
}

$(document).ready(function() {
   if (!gameid) {return}//something wrong

   stones_clickable = 0;
   space_clickable = board_clickable;
   render_board();

   //dl & display comments
   $.getJSON (
      url_base +"/comments/"+ gameid,
      function (data) {render_comment_table(data[1])}
      //data is ['success', game_comments]
   );

   //dl & display move list
   $.getJSON ( url_base +"/game/"+ gameid +"/allmoves",
      function (data) {
         if (data[0] == 'success'){
            var moves = data[1];
            if (moves.length){
               render_moves_list (moves);
               highlight_node (moves[moves.length-1]);
               document.getElementById('moves_pecan').style.display= '';
            }
            else{
               document.getElementById('moves_pecan').style.display= 'none';
            }
         }
         else
            alert (data[0]);
      }
      //data is ['success', game_moves]
   );

   //set up comment submission form
   //by binding 'new_comment' form and provide a simple callback function
   $('#new_comment').ajaxForm(function(json, success, object) {
      var msg_plus_data = eval ('('+json+')');
      var msg = msg_plus_data [0];
      if (msg == 'success'){
         var comments_data = msg_plus_data[1];
         render_comment_table (comments_data);
         return;
      }
      //failure
      var comment_badness = document.getElementById("cBadness");
      comment_badness.innerHTML = msg;
   });
});

<|endoftext|>


<commit_before>var _demo = "\n" +
"\nwindow.demo = function(message, callback) {" +
"\n  if (typeof callback !== 'function')" +
"\n    throw new Error('bad callback: ' + callback);" +
"\n  info(message + ' (waiting 1s)');" +
"\n  setTimeout(function() {" +
"\n    info(message + ' (done!)');" +
"\n    try { callback(null, message.length); }" +
"\n    catch (err) { callback(err); }" +
"\n  }, 1000);" +
"\n}" +
"\n";

var _samples = {
	introSample: "" +
	"// Demonstrates how 'streamline.js' transforms synchronous-looking code" +
	"\n// into asynchronous code with callbacks." +
	"\n//" +
	"\n// Try one of the samples above, or write your own code below." +
	"\n// Syntax is simple: just use '_' anywhere a callback is expected" +
	"\n//" +
	"\n// The samples compute factorial(4) by different methods." +
	"\n//" +
	"\n// Look at the transformed code and run it with the 'execute' button." +
	"\n//" +
	"\n// The transformation generates some one-liner auxiliary functions." +
	"\n// Select the 'show complete code' option to see the whole code." +
	"\n//" +
	"\n// The 'beautify' button can help you tidy your code." +
	_demo +
	"\ndemo('Straight to the answer: fact(4) = 24', _);" +
	"\n" +
	"\n// A few pointers to understand the generated code:" +
	"\n//" +
	"\n// * the '_' parameter is the callback. This is where execution will" +
	"\n//   continue on a return or throw statement." +
	"\n// * the '__' variable is a 'next' callback. This is where execution will" +
	"\n//   resume at the end of the construct if it didn't encounter a return " +
	"\n//   or throw." +
	"\n// * the '__cb' function is just a little callback wrapper that deals with " +
	"\n//   error handling and other small matters in a generic way." +
	"\n// * the '__trap' function handles errors if the callback is missing." +
	"\n",

	sequenceSample: "" +
	"// Multiply one step at a time:" +
	"\n" +
	"\nvar fact = demo('1', _);" +
	"\nfact *= demo('12', _);" +
	"\nfact *= demo('123', _);" +
	"\nfact *= demo('1234', _);" +
	"\ndemo('fact(4) = ' + fact, _);" +
	"\n",

	expressionsSample: "" +
	"// Multiply all at once:" +
	"\n" +
	"\nvar fact = demo('1', _) * demo('12', _) * demo('123', _) * demo('1234', _);" +
	"\ndemo('fact(4) = ' + fact, _)" +
	"\n",

	functionsSample: "" +
	"// Go through intermediate functions: " +
	"\n" +
	"\nfunction f(n1, n2, _) {" +
	"\n  return demo(n1, _) * demo(n2, _);" +
	"\n}" +
	"\n" +
	"\nfunction g(_) {" +
	"\n  return f('1', '12', _) * f('123', '1234', _);" +
	"\n}" +
	"\n" +
	"\ndemo('fact(4) = ' + g(_), _);" +
	"\n",

	ifElseSample: "" +
	"// Natural recursive version with if/else test." +
	"\n" +
	"\nfunction fact(n, _) {" +
	"\n  if (n == 1) { demo('return: 1', _); return 1; }" +
	"\n  else { demo('recurse: ' + n, _); return n * fact(n - 1, _); }" +
	"\n}" +
	"\n" +
	"\ndemo('fact(4) = ' + fact(4, _), _);" +
	"\n",

	loopSample: "" +
	"// Natural iterative version" +
	"\n" +
	"\nfunction fact(n, _) {" +
	"\n  var result = 1;" +
	"\n  for (var str = '-'; str.length <= n; str += '-') {" +
	"\n    result *= demo(str, _);" +
	"\n  }" +
	"\n  return result;" +
	"\n}" +
	"\n" +
	"\ndemo('fact(4) = ' + fact(4, _), _);" +
	"\n",

	tryCatchSample: "" +
	"// Recursive variant with throw/catch." +
	"\n" +
	"\nfunction fact(n, _) {" +
	"\n  try {" +
	"\n    demo('try: n = ' + n, _);" +
	"\n    if (n == 0) throw new Error('zero');" +
	"\n    return n * fact(n - 1, _);" +
	"\n  }" +
	"\n  catch (ex) { demo('caught ' + ex.message, _); return 1; }" +
	"\n  finally { demo('finally: n = ' + n, _); }" +
	"\n}" +
	"\n" +
	"\ndemo('fact(4) = ' + fact(4, _), _);" +
	"\n",

	lazySample: "" +
	"// Variant with lazy eval operators." +
	"\n// Note that fact(3, _) is evaluated but fact(5, _) is not" +
	"\n" +
	"\nfunction fact(n, _) {" +
	"\n  demo('n=' + n, _);" +
	"\n  return n == 1 ? demo('!', _) : n * fact(n - 1, _);" +
	"\n}" +
	"\n" +
	"\nvar fact4 = (fact(3, _) - 6) || fact(4, _) || fact(5, _);" +
	"\n" +
	"\ndemo('fact(4) = ' + fact4, _);" +
	"\n",

	futuresSample: "" +
	"// Variant with futures." +
	"\n// Much faster because all futures wait together" +
	"\n" +
	"\n// Intermediate function to return future when called" +
	"\n// without _ (demo does not return future)" +
	"\nfunction demo2(str, _) { return demo(str, _); }" +
	"\n" +
	"\nvar v1 = demo2('1');" +
	"\nvar v2 = demo2('12');" +
	"\nvar v3 = demo2('123');" +
	"\nvar v4 = demo2('1234');" +
	"\n" +
	"\ndemo2('fact(4) = ' +v1(_) * v2(_) * v3(_) * v4(_) , _);" +
	"\n",
}

var _complete = false;

function error(message) {
	$('#result').removeClass('info').addClass('error').text(message);
}

function info(message) {
	$('#result').removeClass('error').addClass('success').text(message);
}

window.__context = {
	errorHandler: function(err) {
		error(err.message || err.toString());
	}
}

eval(_demo); // define demo if user does not execute intro

function _transform() {
	var codeIn = $('#codeIn').val();
	try {
		var codeOut = Streamline.transform(codeIn, {
			noHelpers: !_complete,
			lines: _complete ? "mark" : "ignore"
		});
		$('#codeOut').val(codeOut);
		info("ready")
	} catch (ex) {
		console.error(ex);
		error(ex.message)
	}
}

function _execute() {
	var codeIn = $('#codeIn').val();
	try {
		var codeOut = Streamline.transform(codeIn, {
			lines: "preserve"
		});
		eval(codeOut);
	} catch (ex) {
		error(ex.message);
	}
}

function _beautify(str) {
	try {
		var str = Narcissus.decompiler.pp(Narcissus.parser.parse(str));
		str = str.replace(/}\s*;/g, "}")
		$('#codeIn').val(str);
		return true;
	} catch (ex) {
		error(ex.message);
		return false;
	}
}

$( function() {
	$('#codeIn').keyup(_transform);
	$('.sample').click( function() {
		$('#codeIn').val(_samples[this.id]);
		_transform();
	});
	$('#beautify').click( function() {
		_beautify($('#codeIn').val());
	})
	$('#complete').change( function() {
		_complete = !_complete;
		_transform();
	})
	$('#execute').click( function() {
		_execute();
	})
	$('#codeIn').val(_samples["introSample"]);
	_transform();
})
<commit_msg>tiny cleanup in demo sample<commit_after>var _demo = "\n" +
"\nwindow.demo = function(message, callback) {" +
"\n  if (typeof callback !== 'function')" +
"\n    throw new Error('bad callback: ' + callback);" +
"\n  info(message + ' (waiting 1s)');" +
"\n  setTimeout(function() {" +
"\n    info(message + ' (done!)');" +
"\n    try { callback(null, message.length); }" +
"\n    catch (err) { callback(err); }" +
"\n  }, 1000);" +
"\n}" +
"\n";

var _samples = {
	introSample: "" +
	"// Demonstrates how 'streamline.js' transforms synchronous-looking code" +
	"\n// into asynchronous code with callbacks." +
	"\n//" +
	"\n// Try one of the samples above, or write your own code below." +
	"\n// Syntax is simple: just use '_' anywhere a callback is expected" +
	"\n//" +
	"\n// The samples compute factorial(4) by different methods." +
	"\n//" +
	"\n// Look at the transformed code and run it with the 'execute' button." +
	"\n//" +
	"\n// The transformation generates some one-liner auxiliary functions." +
	"\n// Select the 'show complete code' option to see the whole code." +
	"\n//" +
	"\n// The 'beautify' button can help you tidy your code." +
	_demo +
	"\ndemo('Straight to the answer: fact(4) = 24', _);" +
	"\n" +
	"\n// A few pointers to understand the generated code:" +
	"\n//" +
	"\n// * the '_' parameter is the callback. This is where execution will" +
	"\n//   continue on a return or throw statement." +
	"\n// * the '__' variable is a 'next' callback. This is where execution will" +
	"\n//   resume at the end of the construct if it didn't encounter a return " +
	"\n//   or throw." +
	"\n// * the '__cb' function is just a little callback wrapper that deals with " +
	"\n//   error handling and other small matters in a generic way." +
	"\n// * the '__trap' function handles errors if the callback is missing." +
	"\n",

	sequenceSample: "" +
	"// Multiply one step at a time:" +
	"\n" +
	"\nvar fact = demo('1', _);" +
	"\nfact *= demo('12', _);" +
	"\nfact *= demo('123', _);" +
	"\nfact *= demo('1234', _);" +
	"\ndemo('fact(4) = ' + fact, _);" +
	"\n",

	expressionsSample: "" +
	"// Multiply all at once:" +
	"\n" +
	"\nvar fact = demo('1', _) * demo('12', _) * demo('123', _) * demo('1234', _);" +
	"\ndemo('fact(4) = ' + fact, _)" +
	"\n",

	functionsSample: "" +
	"// Go through intermediate functions: " +
	"\n" +
	"\nfunction f(n1, n2, _) {" +
	"\n  return demo(n1, _) * demo(n2, _);" +
	"\n}" +
	"\n" +
	"\nfunction g(_) {" +
	"\n  return f('1', '12', _) * f('123', '1234', _);" +
	"\n}" +
	"\n" +
	"\ndemo('fact(4) = ' + g(_), _);" +
	"\n",

	ifElseSample: "" +
	"// Natural recursive version with if/else test." +
	"\n" +
	"\nfunction fact(n, _) {" +
	"\n  if (n == 1) { demo('return: 1', _); return 1; }" +
	"\n  else { demo('recurse: ' + n, _); return n * fact(n - 1, _); }" +
	"\n}" +
	"\n" +
	"\ndemo('fact(4) = ' + fact(4, _), _);" +
	"\n",

	loopSample: "" +
	"// Natural iterative version" +
	"\n" +
	"\nfunction fact(n, _) {" +
	"\n  var result = 1;" +
	"\n  for (var str = '-'; str.length <= n; str += '-') {" +
	"\n    result *= demo(str, _);" +
	"\n  }" +
	"\n  return result;" +
	"\n}" +
	"\n" +
	"\ndemo('fact(4) = ' + fact(4, _), _);" +
	"\n",

	tryCatchSample: "" +
	"// Recursive variant with throw/catch." +
	"\n" +
	"\nfunction fact(n, _) {" +
	"\n  try {" +
	"\n    demo('try: n = ' + n, _);" +
	"\n    if (n == 0) throw new Error('zero');" +
	"\n    return n * fact(n - 1, _);" +
	"\n  }" +
	"\n  catch (ex) { demo('caught ' + ex.message, _); return 1; }" +
	"\n  finally { demo('finally: n = ' + n, _); }" +
	"\n}" +
	"\n" +
	"\ndemo('fact(4) = ' + fact(4, _), _);" +
	"\n",

	lazySample: "" +
	"// Variant with lazy eval operators." +
	"\n// Note that fact(3, _) is evaluated but fact(5, _) is not" +
	"\n" +
	"\nfunction fact(n, _) {" +
	"\n  demo('n=' + n, _);" +
	"\n  return n == 1 ? demo('!', _) : n * fact(n - 1, _);" +
	"\n}" +
	"\n" +
	"\nvar fact4 = (fact(3, _) - 6) || fact(4, _) || fact(5, _);" +
	"\n" +
	"\ndemo('fact(4) = ' + fact4, _);" +
	"\n",

	futuresSample: "" +
	"// Variant with futures." +
	"\n// Much faster because all futures wait together" +
	"\n" +
	"\n// Intermediate function to return future when called" +
	"\n// without _ (demo does not return future)" +
	"\nfunction demo2(str, _) { return demo(str, _); }" +
	"\n" +
	"\nvar v1 = demo2('1');" +
	"\nvar v2 = demo2('12');" +
	"\nvar v3 = demo2('123');" +
	"\nvar v4 = demo2('1234');" +
	"\n" +
	"\ndemo2('fact(4) = ' +v1(_) * v2(_) * v3(_) * v4(_));" +
	"\n",
}

var _complete = false;

function error(message) {
	$('#result').removeClass('info').addClass('error').text(message);
}

function info(message) {
	$('#result').removeClass('error').addClass('success').text(message);
}

window.__context = {
	errorHandler: function(err) {
		error(err.message || err.toString());
	}
}

eval(_demo); // define demo if user does not execute intro

function _transform() {
	var codeIn = $('#codeIn').val();
	try {
		var codeOut = Streamline.transform(codeIn, {
			noHelpers: !_complete,
			lines: _complete ? "mark" : "ignore"
		});
		$('#codeOut').val(codeOut);
		info("ready")
	} catch (ex) {
		console.error(ex);
		error(ex.message)
	}
}

function _execute() {
	var codeIn = $('#codeIn').val();
	try {
		var codeOut = Streamline.transform(codeIn, {
			lines: "preserve"
		});
		eval(codeOut);
	} catch (ex) {
		error(ex.message);
	}
}

function _beautify(str) {
	try {
		var str = Narcissus.decompiler.pp(Narcissus.parser.parse(str));
		str = str.replace(/}\s*;/g, "}")
		$('#codeIn').val(str);
		return true;
	} catch (ex) {
		error(ex.message);
		return false;
	}
}

$( function() {
	$('#codeIn').keyup(_transform);
	$('.sample').click( function() {
		$('#codeIn').val(_samples[this.id]);
		_transform();
	});
	$('#beautify').click( function() {
		_beautify($('#codeIn').val());
	})
	$('#complete').change( function() {
		_complete = !_complete;
		_transform();
	})
	$('#execute').click( function() {
		_execute();
	})
	$('#codeIn').val(_samples["introSample"]);
	_transform();
})
<|endoftext|>


<commit_before>/* eslint-env mocha */
const Queue = require('../../src').DataStructures.Queue;
const assert = require('assert');

describe('Queue', () => {

});
<commit_msg>Queue: Tests various methods. 100 % coverage<commit_after>/* eslint-env mocha */
const Queue = require('../../src').DataStructures.Queue;
const assert = require('assert');

describe('Queue', () => {
  it('should be empty when initialized', () => {
    const inst = new Queue();
    assert(inst.isEmpty());
    assert.equal(inst.size, 0);
  });

  it('should push a node', () => {
    const inst = new Queue();

    inst.push(10);
    assert(!inst.isEmpty());
    assert.equal(inst.size, 1);
  });

  it('should check front and back value', () => {
    const inst = new Queue();

    inst.push(10);
    inst.push(20);
    inst.push(30);
    inst.push(40);
    inst.push(50);
    assert(!inst.isEmpty());

    assert.equal(inst.size, 5);
    assert.equal(inst.front(), 10);
    assert.equal(inst.back(), 50);
  });

  it('should pop node', () => {
    const inst = new Queue();

    inst.push(10);
    inst.push(20);
    inst.push(30);
    inst.push(40);
    inst.push(50);

    let poppedNodeVal = inst.pop();
    assert.equal(poppedNodeVal, 10);
    assert.equal(inst.front(), 20);
    assert.equal(inst.size, 4);

    inst.pop();
    inst.pop();
    poppedNodeVal = inst.pop();

    assert.equal(poppedNodeVal, 40);
    assert.equal(inst.front(), 50);
    assert.equal(inst.back(), 50);
    assert.equal(inst.size, 1);

    inst.pop();

    assert.throws(() => inst.pop(), Error);
  });

  it('should throw error on popping from empty Queue', () => {
    const inst = new Queue();
    assert(inst.isEmpty());
    assert.equal(inst.size, 0);

    assert.throws(() => inst.pop(), Error);
  });
});
<|endoftext|>


<commit_before>import rateLimit from '../../lib/rate-limit';
import validate from '../../lib/validate';
import changeCase from 'change-case';
import express from 'express';
const router = express.Router();

const slackUrl = process.env.SLACK_WEBHOOK_URL;

if (!slackUrl) {
  exitWithError('Please set SLACK_WEBHOOK_URL environment variable.')
}

import slackApi from '../../lib/slack';
const slack = slackApi(slackUrl);

router.get('/', validate(), (req, res) => {
  const user = dotty.get(req, 'session.user');
  const strings = getStrings();

  strings.apply.form.fullName.value = user.displayName;
  strings.apply.form.email.value = user.emails[0].value;

  res.render('apply', _.assign({}, strings.apply, user));
});

router.post('/', validate(), rateLimit(), (req, res) => {
  const user = dotty.get(req, 'session.user');
  const files = req.files;
  const renameJobs = [];

  debug('Received application from "%s <%s>"', user.displayName, user.emails[0].value);

  for (const field in files) {
    const fileObj = files[field];
    const tmpPath = fileObj.path;
    const filename = field + '-' + fileObj.name;
    const dest = __dirname + '/public/images/' + filename;

    _.assign(fileObj, {
      dest: dest,
      uri: req.originUri + '/images/' + filename
    });

    renameJobs.push(async.apply(mv, tmpPath, dest));

    async.parallel(renameJobs, (err) => {
      if (err) {
        error(err);
        return res.sendStatus(500);
      }

      res.redirect('/thanks');

      slack({
      channel: channel,
      username: botName,
      icon_url: req.originUri + 'images/bot.png',
      attachments: [
        {
          fallback: user.displayName + ' wants to join Slack',
          author_name: user.displayName,
          author_link: user.url,
          author_icon: dotty.get(user, 'image.url'),
          color: '#28f428',
          pretext: 'New invite request:',
          text: req.body.comments ? '"' + req.body.comments + '"' : undefined,
          fields: _.map(
            _.pairs(_.omit(req.body, 'comments')),
            _.flow(
              x => x,
              _.partialRight(_.map, (str, i) => {
                return i ? str : changeCase.title(str);
              }),
              _.partial(_.zipObject, ['title', 'value']),
              _.partialRight(_.assign, { short: true })
            )
          )
            .concat(_.map(files, (file) => ({
              title: file.fieldname,
              value: '<' + file.uri + '|View>',
              short: true
            })))
        }
      ]
    });
  });
}});

export default router;
<commit_msg>add missing imports in apply route<commit_after>import express from 'express';
import _ from 'lodash';
import dotty from 'dotty';
import bug from 'debug';
import changeCase from 'change-case';
import validate from '../../lib/validate';
import rateLimit from '../../lib/rate-limit';
import slackApi from '../../lib/slack';
import { exitWithError, getStrings } from '../../lib/helpers';

const debug = bug('SIR:apply');
const router = express.Router();
const slackUrl = process.env.SLACK_WEBHOOK_URL;
const slack = slackUrl ? slackApi(slackUrl) : exitWithError('Please set SLACK_WEBHOOK_URL environment variable.');

router.get('/', validate(), (req, res) => {
  const user = dotty.get(req, 'session.user');
  const strings = getStrings();

  strings.apply.form.fullName.value = user.displayName;
  strings.apply.form.email.value = user.emails[0].value;

  res.render('apply', _.assign({}, strings.apply, user));
});

router.post('/', validate(), rateLimit(), (req, res) => {
  const user = dotty.get(req, 'session.user');
  const files = req.files;
  const renameJobs = [];

  debug('Received application from "%s <%s>"', user.displayName, user.emails[0].value);

  for (const field in files) {
    const fileObj = files[field];
    const tmpPath = fileObj.path;
    const filename = field + '-' + fileObj.name;
    const dest = __dirname + '/public/images/' + filename;

    _.assign(fileObj, {
      dest: dest,
      uri: req.originUri + '/images/' + filename
    });

    renameJobs.push(async.apply(mv, tmpPath, dest));

    async.parallel(renameJobs, (err) => {
      if (err) {
        error(err);
        return res.sendStatus(500);
      }

      res.redirect('/thanks');

      slack({
      channel: channel,
      username: botName,
      icon_url: req.originUri + 'images/bot.png',
      attachments: [
        {
          fallback: user.displayName + ' wants to join Slack',
          author_name: user.displayName,
          author_link: user.url,
          author_icon: dotty.get(user, 'image.url'),
          color: '#28f428',
          pretext: 'New invite request:',
          text: req.body.comments ? '"' + req.body.comments + '"' : undefined,
          fields: _.map(
            _.pairs(_.omit(req.body, 'comments')),
            _.flow(
              x => x,
              _.partialRight(_.map, (str, i) => {
                return i ? str : changeCase.title(str);
              }),
              _.partial(_.zipObject, ['title', 'value']),
              _.partialRight(_.assign, { short: true })
            )
          )
            .concat(_.map(files, (file) => ({
              title: file.fieldname,
              value: '<' + file.uri + '|View>',
              short: true
            })))
        }
      ]
    });
  });
}});

export default router;
<|endoftext|>


<commit_before>var Survey = require('../models/survey');
var SurveyItem = require('../models/surveyitem');
var SurveyVote = require('../models/surveyvote');
var User = require('../models/user');
var Response = require('../modules/response');

var express = require('express');
var async = require('async');
var calls = [];

var router = express.Router();

router.route('/surveyVotes/:survey_id').post(createSurveyVote);
router.route('/surveyVotes/:survey_id').get(getSurveyVotes);
router.route('/surveyVote/:surveyVote_id').get(getSurveyVote);
router.route('/surveyVote/:surveyVote_id').delete(deleteSurveyVote);

module.exports = router;

function createSurveyVote(req, res){
        console.log(req.body);
    var surveyFound = true;
    var userFound = true;
    var surveyItemFound = true;

    var surveyVoteFound = true;
    var numberChoices = -1;
    var surveyClosed = false;

    var user = null;
    var survey = null;
    var surveyItems = [];

    var surveyVoteNotCreated = false;

    var surveyVotes = [];

    if (!('username' in req.body)){
        Response(res, "Error : No username given", null, 0);
        return;
    }
    if (!('items' in req.body)){
        Response(res, "Error : No items given", null, 0);
        return;
    }
    else if (!Array.isArray(req.body.items)){
        Response(res, "Error : Items must be an array", null, 0);
        return;
    }

    async.parallel([
        function(callback){
            User.findOne({username : req.body.username}, function(err, u){
                if (err || u == null) userFound = false;
                else user = u._id;
                console.log("User in callback function : "+ user);
                callback();
            });
        },
        function(callback){
            Survey.findById(req.params.survey_id, function(err, s){
                if (err || s == null) surveyFound = false;
                else {
                    survey = s._id;
                    numberChoices = s.numberChoices;
                    surveyClosed = s.isClosed;
                }
                callback();
            });
        }],
                   function(err){
        async.each(req.body.items, function(v, callback){
            console.log(req.body.items);
            console.log("item : " + v);
            console.log("user : " + user + " - survey : " + survey + " - userFound : " +userFound);
            SurveyItem.findById(v, function(err, surveyItem){
                if (err || surveyItem == null) surveyItemFound = false;
                else surveyItems.push(surveyItem._id);
                callback();
            });
        }, function(err){
            console.log("Testing values");
            if (!userFound) Response(res, "Error : User not found", null, 0);
            else if (!surveyFound) Response(res, "Error : Survey not found", null, 0);
            else if (!surveyItemFound) Response(res, "Error : One SurveyItem not valid", null, 0);
            else if (surveyClosed) Response(res, "Error : Survey closed", null, 0);
            else {
                console.log("Survey : " + surveyItems);

                async.series([
                    function(callback){
                        SurveyVote.remove({user : user, survey : survey}, function(err){
                            callback();
                        });
                    },
                    function(callback){
                        async.each(surveyItems, function(v, callback2){
                            var sv = new SurveyVote();

                            sv.user = user;
                            sv.survey = survey;
                            sv.value = v;

                            surveyVotes.push(sv);
                            console.log(sv);
                            sv.save(function(err){
                                if (err){
                                    surveyVoteNotCreated = true;
                                }
                                callback2();
                            });
                        });
                        callback();
                    },
                    function(callback){
                        console.log("Pute " + surveyVotes);
                        if (surveyVoteNotCreated)
                            Response(res, "Error : SurveyVote not created", null, 0);
                        else
                            Response(res, "SurveyVotes created", surveyVotes, 1);
                        callback();
                    }
                ]);
            }
        });
    });
}

function getSurveyVotes(req, res){
    SurveyVote.find({survey : req.params.survey_id}, function(err, sv){
        if (err) Response(res, "Error", err, 0);
        else Response(res, "SurveyVotes found", sv, 1);
    });
}

function getSurveyVote(req, res){
    SurveyVote.findById(req.params.surveyVote_id, function(err, sv){
        if (err) Response(res, "Error", err, 0);
        else if (sv == null) Response(res, "Error : SurveyVote not found", null, 0);
        else Response(res, "SurveyVote found", sv, 1);
    });
}

function deleteSurveyVote(req, res){
    SurveyVote.remove({_id : req.params.surveyVote_id}, function(err, sv){
        if (err) Response(res, "Error", err, 0);
        else Response(res, "SurveyVote deleted", sv, 1);
    });
}<commit_msg>Correction of a require bug on surveyVote<commit_after>var Survey = require('../models/survey');
var SurveyItem = require('../models/surveyItem');
var SurveyVote = require('../models/surveyVote');
var User = require('../models/user');
var Response = require('../modules/response');

var express = require('express');
var async = require('async');
var calls = [];

var router = express.Router();

router.route('/surveyVotes/:survey_id').post(createSurveyVote);
router.route('/surveyVotes/:survey_id').get(getSurveyVotes);
router.route('/surveyVote/:surveyVote_id').get(getSurveyVote);
router.route('/surveyVote/:surveyVote_id').delete(deleteSurveyVote);

module.exports = router;

function createSurveyVote(req, res){
        console.log(req.body);
    var surveyFound = true;
    var userFound = true;
    var surveyItemFound = true;

    var surveyVoteFound = true;
    var numberChoices = -1;
    var surveyClosed = false;

    var user = null;
    var survey = null;
    var surveyItems = [];

    var surveyVoteNotCreated = false;

    var surveyVotes = [];

    if (!('username' in req.body)){
        Response(res, "Error : No username given", null, 0);
        return;
    }
    if (!('items' in req.body)){
        Response(res, "Error : No items given", null, 0);
        return;
    }
    else if (!Array.isArray(req.body.items)){
        Response(res, "Error : Items must be an array", null, 0);
        return;
    }

    async.parallel([
        function(callback){
            User.findOne({username : req.body.username}, function(err, u){
                if (err || u == null) userFound = false;
                else user = u._id;
                console.log("User in callback function : "+ user);
                callback();
            });
        },
        function(callback){
            Survey.findById(req.params.survey_id, function(err, s){
                if (err || s == null) surveyFound = false;
                else {
                    survey = s._id;
                    numberChoices = s.numberChoices;
                    surveyClosed = s.isClosed;
                }
                callback();
            });
        }],
                   function(err){
        async.each(req.body.items, function(v, callback){
            console.log(req.body.items);
            console.log("item : " + v);
            console.log("user : " + user + " - survey : " + survey + " - userFound : " +userFound);
            SurveyItem.findById(v, function(err, surveyItem){
                if (err || surveyItem == null) surveyItemFound = false;
                else surveyItems.push(surveyItem._id);
                callback();
            });
        }, function(err){
            console.log("Testing values");
            if (!userFound) Response(res, "Error : User not found", null, 0);
            else if (!surveyFound) Response(res, "Error : Survey not found", null, 0);
            else if (!surveyItemFound) Response(res, "Error : One SurveyItem not valid", null, 0);
            else if (surveyClosed) Response(res, "Error : Survey closed", null, 0);
            else {
                console.log("Survey : " + surveyItems);

                async.series([
                    function(callback){
                        SurveyVote.remove({user : user, survey : survey}, function(err){
                            callback();
                        });
                    },
                    function(callback){
                        async.each(surveyItems, function(v, callback2){
                            var sv = new SurveyVote();

                            sv.user = user;
                            sv.survey = survey;
                            sv.value = v;

                            surveyVotes.push(sv);
                            console.log(sv);
                            sv.save(function(err){
                                if (err){
                                    surveyVoteNotCreated = true;
                                }
                                callback2();
                            });
                        });
                        callback();
                    },
                    function(callback){
                        console.log("Pute " + surveyVotes);
                        if (surveyVoteNotCreated)
                            Response(res, "Error : SurveyVote not created", null, 0);
                        else
                            Response(res, "SurveyVotes created", surveyVotes, 1);
                        callback();
                    }
                ]);
            }
        });
    });
}

function getSurveyVotes(req, res){
    SurveyVote.find({survey : req.params.survey_id}, function(err, sv){
        if (err) Response(res, "Error", err, 0);
        else Response(res, "SurveyVotes found", sv, 1);
    });
}

function getSurveyVote(req, res){
    SurveyVote.findById(req.params.surveyVote_id, function(err, sv){
        if (err) Response(res, "Error", err, 0);
        else if (sv == null) Response(res, "Error : SurveyVote not found", null, 0);
        else Response(res, "SurveyVote found", sv, 1);
    });
}

function deleteSurveyVote(req, res){
    SurveyVote.remove({_id : req.params.surveyVote_id}, function(err, sv){
        if (err) Response(res, "Error", err, 0);
        else Response(res, "SurveyVote deleted", sv, 1);
    });
}<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var UserInvite = require('../models/userInvite');
var Verify = require('./verify');
var SendMail = require('./sendmail');

var router = express.Router();
router.use(bodyParser.json());

//#################################################################################################
//#################################################################################################
router.route('/')

//get all user invites:
.get(function(req, res) {
    UserInvite.find(req.query)
        .populate('role')
        .exec(function(err, userInvites) {
            if(err) throw err;
            res.json(userInvites);
    });
})

//add a new user invite to the system:
.post(Verify.verifyOrdinaryUser, SendMail.sendInviteEmail, function(req, res, next) {
    console.log(req.emailResponse);
    UserInvite.create(req.body, function(err, userInvite) {
        if(err) return next(err);
        console.log("New user invite created");
        res.json(userInvite);
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    UserInvite.remove({}, function(err, userInvites) {
        if(err) return next(err);
        console.log("Removed: \n" + userInvites);
        res.json("All user invites removed.");
    });
});

//#################################################################################################
//#################################################################################################
router.route('/:userInviteId')

///GET user invite by ID
.get(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findById(req.params.userInviteId)
        .populate('role')
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
})

//PUT update user invite by ID
.put(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findByIdAndUpdate(req.params.userInviteId, {$set: req.body}, {new: true})
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
})

///DELETE user invite by ID
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findById(req.params.userInviteId)
        .exec(function(err, userInvite) {
            if(err) throw err;
            userInvite.remove();
            res.json("Successfully removed user invite " + userInvite.invite_key);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/findByKey/:inviteKey')

///GET user invite by invite key
.get(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.find({invite_key: req.params.inviteKey})
        .populate('role')
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/deleteByKey/:inviteKey')

///DELETE user invite by invite key
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.find({invite_key: req.params.inviteKey})
        .exec(function(err, userInvite) {
            if(err) throw err;
            userInvite.remove();
            res.json("Successfully removed user invite " + userInvite.invite_key);
    });
});

module.exports = router;<commit_msg>correction, changed deleteByKey to findOne<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var UserInvite = require('../models/userInvite');
var Verify = require('./verify');
var SendMail = require('./sendmail');

var router = express.Router();
router.use(bodyParser.json());

//#################################################################################################
//#################################################################################################
router.route('/')

//get all user invites:
.get(function(req, res) {
    UserInvite.find(req.query)
        .populate('role')
        .exec(function(err, userInvites) {
            if(err) throw err;
            res.json(userInvites);
    });
})

//add a new user invite to the system:
.post(Verify.verifyOrdinaryUser, SendMail.sendInviteEmail, function(req, res, next) {
    console.log(req.emailResponse);
    UserInvite.create(req.body, function(err, userInvite) {
        if(err) return next(err);
        console.log("New user invite created");
        res.json(userInvite);
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    UserInvite.remove({}, function(err, userInvites) {
        if(err) return next(err);
        console.log("Removed: \n" + userInvites);
        res.json("All user invites removed.");
    });
});

//#################################################################################################
//#################################################################################################
router.route('/:userInviteId')

///GET user invite by ID
.get(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findById(req.params.userInviteId)
        .populate('role')
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
})

//PUT update user invite by ID
.put(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findByIdAndUpdate(req.params.userInviteId, {$set: req.body}, {new: true})
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
})

///DELETE user invite by ID
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findById(req.params.userInviteId)
        .exec(function(err, userInvite) {
            if(err) throw err;
            userInvite.remove();
            res.json("Successfully removed user invite " + userInvite.invite_key);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/findByKey/:inviteKey')

///GET user invite by invite key
.get(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.find({invite_key: req.params.inviteKey})
        .populate('role')
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/deleteByKey/:inviteKey')

///DELETE user invite by invite key
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findOne({invite_key: req.params.inviteKey})
        .exec(function(err, userInvite) {
            if(err) throw err;
            userInvite.remove();
            res.json("Successfully removed user invite " + userInvite.invite_key);
    });
});

module.exports = router;<|endoftext|>


<commit_before>'use strict';

var app = app || {};

(function(module) {

  function Meet (rawSQLResults) {
    Object.assign(this, rawSQLResults);
    this.militaryTime = toMilitaryTime(rawSQLResults.time);
    this.timeBatch = calculateTimeBatch(this.militaryTime);
    // this.nextMeeting = new Date();
    // this.nextMeeting.setDate(todaysDate.getDate() + weekdayDifference(rawSQLResults.weekday));
    // this.nextMeeting.setHours(this.militaryTime, this.militaryTime);
  }

  var todaysDate = new Date();
  var endOfToday = new Date();
  endOfToday.setHours(24, 0, 0, 0);

  var daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

  var todaysWeekday = todaysDate.toString().substring(0, 3);

  const meetings = {};

  meetings.all = [];
  meetings.filtered = [];

  meetings.getAllMeetings = function(callback) {
    $.get('/meetings')
      .then(
        results => {
          results.forEach(obj => {
            var newGuy = new Meet(obj);
            meetings.all.push(newGuy);
          });
        }
      )
      .then(callback);
  };

  // function weekdayDifference(weekday) {
  //   var dayIndex = todaysDate.getDay();
  //   var meetIndex = daysOfWeek.indexOf(weekday);
  //   var difference = meetIndex - dayIndex;
  //   return difference >= 0 ? difference : difference + 7;
  // }

  function toMilitaryTime(time) {
    var transformedTime;
    if (time.substring(0, 2) === '12') {
      if (time.includes('AM')) {
        transformedTime = '0' + time.substring(2, 5);
      } else {
        transformedTime = time.split(' ')[0];
      }
    } else if (time.includes('PM')) {
      transformedTime = time.replace(/^\d{1,2}/, parseInt(time.match(/^\d{1,2}/)) + 12).split(' ')[0];
    } else {
      transformedTime = time.split(' ')[0];
    }
    var intermediateTime = transformedTime.replace(/:/ig, '');
    if(intermediateTime.length === 3){
      var finalTime = '0' + intermediateTime;
      return finalTime;
    }
    return intermediateTime;
  }

  function calculateTimeBatch(milTime) {
    if (milTime < 1159) {
      return 'Morning';
    } else if (milTime >= 1200 && milTime < 1659) {
      return 'Afternoon';
    } else if (milTime >= 1700 && milTime < 2059) {
      return 'Evening';
    } else {
      return 'Night';
    }
  }

  meetings.dateFiltered = () => {
    app.meetings.filtered = [];
    meetings.all.filter(meet => {
      var mtgLocation = new google.maps.LatLng(meet.lat, meet.lng);
      meet.distanceBetween = (0.000621371 * google.maps.geometry.spherical.computeDistanceBetween(app.mapThings.userLocation, mtgLocation));

      if (meet.weekday.includes(todaysWeekday) && meet.distanceBetween <= app.formData.Submission.radiusString && meet.timeBatch === app.formData.Submission.timeString) {
        meetings.filtered.push(meet);
      }
    });
  };
  module.meetings = meetings;
})(app);
<commit_msg>cleaning up dateController<commit_after>'use strict';

var app = app || {};

(function(module) {

  function Meet (rawSQLResults) {
    Object.assign(this, rawSQLResults);
    this.militaryTime = toMilitaryTime(rawSQLResults.time);
    this.timeBatch = calculateTimeBatch(this.militaryTime);
  }

  var todaysDate = new Date();

  var daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

  var todaysWeekday = todaysDate.toString().substring(0, 3);

  const meetings = {};

  meetings.all = [];
  meetings.filtered = [];

  meetings.getAllMeetings = function(callback) {
    $.get('/meetings')
      .then(
        results => {
          results.forEach(obj => {
            var newObj = new Meet(obj);
            meetings.all.push(newObj);
          });
        }
      )
      .then(callback);
  };

  function toMilitaryTime(time) {
    var transformedTime;
    if (time.substring(0, 2) === '12') {
      if (time.includes('AM')) {
        transformedTime = '0' + time.substring(2, 5);
      } else {
        transformedTime = time.split(' ')[0];
      }
    } else if (time.includes('PM')) {
      transformedTime = time.replace(/^\d{1,2}/, parseInt(time.match(/^\d{1,2}/)) + 12).split(' ')[0];
    } else {
      transformedTime = time.split(' ')[0];
    }
    var intermediateTime = transformedTime.replace(/:/ig, '');
    if(intermediateTime.length === 3){
      var finalTime = '0' + intermediateTime;
      return finalTime;
    }
    return intermediateTime;
  }

  function calculateTimeBatch(milTime) {
    if (milTime < 1159) {
      return 'Morning';
    } else if (milTime >= 1200 && milTime < 1659) {
      return 'Afternoon';
    } else if (milTime >= 1700 && milTime < 2059) {
      return 'Evening';
    } else {
      return 'Night';
    }
  }

  meetings.dateFiltered = () => {
    app.meetings.filtered = [];
    meetings.all.filter(meet => {
      var mtgLocation = new google.maps.LatLng(meet.lat, meet.lng);
      meet.distanceBetween = (0.000621371 * google.maps.geometry.spherical.computeDistanceBetween(app.mapThings.userLocation, mtgLocation));

      if (meet.weekday.includes(todaysWeekday) && meet.distanceBetween <= app.formData.Submission.radiusString && meet.timeBatch === app.formData.Submission.timeString) {
        meetings.filtered.push(meet);
      }
    });
  };
  module.meetings = meetings;
})(app);
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Checkbox control")
description("This will return the checkbox control")
base_component_id("checkbox_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "checked",
            name:       "Checked",
            type:       "Select",
            default:    "True",
            values:     [
                            {display: "True",   value: "True"},
                            {display: "False",  value: "False"}
                        ]
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
    ]
)//properties
logo_url("/driver_icons/checkbox_control.png")
*/

    Vue.component("checkbox_control",{
      props: ["args","design_mode","meta", "form",  "name", "refresh"]
      ,
      template: `<input v-bind:id='design_mode?"":args.name'
                        type="checkbox"
                        v-on:change='valChanged(event)'
                        v-bind:checked='(args.checked=="True")?"True":""'
                        >

                 </input>`
      ,
      data: function() {
          return {
          }
      }
      ,
      mounted: function() {
        registerComponent(this)
      }
      ,
      methods: {
          valChanged: function(e) {
              if(e.target.checked) {
                  this.args.checked="True"
              } else {
                  this.args.checked="False"
              }
          }
      }
    })
}
<commit_msg>Added a changed event<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Checkbox control")
description("This will return the checkbox control")
base_component_id("checkbox_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "checked",
            name:       "Checked",
            type:       "Select",
            default:    "True",
            values:     [
                            {display: "True",   value: "True"},
                            {display: "False",  value: "False"}
                        ]
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:     "changed_event",
            name:   "Changed event",
            type:   "Event",
            help:       `
Help text for
                            changed_event event

`
        }

    ]
)//properties
logo_url("/driver_icons/checkbox_control.png")
*/

    Vue.component("checkbox_control",{
      props: ["args","design_mode","meta", "form",  "name", "refresh"]
      ,
      template: `<input v-bind:id='design_mode?"":args.name'
                        type="checkbox"
                        v-on:change='valChanged(event)'
                        v-bind:checked='(args.checked=="True")?"True":""'
                        >

                 </input>`
      ,
      data: function() {
          return {
          }
      }
      ,
      mounted: function() {
        registerComponent(this)
      }
      ,
      methods: {
          valChanged: function(e) {
              if(e.target.checked) {
                  this.args.checked="True"
              } else {
                  this.args.checked="False"
              }
              this.$emit('send', {
                                              type:               "subcomponent_event",
                                              form_name:           this.meta.form,
                                              control_name:        this.meta.name,
                                              sub_type:           "changed",
                                              code:                this.args.changed_event
                                          })

          }
      }
    })
}
<|endoftext|>


<commit_before>// from http://eloquentjavascript.net/code/#17.2
'use strict';

function all(promises) {
  return new Promise(function(success, fail) {
    // Your code here.
  });
}

// Test code.
all([]).then(function(array) {
  console.log("This should be []:", array);
});
function soon(val) {
  return new Promise(function(success) {
    setTimeout(function() { success(val); },
               Math.random() * 500);
  });
}
all([soon(1), soon(2), soon(3)]).then(function(array) {
  console.log("This should be [1, 2, 3]:", array);
});
function fail() {
  return new Promise(function(success, fail) {
    fail(new Error("boom"));
  });
}
all([soon(1), fail(), soon(3)]).then(function(array) {
  console.log("We should not get here");
}, function(error) {
  if (error.message != "boom")
    console.log("Unexpected failure:", error);
});
<commit_msg>17.2 Waiting for multiple promises, eslinting<commit_after>// from http://eloquentjavascript.net/code/#17.2
'use strict';

/**
 * all
 * @param {object} promises
 * @return {object}
 */
function all(promises) {
  return new Promise(function(success, fail) {
    // Your code here.
  });
}

// Test code.
all([]).then(function(array) {
  console.log('This should be []:', array);
});
/**
 * soon
 * @param {object} val
 * @return {object}
 */
function soon(val) {
  return new Promise(function(success) {
    setTimeout(function() {
 success(val);
},
               Math.random() * 500);
  });
}
all([soon(1), soon(2), soon(3)]).then(function(array) {
  console.log('This should be [1, 2, 3]:', array);
});
/**
 * fail
 * @return {object}
 */
function fail() {
  return new Promise(function(success, fail) {
    fail(new Error('boom'));
  });
}
all([soon(1), fail(), soon(3)]).then(function(array) {
  console.log('We should not get here');
}, function(error) {
  if (error.message != 'boom')
    console.log('Unexpected failure:', error);
});
<|endoftext|>


<commit_before>experimental-download.js<commit_msg>Set up experimental download using aws-sdk directly<commit_after>var AWS = require('aws-sdk');

var filePath = '/Users/mikermcneil/Desktop/foo.txt';
var awsAccessKey = process.argv[2];
var awsSecret = process.argv[3];
var bucketName = 'experiment-jun28-2018';

console.log('Using AWS access key:', awsAccessKey);
console.log('Using AWS secret:', awsSecret);
console.log('Using bucket:', bucketName);
console.log('Uploading file:', filePath);

var s3 = new AWS.S3({
  apiVersion: '2006-03-01',
  region: 'us-west-2',
  accessKeyId: awsAccessKey,
  secretAccessKey: awsSecret
});

var readable = s3.getObject({
  Bucket: bucketName,
  Key: require('path').basename(filePath),
})
.createReadStream();
readable.on('error', (err)=>{
  console.error('s3 download stream error:',err);
});
var drain = require('fs').createWriteStream('/Users/mikermcneil/Desktop/downloaded-foo.txt');
drain.on('error', (err)=>{
  console.error('local filesystem write error:',err);
});

readable.pipe(drain);
console.log('Download Success!');

// wtf:
//
// s3.getObject({
//   Bucket: bucketName,
//   Key: require('path').basename(filePath),
// }, function (err, data) {
//   if (err) {
//     console.log('Error', err);
//   } if (data) {
//     console.log('Download Success', data);
//   }
// });
<|endoftext|>