<commit_before>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Creates correctly formatted tooltip for Apps
//-------------------------------------------------------------------
d3plus.tooltip.app = function(params) {

  var vars = params.vars,
      d = params.data,
      ex = params.ex,
      mouse = params.mouseevents ? params.mouseevents : false,
      arrow = "arrow" in params ? params.arrow : true,
      id = d3plus.variable.value(vars,d,vars.id.key),
      tooltip_id = params.id || vars.type.value

  if ((d3.event && d3.event.type == "click") && (vars.html.value || vars.tooltip.value.long) && !("fullscreen" in params)) {
    var fullscreen = true,
        arrow = false,
        mouse = true,
        length = "long",
        footer = vars.footer.value

    vars.covered = true
  }
  else {
    var fullscreen = false,
        align = params.anchor || vars.style.tooltip.anchor,
        length = params.length || "short",
        zoom = vars.zoom_direction()

    if (zoom === -1) {
      var key = vars.id.nesting[vars.depth.value-1],
          parent = d3plus.variable.value(vars,id,key),
          solo = vars.id.solo.value.indexOf(parent) >= 0
    }

    if (zoom === 1 && vars.zoom.value) {
      var text = vars.format("Click to Expand")
    }
    else if (zoom === -1 && vars.zoom.value && solo) {
      var text = vars.format("Click to Collapse")
    }
    else if (length == "short" && (vars.html.value || vars.tooltip.value.long) && vars.focus.value != id) {
      var text = "Click for More Info"
    }
    else {
      var text = vars.footer.value || ""
    }

    var footer = vars.format(text,"footer")

  }

  if ("x" in params) {
    var x = params.x
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var x = d3.mouse(vars.parent.node())[0]
  }
  else {
    var x = d.d3plus.x
    if (vars.zoom.translate && vars.zoom.scale) {
      x = vars.zoom.translate[0]+x*vars.zoom.scale
    }
    x += vars.margin.left
  }

  if ("y" in params) {
    var y = params.y
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var y = d3.mouse(vars.parent.node())[1]
  }
  else {
    var y = d.d3plus.y
    if (vars.zoom.translate && vars.zoom.scale) {
      y = vars.zoom.translate[1]+y*vars.zoom.scale
    }
    y += vars.margin.top
  }

  if ("offset" in params) {
    var offset = params.offset
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var offset = 3
  }
  else {
    var offset = d.d3plus.r ? d.d3plus.r : d.d3plus.height/2
    if (vars.zoom.scale) {
      offset = offset * vars.zoom.scale
    }
  }

  function make_tooltip(html) {

    if (d.d3plus) {

      if (d.d3plus.merged) {
        if (!ex) ex = {}
        ex.items = d.d3plus.merged.length
      }

      var active = vars.active.key ? d3plus.variable.value(vars,d,vars.active.key) : d.d3plus.active,
          temp = vars.temp.key ? d3plus.variable.value(vars,d,vars.temp.key) : d.d3plus.temp,
          total = vars.total.key ? d3plus.variable.value(vars,d,vars.total.key) : d.d3plus.total

      if (typeof active == "number" && active > 0 && total) {
        if (!ex) ex = {}
        var label = vars.active.key || "active"
        ex[label] = active+"/"+total+" ("+vars.format((active/total)*100,"share")+"%)"
      }

      if (typeof temp == "number" && temp > 0 && total) {
        if (!ex) ex = {}
        var label = vars.temp.key || "temp"
        ex[label] = temp+"/"+total+" ("+vars.format((temp/total)*100,"share")+"%)"
      }

      if (d.d3plus.share) {
        if (!ex) ex = {}
        ex.share = vars.format(d.d3plus.share*100,"share")+"%"
      }

    }

    var depth = "depth" in params ? params.depth : vars.depth.value,
        title = d3plus.variable.text(vars,d,depth)[0],
        icon = d3plus.variable.value(vars,d,vars.icon.key,vars.id.nesting[depth]),
        tooltip_data = d3plus.tooltip.data(vars,d,length,ex,depth)

    if ((tooltip_data.length > 0 || footer) || ((!d.d3plus_label && length == "short") || (d.d3plus_label && "visible" in d.d3plus_label && !d.d3plus_label.visible))) {

      if (!title) {
        title = id
      }

      var depth = d.d3plus && "depth" in d.d3plus ? vars.id.nesting[d.d3plus.depth] : vars.id.key

      if (typeof vars.icon.style.value == "string") {
        var icon_style = vars.icon.style.value
      }
      else if (typeof vars.icon.style.value == "object" && vars.icon.style.value[depth]) {
        var icon_style = vars.icon.style.value[depth]
      }
      else {
        var icon_style = "default"
      }

      if (params.width) {
        var width = params.width
      }
      else if (!fullscreen && tooltip_data.length == 0) {
        var width = "auto"
      }
      else {
        var width = vars.style.tooltip.small
      }

      d3plus.tooltip.create({
        "align": align,
        "arrow": arrow,
        "background": vars.style.tooltip.background,
        "curtain": vars.style.tooltip.curtain.color,
        "curtainopacity": vars.style.tooltip.curtain.opacity,
        "fontcolor": vars.style.tooltip.font.color,
        "fontfamily": vars.style.tooltip.font.family,
        "fontsize": vars.style.tooltip.font.size,
        "fontweight": vars.style.tooltip.font.weight,
        "data": tooltip_data,
        "color": d3plus.variable.color(vars,d),
        "footer": footer,
        "fullscreen": fullscreen,
        "html": html,
        "icon": icon,
        "id": tooltip_id,
        "max_height": params.maxheight,
        "max_width": vars.style.tooltip.small,
        "mouseevents": mouse,
        "offset": offset,
        "parent": vars.parent,
        "style": icon_style,
        "title": title,
        "width": width,
        "x": x,
        "y": y
      })

    }

  }

  if (fullscreen) {

    if (typeof vars.html.value == "string") {
      make_tooltip(vars.html.value)
    }
    else if (typeof vars.html.value == "function") {
      make_tooltip(vars.html.value(id))
    }
    else if (vars.html.value && typeof vars.html.value == "object" && vars.html.value.url) {
      d3.json(vars.html.value.url,function(data){
        var html = vars.html.value.callback ? vars.html.value.callback(data) : data
        make_tooltip(html)
      })
    }
    else {
      make_tooltip("")
    }

  }
  else {
    make_tooltip("")
  }

}
<commit_msg>prevent null footer value from passing to text_format<commit_after>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Creates correctly formatted tooltip for Apps
//-------------------------------------------------------------------
d3plus.tooltip.app = function(params) {

  var vars = params.vars,
      d = params.data,
      ex = params.ex,
      mouse = params.mouseevents ? params.mouseevents : false,
      arrow = "arrow" in params ? params.arrow : true,
      id = d3plus.variable.value(vars,d,vars.id.key),
      tooltip_id = params.id || vars.type.value

  if ((d3.event && d3.event.type == "click") && (vars.html.value || vars.tooltip.value.long) && !("fullscreen" in params)) {
    var fullscreen = true,
        arrow = false,
        mouse = true,
        length = "long",
        footer = vars.footer.value

    vars.covered = true
  }
  else {
    var fullscreen = false,
        align = params.anchor || vars.style.tooltip.anchor,
        length = params.length || "short",
        zoom = vars.zoom_direction()

    if (zoom === -1) {
      var key = vars.id.nesting[vars.depth.value-1],
          parent = d3plus.variable.value(vars,id,key),
          solo = vars.id.solo.value.indexOf(parent) >= 0
    }

    if (zoom === 1 && vars.zoom.value) {
      var text = vars.format("Click to Expand")
    }
    else if (zoom === -1 && vars.zoom.value && solo) {
      var text = vars.format("Click to Collapse")
    }
    else if (length == "short" && (vars.html.value || vars.tooltip.value.long) && vars.focus.value != id) {
      var text = "Click for More Info"
    }
    else {
      var text = vars.footer.value || ""
    }

    var footer = text.length ? vars.format(text,"footer") : false

  }

  if ("x" in params) {
    var x = params.x
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var x = d3.mouse(vars.parent.node())[0]
  }
  else {
    var x = d.d3plus.x
    if (vars.zoom.translate && vars.zoom.scale) {
      x = vars.zoom.translate[0]+x*vars.zoom.scale
    }
    x += vars.margin.left
  }

  if ("y" in params) {
    var y = params.y
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var y = d3.mouse(vars.parent.node())[1]
  }
  else {
    var y = d.d3plus.y
    if (vars.zoom.translate && vars.zoom.scale) {
      y = vars.zoom.translate[1]+y*vars.zoom.scale
    }
    y += vars.margin.top
  }

  if ("offset" in params) {
    var offset = params.offset
  }
  else if (d3plus.apps[vars.type.value].tooltip == "follow") {
    var offset = 3
  }
  else {
    var offset = d.d3plus.r ? d.d3plus.r : d.d3plus.height/2
    if (vars.zoom.scale) {
      offset = offset * vars.zoom.scale
    }
  }

  function make_tooltip(html) {

    if (d.d3plus) {

      if (d.d3plus.merged) {
        if (!ex) ex = {}
        ex.items = d.d3plus.merged.length
      }

      var active = vars.active.key ? d3plus.variable.value(vars,d,vars.active.key) : d.d3plus.active,
          temp = vars.temp.key ? d3plus.variable.value(vars,d,vars.temp.key) : d.d3plus.temp,
          total = vars.total.key ? d3plus.variable.value(vars,d,vars.total.key) : d.d3plus.total

      if (typeof active == "number" && active > 0 && total) {
        if (!ex) ex = {}
        var label = vars.active.key || "active"
        ex[label] = active+"/"+total+" ("+vars.format((active/total)*100,"share")+"%)"
      }

      if (typeof temp == "number" && temp > 0 && total) {
        if (!ex) ex = {}
        var label = vars.temp.key || "temp"
        ex[label] = temp+"/"+total+" ("+vars.format((temp/total)*100,"share")+"%)"
      }

      if (d.d3plus.share) {
        if (!ex) ex = {}
        ex.share = vars.format(d.d3plus.share*100,"share")+"%"
      }

    }

    var depth = "depth" in params ? params.depth : vars.depth.value,
        title = d3plus.variable.text(vars,d,depth)[0],
        icon = d3plus.variable.value(vars,d,vars.icon.key,vars.id.nesting[depth]),
        tooltip_data = d3plus.tooltip.data(vars,d,length,ex,depth)

    if ((tooltip_data.length > 0 || footer) || ((!d.d3plus_label && length == "short") || (d.d3plus_label && "visible" in d.d3plus_label && !d.d3plus_label.visible))) {

      if (!title) {
        title = id
      }

      var depth = d.d3plus && "depth" in d.d3plus ? vars.id.nesting[d.d3plus.depth] : vars.id.key

      if (typeof vars.icon.style.value == "string") {
        var icon_style = vars.icon.style.value
      }
      else if (typeof vars.icon.style.value == "object" && vars.icon.style.value[depth]) {
        var icon_style = vars.icon.style.value[depth]
      }
      else {
        var icon_style = "default"
      }

      if (params.width) {
        var width = params.width
      }
      else if (!fullscreen && tooltip_data.length == 0) {
        var width = "auto"
      }
      else {
        var width = vars.style.tooltip.small
      }

      d3plus.tooltip.create({
        "align": align,
        "arrow": arrow,
        "background": vars.style.tooltip.background,
        "curtain": vars.style.tooltip.curtain.color,
        "curtainopacity": vars.style.tooltip.curtain.opacity,
        "fontcolor": vars.style.tooltip.font.color,
        "fontfamily": vars.style.tooltip.font.family,
        "fontsize": vars.style.tooltip.font.size,
        "fontweight": vars.style.tooltip.font.weight,
        "data": tooltip_data,
        "color": d3plus.variable.color(vars,d),
        "footer": footer,
        "fullscreen": fullscreen,
        "html": html,
        "icon": icon,
        "id": tooltip_id,
        "max_height": params.maxheight,
        "max_width": vars.style.tooltip.small,
        "mouseevents": mouse,
        "offset": offset,
        "parent": vars.parent,
        "style": icon_style,
        "title": title,
        "width": width,
        "x": x,
        "y": y
      })

    }

  }

  if (fullscreen) {

    if (typeof vars.html.value == "string") {
      make_tooltip(vars.html.value)
    }
    else if (typeof vars.html.value == "function") {
      make_tooltip(vars.html.value(id))
    }
    else if (vars.html.value && typeof vars.html.value == "object" && vars.html.value.url) {
      d3.json(vars.html.value.url,function(data){
        var html = vars.html.value.callback ? vars.html.value.callback(data) : data
        make_tooltip(html)
      })
    }
    else {
      make_tooltip("")
    }

  }
  else {
    make_tooltip("")
  }

}
<|endoftext|>


<commit_before>Array.prototype.move = function(old_index, new_index) {
  if (new_index >= this.length) {
    var k = new_index - this.length;
    while ((k--) + 1) {
      this.push(undefined);
    }
  }
  this.splice(new_index, 0, this.splice(old_index, 1)[0]);
  return this; // for testing purposes
};

var container = document.getElementById('jsoneditor');
var container2 = document.getElementById('jsoneditor2');

var options = {
  mode: 'tree',
  modes: ['code', 'form', 'text', 'tree', 'view'], // allowed modes
  error: function(err) {
    alert(err.toString());
  }
};

new_editor = ace.edit("new-editor");
edit_editor = ace.edit("edit-editor");

function ctrler($scope) {
  $scope.items = [
    {
      "type": "filter",
      "name": "Songs named Possum",
      "code": "function (object) {\n  return object.Title.indexOf('Possum') === 0;\n}\n"
    }
  ];

  $scope.data = {};
  $scope.data.name = "";
  $scope.data.edit_name = "";
  $scope.editing = false;
  $scope.editing_index = -1;
  $scope.is_horiz = true;

  $scope.edit = function(i) {
    $scope.editing = true;
    $scope.editing_index = i;
    $scope.data.edit_name = $scope.items[i].name;
    edit_editor.getSession().setValue($scope.items[i].code);
  }

  $scope.save = function() {
    localStorage["json"] = editor.getText();
    localStorage["data"] = JSON.stringify($scope.items);
    localStorage["new_editor"] = JSON.stringify(new_editor.getSession().getValue());
    localStorage["is_horiz"] = JSON.stringify($scope.is_horiz);
  }

  $scope.hydrate = function() {
    if (localStorage["json"]) editor.setText(localStorage["json"]);
    if (localStorage["data"]) $scope.items = JSON.parse(localStorage["data"]);
    if (localStorage["new_editor"]) new_editor.getSession().setValue(JSON.parse(localStorage["new_editor"]));
    if (localStorage["is_horiz"]) $scope.is_horiz = JSON.parse(localStorage["new_editor"]);
  }

  $scope.moveUp = function(i) {
    $scope.items.move(i, i - 1);
    $scope.save();
  }
  $scope.moveDown = function(i) {
    $scope.items.move(i, i + 1);
    $scope.save();
  }
  $scope.delete = function(i) {
    $scope.items.splice(i, 1);
    $scope.save();
  }

  $scope.switchToAdd = function() {
    $scope.data.edit_name = "";
    edit_editor.getSession().setValue("");
    $scope.editing = false;
  }

  $scope.add = function(type) {
    if ($scope.editing) {
      if ($scope.data.edit_name.length == 0) {
        alert("Name this operation!");
        return;
      }

      $scope.items[$scope.editing_index] = {
        "type": type,
        "name": $scope.data.edit_name,
        "code": edit_editor.getSession().getValue()
      };

      return;
    }

    if ($scope.data.name.length == 0) {
      alert("Name this operation!");
      return;
    }

    $scope.items.push({
      "type": type,
      "name": $scope.data.name,
      "code": new_editor.getSession().getValue()
    });

    $scope.data.name = "";
    new_editor.getSession().setValue("function (object) {\n  return object;\n}");

    $scope.save();
  }

  $scope.run = function() {
    if ($scope.items.length == 0) {
      return;
    }

    var nj = editor.get();
    var j = JSON.parse(JSON.stringify(nj));

    $scope.items.forEach(function(v) {
      try {
        j = j[v.type].call(j, eval("(" + v.code + ")"));
      } catch (e) {
        alert("Error in " + v.name + "\n\n" + e);
      }
    });

    editor2.set(j);
    editor2.expandAll();
  }

  $scope.hydrate();
  $scope.run();

  setInterval(function() {
    $scope.save();
    window.dispatchEvent(new Event('resize'));
  }, 1000);
}

var json = [{
  "SourceFile": "1993 Jams mix/ph_jams93_000.mp3",
  "Title": "Bowie - 1993-02-03 Portland, ME",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:07:22 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "6.8 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_001.mp3",
  "Title": "Tweezer - 1993-02-03 Portland, ME",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:06:13 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "5.7 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_002.mp3",
  "Title": "YEM - 1993-02-03 Portland, ME",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:06:11 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "5.7 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_003.mp3",
  "Title": "Possum - 1993-02-03 Portland, ME",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:05:36 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "5.1 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_004.mp3",
  "Title": "Stash - 1993-02-04 Providence",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:06:08 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "5.6 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_005.mp3",
  "Title": "Antelope - 1993-02-04 Providence",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:04:48 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "4.4 MB"
}];

var editor = new JSONEditor(container, options, json);
editor.setMode('code');
var editor2 = new JSONEditor(container2, {
  modes: ['code', 'text', 'view'],
  editable: function() {
    return false;
  }
}, json);

editor2.expandAll();<commit_msg>fix demo<commit_after>Array.prototype.move = function(old_index, new_index) {
  if (new_index >= this.length) {
    var k = new_index - this.length;
    while ((k--) + 1) {
      this.push(undefined);
    }
  }
  this.splice(new_index, 0, this.splice(old_index, 1)[0]);
  return this; // for testing purposes
};

var container = document.getElementById('jsoneditor');
var container2 = document.getElementById('jsoneditor2');

var options = {
  mode: 'tree',
  modes: ['code', 'form', 'text', 'tree', 'view'], // allowed modes
  error: function(err) {
    alert(err.toString());
  }
};

new_editor = ace.edit("new-editor");
edit_editor = ace.edit("edit-editor");

function ctrler($scope) {
  $scope.items = [
    {
      "type": "filter",
      "name": "Songs named Possum",
      "code": "function (object) {\n  return object.Title.indexOf('Possum') === 0;\n}\n"
    }
  ];

  $scope.data = {};
  $scope.data.name = "";
  $scope.data.edit_name = "";
  $scope.editing = false;
  $scope.editing_index = -1;
  $scope.is_horiz = true;

  $scope.edit = function(i) {
    $scope.editing = true;
    $scope.editing_index = i;
    $scope.data.edit_name = $scope.items[i].name;
    edit_editor.getSession().setValue($scope.items[i].code);
  }

  $scope.save = function() {
    localStorage["json"] = editor.getText();
    localStorage["data"] = JSON.stringify($scope.items);
    localStorage["new_editor"] = JSON.stringify(new_editor.getSession().getValue());
    localStorage["is_horiz"] = JSON.stringify($scope.is_horiz);
  }

  $scope.hydrate = function() {
    if (localStorage["json"]) editor.setText(localStorage["json"]);
    if (localStorage["data"] && localStorage["data"].length > 0) $scope.items = JSON.parse(localStorage["data"]);
    if (localStorage["new_editor"]) new_editor.getSession().setValue(JSON.parse(localStorage["new_editor"]));
    if (localStorage["is_horiz"]) $scope.is_horiz = JSON.parse(localStorage["new_editor"]);
  }

  $scope.moveUp = function(i) {
    $scope.items.move(i, i - 1);
    $scope.save();
  }
  $scope.moveDown = function(i) {
    $scope.items.move(i, i + 1);
    $scope.save();
  }
  $scope.delete = function(i) {
    $scope.items.splice(i, 1);
    $scope.save();
  }

  $scope.switchToAdd = function() {
    $scope.data.edit_name = "";
    edit_editor.getSession().setValue("");
    $scope.editing = false;
  }

  $scope.add = function(type) {
    if ($scope.editing) {
      if ($scope.data.edit_name.length == 0) {
        alert("Name this operation!");
        return;
      }

      $scope.items[$scope.editing_index] = {
        "type": type,
        "name": $scope.data.edit_name,
        "code": edit_editor.getSession().getValue()
      };

      return;
    }

    if ($scope.data.name.length == 0) {
      alert("Name this operation!");
      return;
    }

    $scope.items.push({
      "type": type,
      "name": $scope.data.name,
      "code": new_editor.getSession().getValue()
    });

    $scope.data.name = "";
    new_editor.getSession().setValue("function (object) {\n  return object;\n}");

    $scope.save();
  }

  $scope.run = function() {
    if ($scope.items.length == 0) {
      return;
    }

    var nj = editor.get();
    var j = JSON.parse(JSON.stringify(nj));

    $scope.items.forEach(function(v) {
      try {
        j = j[v.type].call(j, eval("(" + v.code + ")"));
      } catch (e) {
        alert("Error in " + v.name + "\n\n" + e);
      }
    });

    editor2.set(j);
    editor2.expandAll();
  }

  $scope.hydrate();
  $scope.run();

  setInterval(function() {
    $scope.save();
    window.dispatchEvent(new Event('resize'));
  }, 1000);
}

var json = [{
  "SourceFile": "1993 Jams mix/ph_jams93_000.mp3",
  "Title": "Bowie - 1993-02-03 Portland, ME",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:07:22 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "6.8 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_001.mp3",
  "Title": "Tweezer - 1993-02-03 Portland, ME",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:06:13 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "5.7 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_002.mp3",
  "Title": "YEM - 1993-02-03 Portland, ME",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:06:11 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "5.7 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_003.mp3",
  "Title": "Possum - 1993-02-03 Portland, ME",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:05:36 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "5.1 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_004.mp3",
  "Title": "Stash - 1993-02-04 Providence",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:06:08 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "5.6 MB"
}, {
  "SourceFile": "1993 Jams mix/ph_jams93_005.mp3",
  "Title": "Antelope - 1993-02-04 Providence",
  "Album": "Phish Just Jams 1993",
  "Artist": "Phish",
  "Duration": "0:04:48 (approx)",
  "AudioBitrate": "128 kbps",
  "FileSize": "4.4 MB"
}];

var editor = new JSONEditor(container, options, json);
editor.setMode('code');
var editor2 = new JSONEditor(container2, {
  modes: ['code', 'text', 'view'],
  editable: function() {
    return false;
  }
}, json);

editor2.expandAll();<|endoftext|>


<commit_before>var express = require('express'),
	app = express(),
	http = require('http'),
	server = http.createServer(app),
	path = require('path'),
	helmet = require('helmet'),
	jobHandler = require('./jobHandler'),
	io = require('socket.io').listen(server)

app.configure(function(){
	app.set('port', process.env.PORT || 3000)
	app.set('views', __dirname + '/views')
	app.set('view engine', 'jade')
	app.use(express.favicon())
	app.use(express.logger('dev'))
	app.use(helmet.xframe())
	app.use(helmet.iexss())
	app.use(helmet.contentTypeOptions())
	app.use(helmet.cacheControl())
	app.use(express.bodyParser())
	app.use(express.methodOverride())
	app.use(express.cookieParser())
	app.use(express.session({
		secret: "notagoodsecret",
		cookie: {httpOnly: true, secure: true},
	}))
	app.use(express.csrf())

	app.use(function (req, res, next) {
		res.locals.csrftoken = req.session._csrf
		next()
	})

	app.use(app.router)
	app.use(express.static(path.join(__dirname, 'public')))
})

app.configure('development', function(){
	app.use(express.errorHandler())
})

app.get('/', function(req, res) {
	res.render('index',
		{ title: 'Jobs',
			jobArray: jobHandler.jobs
		}
	)
})

app.get('/detail/:id', function( req, res ) {
	if( req.params.id >= jobHandler.jobs.length ) {
		res.redirect('/')
	} else {
		res.render( 'detail', { title: "Job's details", job: jobHandler.jobs[ req.params.id ] } )
	}
})

app.get('/update', function( req, res ) {
	jobHandler.updateJobs()
	res.redirect('/')
})

process.on('uncaughtException', function(err) {
  console.error(err.stack);
})

jobHandler.setCallback( broadcastNews )
jobHandler.updateJobs()

server.listen(app.get('port'), function(){
	console.log("Express server listening on port " + app.get('port'))
	//process.setuid(config.uid)
	//process.setgid(config.gid)
})

function broadcastNews( data ) {
	io.sockets.emit( 'news', data )
}
<commit_msg>Reduce logging Adhere to JSHints, add semi-colons<commit_after>var express = require('express'),
	app = express(),
	http = require('http'),
	server = http.createServer(app),
	path = require('path'),
	helmet = require('helmet'),
	jobHandler = require('./jobHandler'),
	io = require('socket.io').listen(server);

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	app.use(express.logger());
	app.use(helmet.xframe());
	app.use(helmet.iexss());
	app.use(helmet.contentTypeOptions());
	app.use(helmet.cacheControl());
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.session({
		secret: "notagoodsecret",
		cookie: {httpOnly: true, secure: true}
	}));
	app.use(express.csrf());

	app.use(function (req, res, next) {
		res.locals.csrftoken = req.session._csrf;
		next();
	});

	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('production', function(){
	app.use(express.errorHandler());
});

app.get('/', function(req, res) {
	res.render('index',
		{ title: 'Jobs',
			jobArray: jobHandler.jobs
		}
	);
});

app.get('/detail/:id', function( req, res ) {
	if( req.params.id >= jobHandler.jobs.length ) {
		res.redirect('/');
	} else {
		res.render( 'detail', { title: "Job's details", job: jobHandler.jobs[ req.params.id ] } );
	}
});

app.get('/update', function( req, res ) {
	jobHandler.updateJobs();
	res.redirect('/');
});

process.on('uncaughtException', function(err) {
  console.error(err.stack);
});

jobHandler.setCallback( broadcastNews );
jobHandler.updateJobs();

server.listen(app.get('port'), function(){
	console.log("Express server listening on port " + app.get('port'));
	io.set('log level', 1); // reduce logging
	//process.setuid(config.uid)
	//process.setgid(config.gid)
});

function broadcastNews( data ) {
	io.sockets.emit( 'news', data );
}
<|endoftext|>


<commit_before>/* Links that are essential :
 * 1. For prev page = http://www.engadget.com/page/n-1/
 * 2. For curr page = http://www.engadget.com/
 * 3. Example of the url : http://www.engadget.com/2015/06/04/apple-watch-reader-review-roundup/
 */
var e = require('express')
var c = require('cheerio')
var fs = require('fs')
var req = require('request')
var post = require('request')
var store = new Array();
var app = e();
var router = e.Router();
var port = process.env.PORT || 8100;

app.use(e.static('assets'));

console.log("Express Serving is starting")
console.log("Starting Scraping")

router.get('/', function(req, res) {
        var data = fs.readFileSync('index.html', 'utf8');
        res.send(data.toString());
});

app.use('/', router);
app.listen(port, function() {
        console.log("Listening on port " + port);
});

req('http://www.engadget.com/', function(err, res, html) {
                if(!err && res.statusCode == 200) {
                        var l = c.load(html);

                        // Gives all the headlines together
                        l('header.post-header').each(function(i, element) {
                                var content = l(this).children().children().children('.h2');
                                var data = content.text();
                               // console.log(data);
                                store.push(data);
                                console.log(store);
                        });

                        // Gives the top 5 current posts on the page
                        l('div').attr('id','carousel').each(function(i, element) {
                                var content = l(this).children().children('.always');
                                console.log(content.text());
                        });

                        // Gives the top 2 current posts on the page
                        l('li.top2').each(function(i, element) {
                                var content = l(this);
                                console.log(content.text());
                       });

                        // Gives the last current post on the page
                        l('li.last').each(function(i, element) {
                                var content = l(this);
                                console.log(content.text());
                       });
                }
                });

post('http://localhost:8100/', function(err, res, html) {
        if(!err && res.statusCode == 200) {
                var p = c.load(html);
                p('h3.panel-title').each(function(i, element) {
                        var content = p(this);
                        console.log(content.text());
                });
        }
});

<commit_msg>added to branch test-app<commit_after>/* Links that are essential :
 * 1. For prev page = http://www.engadget.com/page/n-1/
 * 2. For curr page = http://www.engadget.com/
 * 3. Example of the url : http://www.engadget.com/2015/06/04/apple-watch-reader-review-roundup/
 */
var e = require('express')
var c = require('cheerio')
var fs = require('fs')
var req = require('request')
var post = require('request')
var store = new Array();
var app = e();
var router = e.Router();
var port = process.env.PORT || 8100;

app.use(e.static('assets'));

console.log("Express Serving is starting")
console.log("Starting Scraping")

router.get('/', function(req, res) {
        var data = fs.readFileSync('index.html', 'utf8');
        res.send(data.toString());
});

app.use('/', router);
app.listen(port, function() {
        console.log("Listening on port " + port);
});

req('http://www.engadget.com/', function(err, res, html) {
                if(!err && res.statusCode == 200) {
                        var l = c.load(html);

                        // Gives all the headlines together
                        l('header.post-header').each(function(i, element) {
                                var content = l(this).children().children().children('.h2');
                                var data = content.text();
                                console.log(data);
                                store.push(data);
                               // console.log(store);
                        });
                        /*
                        // Gives the top 5 current posts on the page
                        l('div').attr('id','carousel').each(function(i, element) {
                                var content = l(this).children().children('.always');
                                console.log(content.text());
                        });

                        // Gives the top 2 current posts on the page
                        l('li.top2').each(function(i, element) {
                                var content = l(this);
                                console.log(content.text());
                       });

                        // Gives the last current post on the page
                        l('li.last').each(function(i, element) {
                                var content = l(this);
                                console.log(content.text());
                       });*/
                }
                });

post('http://localhost:8100/', function(err, res, html) {
        if(!err && res.statusCode == 200) {
                var p = c.load(html);
                p('h3.panel-title').each(function(i, element) {
                        var content = p(this);
                        console.log(content.text());
                });
        }
});

<|endoftext|>


<commit_before>
window.onload = function() {

    var keyboard = document.getElementById("keyboard");
    keyboard.style.borderRadius = "3px";

    var monitor = document.getElementById("screen");
    var beacon = "Hello world";
    var beaconLink = beacon.link("http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_str_link");
    var myProjects = [
        "i am a program deployed with the goal of telling future prospects about university life ",
        "at some point in time i was written by a student studying applied software engineering at cardiff university ",
        "his name was christopher but that doesnt matter for now ",
        "he wrote me using the skills learnt from his course to speak on his behalf about his experiences at university after one year ",
        "at the national software academy students are being taught what it means to write software in the twenty first century ",
        "they learn to write software as individuals but more importantly in teams ",
        "what my master likes most about software engineering is the ability to always change and update your creations in a costless manner ",
        "he believes this grants you a freedom not many other disciplines do ",
        "if any ",
        "theres a society for everyone at cardiff university ",
        "my master enjoyed the circus and photography societies during his time ",
        "his advice is you get involved in a couple and meet some like minded people ",
        "butttttttt ",
        "dont over do it ",
        "take your first steps towards a life changing journey as my master did ",
        "the ucas code issssss ",
        "four ",
        "j ",
        "v ",
        "d ",
        "did you get that ",
        "if not slow down the typing speed so you can read it ",
        "good luck user ",
        "relaying message ",
    ];

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

    var i = 0;
    var letterSpace = 0;
    var linkIndex = 0;
    var siteLinks;

    var spawn;

    var row1 = document.createElement("div");
    row1.classList.add('row1');
    var row2 = document.createElement("div");
    row2.classList.add('row2');
    var row3 = document.createElement("div");
    row3.classList.add('row3');
    var row4 = document.createElement("div");
    row4.classList.add('row4');

    var keyboardSlider = document.getElementById("typingSpeed");

    var keyNodes = [];

    while (i <= 26) {

        i++;
        //spawn creates each key and add's on event listener and styling ref.

        spawn = document.createElement("div");
        //spawn.onclick = expand.bind(this, (i-1));
        spawn.classList.add('spawn');
        keyNodes.push(spawn);

        if (i < 11) {
            //create and append spawns to row 1.
            row1.appendChild(spawn);
            keyboard.appendChild(row1);
            spawn.innerHTML = alphabet[i - 1].toUpperCase();

        } else if (i < 20) {
            //create and append spawns to row 2.
            row2.appendChild(spawn);
            keyboard.appendChild(row2);
            spawn.innerHTML = alphabet[i - 1].toUpperCase();

        } else if (i < 27) {
            //create and append spawns to row 3.
            row3.appendChild(spawn);
            keyboard.appendChild(row3);
            spawn.innerHTML = alphabet[i - 1].toUpperCase();
        }
        else {
            //create and appends the spacebar.
            row4.appendChild(spawn);
            keyboard.appendChild(row4);
            spawn.style.width = "150px";
            spawn.innerHTML = alphabet[i - 1].toUpperCase();
        }
    }

    document.body.addEventListener("onload", textRoll(beacon));

    function textRoll(texToRoll) {

        var humanTyping = 50; // 105 is optimal starting speed

        var work = function(){

            clearTimeout(anim1);
            message(texToRoll);
            console.log("func ran");
            anim1 = setTimeout(work, keyboardSlider.value);

        }

        var anim1 = setTimeout(work, keyboardSlider.value);

        function message(screenText) {
            // dynamically alter typing speed for realistic human effect at each interval.
            // humanTyping = Math.round(Math.random() * 500);
            console.log(humanTyping);
            console.log(keyboardSlider.value);
            console.log("message function started and iterating");

            letterSpace++;
            keyPress(screenText.substring(letterSpace - 1, letterSpace));

            var character = document.createElement("p");

            character.innerHTML = screenText.substring(letterSpace - 1, letterSpace).link("http://eloquentjavascript.net/");//.toUpperCase();
            //character.link("http://eloquentjavascript.net/");
            monitor.appendChild(character);
            character.classList.add('characters');

            // console.log(letterSpace);
            // console.log(screenText.length);

            if (letterSpace === screenText.length) {
                //clearTimeout(anim1);
                console.log(anim1);
                letterSpace = 0;
                //rewind("bye bye");

                siteLinks = true;

                console.log("looping through array index" + i);

                switch (linkIndex) {
                    case 0:
                        rewind(myProjects[linkIndex]); //message to be rolled out after the text is deleted. beacon string or?
                        break;
                    case 1:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 2:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 3:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 4:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 5:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 6:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 7:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 8:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 9:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 10:
                        rewind(myProjects[linkIndex]);
                        break;
                    default:
                        rewind(myProjects[linkIndex]);
                        siteLinks = false;
                        // clearInterval(anim1);
                        break;
                }

                if (siteLinks === true) {
                    linkIndex++;
                }else{
                    linkIndex = 0;
                }
                console.log("message function scanned and cleared");
            }
        }

    }; //end of textRoll

// side effects of func keyPress
    var prevLetterPos;
    var toggleOff = false;

    function keyPress(key) {
        // soundEffect..
        var soundEffect = new Audio("keyboard_key.mp3");
        // if(toggleOff) soundEffect.pause();
        soundEffect.play();
        var letterPos = alphabet.indexOf(key.toLowerCase());
        //console.log(key);
        //console.log(letterPos);

        if (toggleOff) {
            keyNodes[prevLetterPos].classList.remove("keypress");
        }
        keyNodes[letterPos].classList.add("keypress");
        prevLetterPos = letterPos;
        if (!toggleOff)
            toggleOff = true;
    }

    function rewind(response) {
        //remove children/letters from the computer monitor.
        var letterSpace = monitor.children.length;
        //alert(letterSpace);

        var calls = function () {
            clearTimeout(anim2);
            message();
            anim2 = setTimeout(calls, 30);
        }

        var anim2 = setTimeout(calls, 30);

        function message() {
            letterSpace--;

            monitor.removeChild(monitor.childNodes[letterSpace + 5]);
            //monitor.childNodes[letterSpace].style.borderBottom = "2px solid #00ff00";

            if (letterSpace === 0) {
                // clearInterval(anim2);
                //console.log(beacon);
                textRoll(response);  //beacon
            }
        };
    };
}<commit_msg>stopped the message function from recursively repeating itself by moving the control flow inside it's setTimeout function<commit_after>
window.onload = function() {

    var keyboard = document.getElementById("keyboard");
    keyboard.style.borderRadius = "3px";

    var monitor = document.getElementById("screen");
    var beacon = "Hello world";
    var beaconLink = beacon.link("http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_str_link");
    var myProjects = [
        "i am a program deployed with the goal of telling future prospects about university life ",
        "at some point in time i was written by a student studying applied software engineering at cardiff university ",
        "his name was christopher but that doesnt matter for now ",
        "he wrote me using the skills learnt from his course to speak on his behalf about his experiences at university after one year ",
        "at the national software academy students are being taught what it means to write software in the twenty first century ",
        "they learn to write software as individuals but more importantly in teams ",
        "what my master likes most about software engineering is the ability to always change and update your creations in a costless manner ",
        "he believes this grants you a freedom not many other disciplines do ",
        "if any ",
        "theres a society for everyone at cardiff university ",
        "my master enjoyed the circus and photography societies during his time ",
        "his advice is you get involved in a couple and meet some like minded people ",
        "butttttttt ",
        "dont over do it ",
        "take your first steps towards a life changing journey as my master did ",
        "the ucas code issssss ",
        "four ",
        "j ",
        "v ",
        "d ",
        "did you get that ",
        "if not slow down the typing speed so you can read it ",
        "good luck user ",
        "relaying message ",
    ];

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

    var i = 0;
    var letterSpace = 0;
    var linkIndex = 0;
    var siteLinks;

    var spawn;

    var row1 = document.createElement("div");
    row1.classList.add('row1');
    var row2 = document.createElement("div");
    row2.classList.add('row2');
    var row3 = document.createElement("div");
    row3.classList.add('row3');
    var row4 = document.createElement("div");
    row4.classList.add('row4');

    var keyboardSlider = document.getElementById("typingSpeed");

    var keyNodes = [];

    while (i <= 26) {

        i++;
        //spawn creates each key and add's on event listener and styling ref.

        spawn = document.createElement("div");
        //spawn.onclick = expand.bind(this, (i-1));
        spawn.classList.add('spawn');
        keyNodes.push(spawn);

        if (i < 11) {
            //create and append spawns to row 1.
            row1.appendChild(spawn);
            keyboard.appendChild(row1);
            spawn.innerHTML = alphabet[i - 1].toUpperCase();

        } else if (i < 20) {
            //create and append spawns to row 2.
            row2.appendChild(spawn);
            keyboard.appendChild(row2);
            spawn.innerHTML = alphabet[i - 1].toUpperCase();

        } else if (i < 27) {
            //create and append spawns to row 3.
            row3.appendChild(spawn);
            keyboard.appendChild(row3);
            spawn.innerHTML = alphabet[i - 1].toUpperCase();
        }
        else {
            //create and appends the spacebar.
            row4.appendChild(spawn);
            keyboard.appendChild(row4);
            spawn.style.width = "150px";
            spawn.innerHTML = alphabet[i - 1].toUpperCase();
        }
    }

    document.body.addEventListener("onload", textRoll(myProjects[0]));

    function textRoll(texToRoll) {

        var humanTyping = 50; // 105 is optimal starting speed

        var work = function(){

            clearTimeout(anim1);
            console.log("func ran");
            anim1 = setTimeout(work, keyboardSlider.value);
            message(texToRoll);

        }

        var anim1 = setTimeout(work, keyboardSlider.value);

        function message(screenText) {
            // dynamically alter typing speed for realistic human effect at each interval.

            letterSpace++;
            keyPress(screenText.substring(letterSpace - 1, letterSpace));

            var character = document.createElement("p");

            character.innerHTML = screenText.substring(letterSpace - 1, letterSpace).link("http://eloquentjavascript.net/");//.toUpperCase();
            //character.link("http://eloquentjavascript.net/");
            monitor.appendChild(character);
            character.classList.add('characters');

            // console.log(letterSpace);
            // console.log(screenText.length);

            if (letterSpace === screenText.length) {
                alert('freeze and clear');
                clearTimeout(anim1);
                console.log(anim1);
                console.log("WAITING FOR REWIND TO BE POPPED OFF STACK");
                letterSpace = 0;
                //rewind("bye bye");

                siteLinks = true;

                console.log("looping through array index" + i);

                if (siteLinks === true) {
                    linkIndex++;
                }else{
                    linkIndex = 0;
                }

                switch (linkIndex) {
                    case 0:
                        console.log("rewinding..");
                        rewind(); //message to be rolled out after the text is deleted. beacon string or?
                        // recursive
                        console.log("RUNNING MESSAGE");
                        // could be a delay of x time before calling. as setTimeout is asynchronous and non-blocking
                        // var delay = rewind();
                        // window.setTimeout(function(){textRoll(text)}, delay);
                        textRoll(myProjects[linkIndex]);
                        break;
                    case 1:
                        rewind();
                        console.log("rewinding?");
                        textRoll(myProjects[linkIndex]);
                        break;
                    case 2:
                        rewind();
                        message(myProjects[linkIndex]);
                        break;
                    case 3:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 4:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 5:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 6:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 7:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 8:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 9:
                        rewind(myProjects[linkIndex]);
                        break;
                    case 10:
                        rewind(myProjects[linkIndex]);
                        break;
                    default:
                        rewind(myProjects[linkIndex]);
                        siteLinks = false;
                        // clearInterval(anim1);
                        break;
                }
                console.log("message function scanned and cleared");
            }
        }

    }; //end of textRoll

// side effects of func keyPress
    var prevLetterPos;
    var toggleOff = false;

    function keyPress(key) {
        // soundEffect..
        var soundEffect = new Audio("keyboard_key.mp3");
        // if(toggleOff) soundEffect.pause();
        soundEffect.play();
        var letterPos = alphabet.indexOf(key.toLowerCase());
        //console.log(key);
        //console.log(letterPos);

        if (toggleOff) {
            keyNodes[prevLetterPos].classList.remove("keypress");
        }
        keyNodes[letterPos].classList.add("keypress");
        prevLetterPos = letterPos;
        if (!toggleOff)
            toggleOff = true;
    }

    function rewind(response) {
        //remove children/letters from the computer monitor.
        var letterSpace = monitor.children.length;
        //alert(letterSpace);

        var calls = function () {
            clearTimeout(anim2);
            anim2 = setTimeout(calls, 30);
            message();
        }

        var anim2 = setTimeout(calls, 30);

        function message() {
            letterSpace--;
            monitor.removeChild(monitor.childNodes[letterSpace]);

            if (letterSpace === 0) {
                clearInterval(anim2);
                console.log("CLEARED");
            }
        }
        console.log("but wait");
        // return letterSpace * 30;
    }
}<|endoftext|>


<commit_before>// Globals
var newTaskInput = document.getElementById('new-task'),
    addButton = document.getElementsByTagName('button')[0],
    incompleteTaskHolder = document.getElementById('incomplete-tasks'),
    completedTaskHolder = document.getElementById('completed-tasks');

// creates new task list element
var newTaskElement = function(taskString) {
  // Creats a list task item
  var listItem = document.createElement('li'),
      checkbox = document.createElement('input'),
      label = document.createElement('label'),
      editInput = document.createElement('input'),
      editButton = document.createElement('button'),
      deleteButton = document.createElement('button');

  // Modifiers
  // modify input elemnts type porperty
  checkbox.type = 'checkbox';
  editInput.type = 'text';

  // modify button text and class property
  editButton.innerText = 'Edit';
  editButton.className = 'edit';
  deleteButton.innerText = 'Delete';
  deleteButton.className = 'delete';

  // modify label text with the taskString
  label.innerText = taskString;

  // appending elements
  listItem.appendChild(checkbox);
  listItem.appendChild(label);
  listItem.appendChild(editInput);
  listItem.appendChild(editButton);
  listItem.appendChild(deleteButton);

  return listItem;
};

var addTask = function() {
  console.log('adding');

  // calls newTaskElement() to create a new task
  // gets the value of newTaskInput
  var listItem = newTaskElement(newTaskInput.value);

  // appending to incompleteTaskHolder
  incompleteTaskHolder.appendChild(listItem);

  // will set the listItem to be completed when checked
  bindTaskEvents(listItem, completedTask);
};

var editTask = function() {
  console.log('editing');

  // stores the parent li
  var listItem = this.parentNode,
      editInput = listItem.querySelector('input[type=text]'),
      label = listItem.querySelector('label'),
      containsClass = listItem.classList.contains('editMode');
  // if parent li class is 'editMode'
  if (containsClass) {
    // switch from edit mode
    label.innerText = editInput.value;
  } else {
    // switch to edit mode
    editInput.value = label.innerText;
  }

  listItem.classList.toggle('editMode');
};

var deleteTask = function() {
  console.log('deleting');

  // stores the parent li
  var listItem = this.parentNode,
      ul = listItem.parentNode;

  ul.removeChild(listItem);
};

var completedTask = function() {
  console.log('completeing tasks');

  // appends list Item to #completed-tasks
  var listItem = this.parentNode;
  completedTaskHolder.appendChild(listItem);
  // will set the listItem to be incomplete when checked
  bindTaskEvents(listItem, incompleteTask);
};

var incompleteTask = function() {
  console.log("tasks still incomplete");

  // appends list Item to #incomplete-tasks
  var listItem = this.parentNode;
  incompleteTaskHolder.appendChild(listItem);
  // will set the listItem to be completed when checked
  bindTaskEvents(listItem, completedTask);
};

var bindTaskEvents = function(taskListItem, checkBoxEventHandler) {
  var checkBox = taskListItem.querySelector('input[type=checkbox]'),
      editButton = taskListItem.querySelector('Button.edit'),
      deleteButton = taskListItem.querySelector('button.delete');

  // Sets onclick handlers
  editButton.onclick = editTask;
  deleteButton.onclick = deleteTask;
  checkBox.onchange = checkBoxEventHandler;
  console.log('Binding');
};

// Sets click handler to tasks()'s
addButton.onclick = addTask;

// iterates through all the incomplete list items
for (var i = 0; i < incompleteTaskHolder.children.length; i++) {
  // stores child list item in var
  var listItem = incompleteTaskHolder.children[i];
  // binds events to completedTasks()
  bindTaskEvents(listItem, completedTask);
}

// iterates through all the completed list items
for (var i = 0; i < completedTaskHolder.children.length; i++) {
  // stores child list item in var
  var listItem = completedTaskHolder.children[i];
  // binds events to incompletedTasks()
  bindTaskEvents(listItem, incompleteTask);
}
<commit_msg>now clears new input after submit<commit_after>// Globals
var newTaskInput = document.getElementById('new-task'),
    addButton = document.getElementsByTagName('button')[0],
    incompleteTaskHolder = document.getElementById('incomplete-tasks'),
    completedTaskHolder = document.getElementById('completed-tasks');

// creates new task list element
var newTaskElement = function(taskString) {
  // Creats a list task item
  var listItem = document.createElement('li'),
      checkbox = document.createElement('input'),
      label = document.createElement('label'),
      editInput = document.createElement('input'),
      editButton = document.createElement('button'),
      deleteButton = document.createElement('button');

  // Modifiers
  // modify input elemnts type porperty
  checkbox.type = 'checkbox';
  editInput.type = 'text';

  // modify button text and class property
  editButton.innerText = 'Edit';
  editButton.className = 'edit';
  deleteButton.innerText = 'Delete';
  deleteButton.className = 'delete';

  // modify label text with the taskString
  label.innerText = taskString;

  // appending elements
  listItem.appendChild(checkbox);
  listItem.appendChild(label);
  listItem.appendChild(editInput);
  listItem.appendChild(editButton);
  listItem.appendChild(deleteButton);

  return listItem;
};

var addTask = function() {
  console.log('adding');

  // calls newTaskElement() to create a new task
  // gets the value of newTaskInput
  var listItem = newTaskElement(newTaskInput.value);

  // appending to incompleteTaskHolder
  incompleteTaskHolder.appendChild(listItem);

  // will set the listItem to be completed when checked
  bindTaskEvents(listItem, completedTask);

  // sets the value back to an empty string
  newTaskInput.value = '';
};

var editTask = function() {
  console.log('editing');

  // stores the parent li
  var listItem = this.parentNode,
      editInput = listItem.querySelector('input[type=text]'),
      label = listItem.querySelector('label'),
      containsClass = listItem.classList.contains('editMode');
  // if parent li class is 'editMode'
  if (containsClass) {
    // switch from edit mode
    label.innerText = editInput.value;
  } else {
    // switch to edit mode
    editInput.value = label.innerText;
  }

  listItem.classList.toggle('editMode');
};

var deleteTask = function() {
  console.log('deleting');

  // stores the parent li
  var listItem = this.parentNode,
      ul = listItem.parentNode;

  ul.removeChild(listItem);
};

var completedTask = function() {
  console.log('completeing tasks');

  // appends list Item to #completed-tasks
  var listItem = this.parentNode;
  completedTaskHolder.appendChild(listItem);
  // will set the listItem to be incomplete when checked
  bindTaskEvents(listItem, incompleteTask);
};

var incompleteTask = function() {
  console.log("tasks still incomplete");

  // appends list Item to #incomplete-tasks
  var listItem = this.parentNode;
  incompleteTaskHolder.appendChild(listItem);
  // will set the listItem to be completed when checked
  bindTaskEvents(listItem, completedTask);
};

var bindTaskEvents = function(taskListItem, checkBoxEventHandler) {
  var checkBox = taskListItem.querySelector('input[type=checkbox]'),
      editButton = taskListItem.querySelector('Button.edit'),
      deleteButton = taskListItem.querySelector('button.delete');

  // Sets onclick handlers
  editButton.onclick = editTask;
  deleteButton.onclick = deleteTask;
  checkBox.onchange = checkBoxEventHandler;
  console.log('Binding');
};

// Sets click handler to tasks()'s
addButton.onclick = addTask;

// iterates through all the incomplete list items
for (var i = 0; i < incompleteTaskHolder.children.length; i++) {
  // stores child list item in var
  var listItem = incompleteTaskHolder.children[i];
  // binds events to completedTasks()
  bindTaskEvents(listItem, completedTask);
}

// iterates through all the completed list items
for (var i = 0; i < completedTaskHolder.children.length; i++) {
  // stores child list item in var
  var listItem = completedTaskHolder.children[i];
  // binds events to incompletedTasks()
  bindTaskEvents(listItem, incompleteTask);
}
<|endoftext|>


<commit_before>const {assert} = require('chai');
let Parser, JavaScript;

describe("Query", () => {
  let parser, tree, query;

  before(async () =>
    ({Parser, JavaScript} = await require('./helper'))
  );

  beforeEach(() => {
    parser = new Parser().setLanguage(JavaScript);
  });

  afterEach(() => {
    parser.delete();
    if (tree) tree.delete();
    if (query) query.delete();
  });

  describe('construction', () => {
    it('throws an error on invalid patterns', () => {
      assert.throws(() => {
        JavaScript.query("(function_declaration wat)")
      }, "Bad syntax at offset 22: \'wat)\'...");
      assert.throws(() => {
        JavaScript.query("(non_existent)")
      }, "Bad node name 'non_existent'");
      assert.throws(() => {
        JavaScript.query("(a)")
      }, "Bad node name 'a'");
      assert.throws(() => {
        JavaScript.query("(function_declaration non_existent:(identifier))")
      }, "Bad field name 'non_existent'");
    });

    it('throws an error on invalid predicates',  () => {
      assert.throws(() => {
        JavaScript.query("((identifier) @abc (eq? @ab hi))")
      }, "Bad capture name @ab");
      assert.throws(() => {
        JavaScript.query("((identifier) @abc (eq? @ab hi))")
      }, "Bad capture name @ab");
      assert.throws(() => {
        JavaScript.query("((identifier) @abc (eq?))")
      }, "Wrong number of arguments to `eq?` predicate. Expected 2, got 0");
      assert.throws(() => {
        JavaScript.query("((identifier) @a (eq? @a @a @a))")
      }, "Wrong number of arguments to `eq?` predicate. Expected 2, got 3");
      assert.throws(() => {
        JavaScript.query("((identifier) @a (something-else? @a))")
      }, "Unknown query predicate `something-else?`");
    });
  });

  describe('.matches', () => {
    it('returns all of the matches for the given query',  () => {
      tree = parser.parse("function one() { two(); function three() {} }");
      query = JavaScript.query(`
        (function_declaration name:(identifier) @fn-def)
        (call_expression function:(identifier) @fn-ref)
      `);
      const matches = query.matches(tree.rootNode);
      assert.deepEqual(
        formatMatches(matches),
        [
          {pattern: 0, captures: [{name: 'fn-def', text: 'one'}]},
          {pattern: 1, captures: [{name: 'fn-ref', text: 'two'}]},
          {pattern: 0, captures: [{name: 'fn-def', text: 'three'}]},
        ]
      );
    });

    it('can search in a specified ranges',  () => {
      tree = parser.parse("[a, b,\nc, d,\ne, f,\ng, h]");
      query = JavaScript.query('(identifier) @element');
      const matches = query.matches(
        tree.rootNode,
        {row: 1, column: 1},
        {row: 3, column: 1}
      );
      assert.deepEqual(
        formatMatches(matches),
        [
          {pattern: 0, captures: [{name: 'element', text: 'd'}]},
          {pattern: 0, captures: [{name: 'element', text: 'e'}]},
          {pattern: 0, captures: [{name: 'element', text: 'f'}]},
          {pattern: 0, captures: [{name: 'element', text: 'g'}]},
        ]
      );
    });
  });

  describe('.captures', () => {
    it('returns all of the captures for the given query, in order', () => {
      tree = parser.parse(`
        a({
          bc: function de() {
            const fg = function hi() {}
          },
          jk: function lm() {
            const no = function pq() {}
          },
        });
      `);
      query = JavaScript.query(`
        (pair
          key: * @method.def
          (function
            name: (identifier) @method.alias))

        (variable_declarator
          name: * @function.def
          value: (function
            name: (identifier) @function.alias))

        ":" @delimiter
        "=" @operator
      `);

      const captures = query.captures(tree.rootNode);
      assert.deepEqual(
        formatCaptures(captures),
        [
          {name: "method.def", text: "bc"},
          {name: "delimiter", text: ":"},
          {name: "method.alias", text: "de"},
          {name: "function.def", text: "fg"},
          {name: "operator", text: "="},
          {name: "function.alias", text: "hi"},
          {name: "method.def", text: "jk"},
          {name: "delimiter", text: ":"},
          {name: "method.alias", text: "lm"},
          {name: "function.def", text: "no"},
          {name: "operator", text: "="},
          {name: "function.alias", text: "pq"},
        ]
      );
    });

    it('handles conditions that compare the text of capture to literal strings',  () => {
      tree = parser.parse(`
        const ab = require('./ab');
        new Cd(EF);
      `);

      query = JavaScript.query(`
        (identifier) @variable

        ((identifier) @function.builtin
         (eq? @function.builtin "require"))

        ((identifier) @constructor
         (match? @constructor "^[A-Z]"))

        ((identifier) @constant
         (match? @constant "^[A-Z]{2,}$"))
      `);

      const captures = query.captures(tree.rootNode);
      assert.deepEqual(
        formatCaptures(captures),
        [
          {name: "variable", text: "ab"},
          {name: "variable", text: "require"},
          {name: "function.builtin", text: "require"},
          {name: "variable", text: "Cd"},
          {name: "constructor", text: "Cd"},
          {name: "variable", text: "EF"},
          {name: "constructor", text: "EF"},
          {name: "constant", text: "EF"},
        ]
      );
    });

    it('handles conditions that compare the text of capture to each other',  () => {
      tree = parser.parse(`
        const ab = abc + 1;
        const def = de + 1;
        const ghi = ghi + 1;
      `);

      query = JavaScript.query(`
        ((variable_declarator
            name: (identifier) @id1
            value: (binary_expression
              left: (identifier) @id2))
         (eq? @id1 @id2))
      `);

      const captures = query.captures(tree.rootNode);
      assert.deepEqual(
        formatCaptures(captures),
        [
          {name: "id1", text: "ghi"},
          {name: "id2", text: "ghi"},
        ]
      );
    });
  });
});

function formatMatches(matches) {
  return matches.map(({pattern, captures}) => ({
    pattern,
    captures: formatCaptures(captures)
  }))
}

function formatCaptures(captures) {
  return captures.map(({name, node}) => ({ name, text: node.text }))
}
<commit_msg>Use a more realistic example in one JS query unit test<commit_after>const {assert} = require('chai');
let Parser, JavaScript;

describe("Query", () => {
  let parser, tree, query;

  before(async () =>
    ({Parser, JavaScript} = await require('./helper'))
  );

  beforeEach(() => {
    parser = new Parser().setLanguage(JavaScript);
  });

  afterEach(() => {
    parser.delete();
    if (tree) tree.delete();
    if (query) query.delete();
  });

  describe('construction', () => {
    it('throws an error on invalid patterns', () => {
      assert.throws(() => {
        JavaScript.query("(function_declaration wat)")
      }, "Bad syntax at offset 22: \'wat)\'...");
      assert.throws(() => {
        JavaScript.query("(non_existent)")
      }, "Bad node name 'non_existent'");
      assert.throws(() => {
        JavaScript.query("(a)")
      }, "Bad node name 'a'");
      assert.throws(() => {
        JavaScript.query("(function_declaration non_existent:(identifier))")
      }, "Bad field name 'non_existent'");
    });

    it('throws an error on invalid predicates',  () => {
      assert.throws(() => {
        JavaScript.query("((identifier) @abc (eq? @ab hi))")
      }, "Bad capture name @ab");
      assert.throws(() => {
        JavaScript.query("((identifier) @abc (eq? @ab hi))")
      }, "Bad capture name @ab");
      assert.throws(() => {
        JavaScript.query("((identifier) @abc (eq?))")
      }, "Wrong number of arguments to `eq?` predicate. Expected 2, got 0");
      assert.throws(() => {
        JavaScript.query("((identifier) @a (eq? @a @a @a))")
      }, "Wrong number of arguments to `eq?` predicate. Expected 2, got 3");
      assert.throws(() => {
        JavaScript.query("((identifier) @a (something-else? @a))")
      }, "Unknown query predicate `something-else?`");
    });
  });

  describe('.matches', () => {
    it('returns all of the matches for the given query',  () => {
      tree = parser.parse("function one() { two(); function three() {} }");
      query = JavaScript.query(`
        (function_declaration name:(identifier) @fn-def)
        (call_expression function:(identifier) @fn-ref)
      `);
      const matches = query.matches(tree.rootNode);
      assert.deepEqual(
        formatMatches(matches),
        [
          {pattern: 0, captures: [{name: 'fn-def', text: 'one'}]},
          {pattern: 1, captures: [{name: 'fn-ref', text: 'two'}]},
          {pattern: 0, captures: [{name: 'fn-def', text: 'three'}]},
        ]
      );
    });

    it('can search in a specified ranges',  () => {
      tree = parser.parse("[a, b,\nc, d,\ne, f,\ng, h]");
      query = JavaScript.query('(identifier) @element');
      const matches = query.matches(
        tree.rootNode,
        {row: 1, column: 1},
        {row: 3, column: 1}
      );
      assert.deepEqual(
        formatMatches(matches),
        [
          {pattern: 0, captures: [{name: 'element', text: 'd'}]},
          {pattern: 0, captures: [{name: 'element', text: 'e'}]},
          {pattern: 0, captures: [{name: 'element', text: 'f'}]},
          {pattern: 0, captures: [{name: 'element', text: 'g'}]},
        ]
      );
    });
  });

  describe('.captures', () => {
    it('returns all of the captures for the given query, in order', () => {
      tree = parser.parse(`
        a({
          bc: function de() {
            const fg = function hi() {}
          },
          jk: function lm() {
            const no = function pq() {}
          },
        });
      `);
      query = JavaScript.query(`
        (pair
          key: * @method.def
          (function
            name: (identifier) @method.alias))

        (variable_declarator
          name: * @function.def
          value: (function
            name: (identifier) @function.alias))

        ":" @delimiter
        "=" @operator
      `);

      const captures = query.captures(tree.rootNode);
      assert.deepEqual(
        formatCaptures(captures),
        [
          {name: "method.def", text: "bc"},
          {name: "delimiter", text: ":"},
          {name: "method.alias", text: "de"},
          {name: "function.def", text: "fg"},
          {name: "operator", text: "="},
          {name: "function.alias", text: "hi"},
          {name: "method.def", text: "jk"},
          {name: "delimiter", text: ":"},
          {name: "method.alias", text: "lm"},
          {name: "function.def", text: "no"},
          {name: "operator", text: "="},
          {name: "function.alias", text: "pq"},
        ]
      );
    });

    it('handles conditions that compare the text of capture to literal strings',  () => {
      tree = parser.parse(`
        const ab = require('./ab');
        new Cd(EF);
      `);

      query = JavaScript.query(`
        (identifier) @variable

        ((identifier) @function.builtin
         (eq? @function.builtin "require"))

        ((identifier) @constructor
         (match? @constructor "^[A-Z]"))

        ((identifier) @constant
         (match? @constant "^[A-Z]{2,}$"))
      `);

      const captures = query.captures(tree.rootNode);
      assert.deepEqual(
        formatCaptures(captures),
        [
          {name: "variable", text: "ab"},
          {name: "variable", text: "require"},
          {name: "function.builtin", text: "require"},
          {name: "variable", text: "Cd"},
          {name: "constructor", text: "Cd"},
          {name: "variable", text: "EF"},
          {name: "constructor", text: "EF"},
          {name: "constant", text: "EF"},
        ]
      );
    });

    it('handles conditions that compare the text of capture to each other',  () => {
      tree = parser.parse(`
        ab = abc + 1;
        def = de + 1;
        ghi = ghi + 1;
      `);

      query = JavaScript.query(`
        ((assignment_expression
            left: (identifier) @id1
            right: (binary_expression
              left: (identifier) @id2))
         (eq? @id1 @id2))
      `);

      const captures = query.captures(tree.rootNode);
      assert.deepEqual(
        formatCaptures(captures),
        [
          {name: "id1", text: "ghi"},
          {name: "id2", text: "ghi"},
        ]
      );
    });
  });
});

function formatMatches(matches) {
  return matches.map(({pattern, captures}) => ({
    pattern,
    captures: formatCaptures(captures)
  }))
}

function formatCaptures(captures) {
  return captures.map(({name, node}) => ({ name, text: node.text }))
}
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var express = require('express');
var superagent = require('superagent');
var multer  = require('multer');
var plist = require('plist');
var extract = require('extract-zip');
var B = require('bluebird');
var checkDomain = require('./checkDomain');
var config = require('./config');
var childProcesss = require('child_process');
var newrelic = require('newrelic');

var port = process.env.PORT || config.server.port || 3000;
var app = express();
var uploadDir = 'tmp-app-files';
var upload = multer({ dest: uploadDir });

app.use('/static', express.static('static'));
app.use('/', express.static('static'));

app.post('/domain/:domain', function (httpReq, httpResp) {
    var domain = httpReq.params.domain;
    var respObj = { domains: { } };

    return checkDomain(domain)
        .then(function(aasa) {
            respObj.domains[domain] = { aasa: aasa };

            httpResp.status(200).json(respObj);
        })
        .catch(function(errorObj) {
            respObj.domains[domain] = { errors: errorObj };

            httpResp.status(400).json(respObj);
        });
});

function _checkAssociatedDomain(associatedDomain, respObj) {
    var domain = associatedDomain.substring(9);

    return checkDomain(domain)
        .then(function(aasa) {
            respObj.domains[domain] = { aasa: aasa };
        })
        .catch(function(errorObj) {
            hasBadValue = true;
            respObj.domains[domain] = { errors: errorObj };
        });
}

function _cleanupAppFiles(ipaFile, extractedAppDir) {
    childProcesss.exec('rm -rf ' + ipaFile + ' ' + extractedAppDir);
}

app.post('/app', upload.single('ipa'), function(httpReq, httpResp) {
    var ipa = httpReq.file;
    var appName = ipa.originalname.replace('.ipa', '');
    var extractDir = path.join(uploadDir, appName);
    var entitlementsFile = path.join(extractDir, 'Payload', appName + '.app', 'archived-expanded-entitlements.xcent');

    extract(ipa.path, { dir: extractDir }, function(err) {
        if (err) {
            httpResp.status(500).json({ error: 'Failed to extract archive' });
            _cleanupAppFiles(ipa.path, extractDir);
            return;
        }

        var entitlements = plist.parse(fs.readFileSync(entitlementsFile, 'utf8'));
        var associatedDomains = entitlements['com.apple.developer.associated-domains'];

        if (!associatedDomains || !associatedDomains.length) {
            httpResp.status(400).json({ appInfo: { missingAssociatedDomain: true } });
            _cleanupAppFiles(ipa.path, extractDir);
        }
        else {
            var respObj = { appInfo: { missingAssociatedDomain: false }, domains: { } };
            var domainPromises = [];
            var hasBadValue = false;

            for (var i = 0; i < associatedDomains.length; i++) {
                var associatedDomain = associatedDomains[i];
                if (!/applinks:.*?/.test(associatedDomain)) {
                    hasBadValue = true;
                    respObj.domains[associatedDomain] = { malformed: true };
                }
                else {
                    domainPromises.push(_checkAssociatedDomain(associatedDomain, respObj));
                }
            }

            return B.all(domainPromises).then(function() {
                if (!hasBadValue) {
                    httpResp.status(200);
                }
                else {
                    httpResp.status(400);
                }

                httpResp.json(respObj);
                _cleanupAppFiles(ipa.path, extractDir);
            });
        }
    });
});

var server = app.listen(port, function() {
    console.log('Server running on port ' + port);
});
<commit_msg>Apparently this needs to be first.<commit_after>var newrelic = require('newrelic');
var path = require('path');
var fs = require('fs');
var express = require('express');
var superagent = require('superagent');
var multer  = require('multer');
var plist = require('plist');
var extract = require('extract-zip');
var B = require('bluebird');
var checkDomain = require('./checkDomain');
var config = require('./config');
var childProcesss = require('child_process');

var port = process.env.PORT || config.server.port || 3000;
var app = express();
var uploadDir = 'tmp-app-files';
var upload = multer({ dest: uploadDir });

app.use('/static', express.static('static'));
app.use('/', express.static('static'));

app.post('/domain/:domain', function (httpReq, httpResp) {
    var domain = httpReq.params.domain;
    var respObj = { domains: { } };

    return checkDomain(domain)
        .then(function(aasa) {
            respObj.domains[domain] = { aasa: aasa };

            httpResp.status(200).json(respObj);
        })
        .catch(function(errorObj) {
            respObj.domains[domain] = { errors: errorObj };

            httpResp.status(400).json(respObj);
        });
});

function _checkAssociatedDomain(associatedDomain, respObj) {
    var domain = associatedDomain.substring(9);

    return checkDomain(domain)
        .then(function(aasa) {
            respObj.domains[domain] = { aasa: aasa };
        })
        .catch(function(errorObj) {
            hasBadValue = true;
            respObj.domains[domain] = { errors: errorObj };
        });
}

function _cleanupAppFiles(ipaFile, extractedAppDir) {
    childProcesss.exec('rm -rf ' + ipaFile + ' ' + extractedAppDir);
}

app.post('/app', upload.single('ipa'), function(httpReq, httpResp) {
    var ipa = httpReq.file;
    var appName = ipa.originalname.replace('.ipa', '');
    var extractDir = path.join(uploadDir, appName);
    var entitlementsFile = path.join(extractDir, 'Payload', appName + '.app', 'archived-expanded-entitlements.xcent');

    extract(ipa.path, { dir: extractDir }, function(err) {
        if (err) {
            httpResp.status(500).json({ error: 'Failed to extract archive' });
            _cleanupAppFiles(ipa.path, extractDir);
            return;
        }

        var entitlements = plist.parse(fs.readFileSync(entitlementsFile, 'utf8'));
        var associatedDomains = entitlements['com.apple.developer.associated-domains'];

        if (!associatedDomains || !associatedDomains.length) {
            httpResp.status(400).json({ appInfo: { missingAssociatedDomain: true } });
            _cleanupAppFiles(ipa.path, extractDir);
        }
        else {
            var respObj = { appInfo: { missingAssociatedDomain: false }, domains: { } };
            var domainPromises = [];
            var hasBadValue = false;

            for (var i = 0; i < associatedDomains.length; i++) {
                var associatedDomain = associatedDomains[i];
                if (!/applinks:.*?/.test(associatedDomain)) {
                    hasBadValue = true;
                    respObj.domains[associatedDomain] = { malformed: true };
                }
                else {
                    domainPromises.push(_checkAssociatedDomain(associatedDomain, respObj));
                }
            }

            return B.all(domainPromises).then(function() {
                if (!hasBadValue) {
                    httpResp.status(200);
                }
                else {
                    httpResp.status(400);
                }

                httpResp.json(respObj);
                _cleanupAppFiles(ipa.path, extractDir);
            });
        }
    });
});

var server = app.listen(port, function() {
    console.log('Server running on port ' + port);
});
<|endoftext|>