<commit_before>/* 12oct12abu
 * (c) Software Lab. Alexander Burger
 */

var FormReq = false;
var HintReq = false;
var LispReq = false;
var Hint, Hints, Item, Beg, End;

try {
   FormReq = new XMLHttpRequest();
   HintReq = new XMLHttpRequest();
   LispReq = new XMLHttpRequest();
   FormReq.upload.addEventListener("progress", dropProgress, false);
   FormReq.upload.addEventListener("load", dropLoad, false);
}
catch (e) {}

var Queue = new Array();
var Btn = new Array();
var Key, InBtn, Auto, Drop;

function inBtn(flg) {InBtn = flg;}

function formKey(event) {
   Key = event.keyCode;
   if (Hint  &&  Hint.style.visibility == "visible") {
      if ((Item >= 0 && Key == 13) || Key == 38 || Key == 40)
         return false;
      if (event.keyCode == 27) {
         Hint.style.visibility = "hidden";
         return false;
      }
   }
   return true;
}

function fldChg(field) {
   if (!InBtn && Key != 13)
      post(field.form, null);
   return true;
}

function doBtn(btn) {
   Btn.push(btn);
   return true;
}

function doDrag(event) {
   event.stopPropagation();
   event.preventDefault();
}

function doDrop(btn, event) {
   doDrag(event);
   if (event.dataTransfer.files.length != 0) {
      Btn.push(Drop = btn);
      btn.value = "0 %";
      post(btn.form, event.dataTransfer.files[0]);
   }
}

function dropProgress(event) {
   if (Drop)
      Drop.value = event.lengthComputable?
         Math.round((event.loaded * 100) / event.total) + " %" : "(?) %";
}

function dropLoad(event) {
   Drop = null;
}

function hasElement(form, name) {
   for (var i = 0; i < form.elements.length; ++i)
      if (form.elements[i].name == name)
         return true;
   return false;
}

/*** Form submit ***/
function doPost(form) {
   for (var i = 0; ; ++i) {
      if (i == Btn.length)
         return true;
      if (Btn[i].form == form)
         break;
   }
   return post(form, null);
}

function post(form, file) {
   var i;

   if (!FormReq || !hasElement(form,"*Get") || (i = form.action.indexOf("~")) <= 0)
      return true;
   if (FormReq.readyState > 0 && FormReq.readyState < 4) {
      Queue.push(form);
      return false;
   }
   form.style.cursor = "wait";
   try {FormReq.open("POST", form.action.substr(0,i) + "~!jsForm?" + form.action.substr(i+1));}
   catch (e) {return true;}
   FormReq.onreadystatechange = function() {
      if (FormReq.readyState == 4 && FormReq.status == 200) {
         var i, j;

         if (FormReq.responseText == "T") {
            Queue.length = 0;
            form.submit();
         }
         else {
            var txt = FormReq.responseText.split("&");

            if (txt[0]) {
               var r = txt[0].split(":");

               if (Auto)
                  window.clearTimeout(Auto);
               if (r[1])
                  Auto = window.setTimeout("document.getElementById(\"" + r[0] + "\").click()", r[1]);
            }
            for (i = 1; i < txt.length;) {
               var fld = txt[i++];
               var val = decodeURIComponent(txt[i++]);

               if (!fld) {
                  window[txt[i++]](val);
                  continue;
               }
               if (!(fld = document.getElementById(fld)))
                  continue;
               if (fld.tagName == "SPAN") {
                  if (i != txt.length && txt[i].charAt(0) == "=")
                     ++i;
                  if (i == txt.length || txt[i].charAt(0) != "+") {
                     if (fld.firstChild.tagName != "A")
                        fld.firstChild.data = val? val : "\u00A0";
                     else
                        fld.replaceChild(document.createTextNode(val? val : "\u00A0"), fld.firstChild);
                  }
                  else {
                     var a = document.createElement("A");

                     a.href = decodeURIComponent(txt[i++].substr(1));
                     a.appendChild(document.createTextNode(val));
                     fld.replaceChild(a, fld.firstChild);
                  }
               }
               else if (fld.tagName == "A") {
                  if (i != txt.length && txt[i].charAt(0) == "=")
                     ++i;
                  if (i == txt.length || txt[i].charAt(0) != "+") {
                     fld.replaceChild(document.createTextNode(val? val : "\u00A0"), fld.firstChild);
                     fld.removeAttribute("href");
                  }
                  else {
                     fld.firstChild.data = val;
                     fld.href = decodeURIComponent(txt[i++].substr(1));
                  }
               }
               else if (fld.tagName == "IMG")
                  fld.src = val;
               else {
                  if (fld.custom != null)
                     putCustom(fld.custom, val);
                  else if (fld.type == "checkbox") {
                     fld.checked = val != "";
                     document.getElementsByName(fld.name)[0].value = "";
                  }
                  else if (fld.type == "select-one") {
                     for (j = 0; j < fld.options.length; ++j) {
                        if (fld.options[j].text == val)
                           fld.selectedIndex = j;
                        fld.options[j].disabled = false;
                     }
                  }
                  else if (fld.type == "radio") {
                     fld.value = val;
                     fld.checked = txt[i++].charAt(0) != "";
                  }
                  else if (fld.type == "image")
                     fld.src = val;
                  else if (fld.value != val) {
                     fld.value = val;
                     fld.scrollTop = fld.scrollHeight;
                  }
                  fld.disabled = false;
                  if (i < txt.length && txt[i].charAt(0) == "=") {
                     if (fld.type == "select-one") {
                        for (j = 0; j < fld.options.length; ++j)
                           if (fld.options[j].text != val)
                              fld.options[j].disabled = true;
                     }
                     fld.disabled = true;
                     InBtn = 0;  // 'onblur' on won't come when disabled
                     if (fld.type == "checkbox"  &&  fld.checked)
                        document.getElementsByName(fld.name)[0].value = "T";
                     ++i;
                  }
                  if (fld.custom != null)
                     ableCustom(fld.custom);
               }
               while (i < txt.length && (j = "#*?".indexOf(txt[i].charAt(0))) >= 0) {
                  switch (j) {

                  case 0:  // '#'
                     var cls;

                     val = txt[i++].substr(1);
                     if ((cls = fld.getAttribute("class")) != null  &&  (j = cls.indexOf(" ")) >= 0)
                        val += cls.substr(j);
                     fld.setAttribute("class", val);
                     break;

                  case 1:  // '*'
                     var node = fld.parentNode.parentNode.lastChild;
                     var img = document.createElement("IMG");

                     if (!node.firstChild)
                        node = fld.parentNode.parentNode.parentNode.lastChild;
                     node.removeChild(node.firstChild);
                     img.src = txt[i++].substr(1);
                     if (!txt[i])
                        node.appendChild(img);
                     else {
                        var a = document.createElement("A");

                        a.href = decodeURIComponent(txt[i]);
                        a.appendChild(img);
                        node.appendChild(a);
                     }
                     ++i;
                     break;

                  case 2:  // '?'
                     fld.title = decodeURIComponent(txt[i++].substr(1));
                     break;
                  }
               }
            }
         }
         form.style.cursor = "";
         if (Queue.length > 0)
            post(Queue.shift(), null);
      }
   }
   var data = "";
   for (var i = 0; i < Btn.length;)
      if (Btn[i].form != form)
         ++i;
      else {
         data += (data? "&":"") + Btn[i].name + "=" + encodeURIComponent(Btn[i].type == "submit"? Btn[i].value : Btn[i].src);
         Btn.splice(i,1);
      }
   for (i = 0; i < form.elements.length; ++i) {
      var fld = form.elements[i];

      if (fld.name  &&  fld.type != "submit") {   // "image" won't come :-(
         var val;

         if (fld.custom != null)
            val = getCustom(fld.custom);
         else if (fld.type == "checkbox")
            val = fld.checked? "T" : "";
         else if (fld.type == "select-one")
            val = fld.options[fld.selectedIndex].text;
         else if (fld.type == "radio" && !fld.checked)
            continue;
         else
            val = fld.value;
         data += "&" + fld.name + "=" + encodeURIComponent(val);
      }
   }
   try {
      if (!file)
         FormReq.send(data);
      else {
         var rd = new FileReader();
         rd.readAsBinaryString(file);
         rd.onload = function() {
            FormReq.setRequestHeader("X-Pil", "*ContLen=");
            FormReq.sendAsBinary(data + "&*Drop=" +
               encodeURIComponent(file.name) + "=" +
               file.size + "\n" + rd.result );
         }
      }
   }
   catch (e) {
      FormReq.abort();
      return true;
   }
   return false;
}

/*** Hints ***/
function doHint(field) {
   if (HintReq) {
      if (!Hint) {
         Hint = document.createElement("div");
         Hint.setAttribute("class", "hint");
         Hint.style.visibility = "hidden";
         Hint.style.position = "absolute";
         Hints = document.createElement("div");
         Hints.setAttribute("class", "hints");
         Hints.style.position = "relative";
         Hints.style.top = "-2px";
         Hints.style.left = "-3px";
         Hint.appendChild(Hints);
      }
      field.parentNode.appendChild(Hint);
      field.onblur = function() {
         Hint.style.visibility = "hidden";
      }
      var top = field.offsetHeight + 2;
      var left = 3;
      for (var obj = field;  obj.id != "main" && obj.id != "menu";  obj = obj.offsetParent) {
         top += obj.offsetTop;
         left += obj.offsetLeft;
      }
      Hint.style.top = top + "px";
      Hint.style.left = left + "px";
   }
}

function hintKey(field, event, tok, coy) {
   var i, data;

   if (!HintReq)
      return true;
   if (event.keyCode == 9 || event.keyCode == 27)
      return false;
   if (Hint.style.visibility == "visible") {
      if (Item >= 0 && event.keyCode == 13) {
         setHint(field, Hints.childNodes[Item]);
         return false;
      }
      if (event.keyCode == 38) {  // Up
         if (Item > 0) {
            hintOff(Item);
            hintOn(--Item);
         }
         return false;
      }
      if (event.keyCode == 40) {  // Down
         if (Item < (lst = Hints.childNodes).length-1) {
            if (Item >= 0)
               hintOff(Item);
            hintOn(++Item);
         }
         return false;
      }
   }
   if (event.keyCode == 13)
      return true;
   if (HintReq.readyState > 0 && HintReq.readyState < 4)
      return false;
   if (tok) {
      for (Beg = field.selectionStart;  Beg > 0 && !field.value.charAt(Beg-1).match(/\s/);  --Beg);
      End = field.selectionEnd;
   }
   else {
      Beg = 0;
      End = field.value.length;
   }
   if (event.keyCode != 45) {  // INS
      if (Beg == End) {
         Hint.style.visibility = "hidden";
         return false;
      }
      if (coy && Hint.style.visibility == "hidden")
         return false;
   }
   try {
      HintReq.open("POST",
         ((i = field.form.action.indexOf("~")) <= 0?
            "" : field.form.action.substr(0, i+1) ) +
         ((i = field.id.lastIndexOf("-")) < 0?
            "!jsHint?$" + field.id : "!jsHint?+" + field.id.substr(i+1) ) );
   }
   catch (e) {return true;}
   HintReq.onreadystatechange = function() {
      if (HintReq.readyState == 4 && HintReq.status == 200) {
         var i, n, lst, str;

         if ((str = HintReq.responseText).length == 0)
            Hint.style.visibility = "hidden";
         else {
            lst = str.split("&");
            while (Hints.hasChildNodes())
               Hints.removeChild(Hints.firstChild);
            for (i = 0, n = 7; i < lst.length; ++i) {
               addHint(i, field, str = decodeURIComponent(lst[i]));
               if (str.length > n)
                  n = str.length;
            }
            Hints.style.width = n + 3 + "ex";
            Hint.style.width = n + 4 + "ex";
            Hint.style.visibility = "visible";
            Item = -1;
         }
      }
   }
   var data = "*JsHint=" + encodeURIComponent(field.value.substring(Beg,End));
   for (i = 0; i < field.form.elements.length; ++i) {
      var fld = field.form.elements[i];

      if (fld.name == "*Get")
         data += "&*Get=" + fld.value;
      else if (fld.name == "*Form")
         data += "&*Form=" + fld.value;
   }
   try {HintReq.send(data);}
   catch (e) {
      HintReq.abort();
      return true;
   }
   return (event.keyCode != 45);  // INS
}

function addHint(i, field, str) {
   var item = document.createElement("div");
   item.appendChild(document.createTextNode(str));
   item.onmouseover = function() {
      if (Item >= 0)
         hintOff(Item);
      hintOn(i);
      field.onblur = false;
      field.onchange = false;
      Item = i;
   }
   item.onmouseout = function() {
      hintOff(Item);
      field.onblur = function() {
         Hint.style.visibility = "hidden";
      }
      field.onchange = function() {
         return fldChg(field, item);
      };
      Item = -1;
   }
   item.onclick = function() {
      setHint(field, item);
   }
   Hints.appendChild(item);
}

function setHint(field, item) {
   Hint.style.visibility = "hidden";
   field.value = field.value.substr(0,Beg) + item.firstChild.nodeValue + field.value.substr(End);
   post(field.form, null);
   field.setSelectionRange(Beg + item.firstChild.nodeValue.length, field.value.length);
   field.focus();
   field.onchange = function() {
      return fldChg(field)
   };
}

function hintOn(i) {
   var s = Hints.childNodes[i].style;
   s.background = "black";
   s.color= "white";
}

function hintOff(i) {
   var s = Hints.childNodes[i].style;
   s.background = "white";
   s.color= "black";
}

/*** Lisp calls ***/
function lisp(url) {
   if (!LispReq)
      return true;
   if (arguments.length > 1) {
      url += "?" + arguments[1];  // arguments should be properly encoded
      for (var i = 2; i < arguments.length; ++i)
         url += "&" + arguments[i];
   }
   try {LispReq.open("GET", url);}
   catch (e) {return true;}
   try {LispReq.send(null);}
   catch (e) {
      LispReq.abort();
      return true;
   }
   return false;
}
<commit_msg>Cosmetics<commit_after>/* 28dec12abu
 * (c) Software Lab. Alexander Burger
 */

var FormReq = false;
var HintReq = false;
var LispReq = false;
var Hint, Hints, Item, Beg, End;

try {
   FormReq = new XMLHttpRequest();
   HintReq = new XMLHttpRequest();
   LispReq = new XMLHttpRequest();
   FormReq.upload.addEventListener("progress", dropProgress, false);
   FormReq.upload.addEventListener("load", dropLoad, false);
}
catch (e) {}

var Queue = new Array();
var Btn = new Array();
var Key, InBtn, Auto, Drop;

function inBtn(flg) {InBtn = flg;}

function formKey(event) {
   Key = event.keyCode;
   if (Hint  &&  Hint.style.visibility == "visible") {
      if ((Item >= 0 && Key == 13) || Key == 38 || Key == 40)
         return false;
      if (event.keyCode == 27) {
         Hint.style.visibility = "hidden";
         return false;
      }
   }
   return true;
}

function fldChg(field) {
   if (!InBtn && Key != 13)
      post(field.form, null);
   return true;
}

function doBtn(btn) {
   Btn.push(btn);
   return true;
}

function doDrag(event) {
   event.stopPropagation();
   event.preventDefault();
}

function doDrop(btn, event) {
   doDrag(event);
   if (event.dataTransfer.files.length != 0) {
      Btn.push(Drop = btn);
      btn.value = "0 %";
      post(btn.form, event.dataTransfer.files[0]);
   }
}

function dropProgress(event) {
   if (Drop)
      Drop.value = event.lengthComputable?
         Math.round((event.loaded * 100) / event.total) + " %" : "(?) %";
}

function dropLoad(event) {
   Drop = null;
}

function hasElement(form, name) {
   for (var i = 0; i < form.elements.length; ++i)
      if (form.elements[i].name == name)
         return true;
   return false;
}

/*** Form submit ***/
function doPost(form) {
   for (var i = 0; ; ++i) {
      if (i == Btn.length)
         return true;
      if (Btn[i].form == form)
         break;
   }
   return post(form, null);
}

function post(form, file) {
   var i;

   if (!FormReq || !hasElement(form,"*Get") || (i = form.action.indexOf("~")) <= 0)
      return true;
   if (FormReq.readyState > 0 && FormReq.readyState < 4) {
      Queue.push(form);
      return false;
   }
   form.style.cursor = "wait";
   try {FormReq.open("POST", form.action.substr(0,i) + "~!jsForm?" + form.action.substr(i+1));}
   catch (e) {return true;}
   FormReq.onload = function() {
      var i, j;

      if (FormReq.responseText == "T") {
         Queue.length = 0;
         form.submit();
      }
      else {
         var txt = FormReq.responseText.split("&");

         if (txt[0]) {
            var r = txt[0].split(":");

            if (Auto)
               window.clearTimeout(Auto);
            if (r[1])
               Auto = window.setTimeout("document.getElementById(\"" + r[0] + "\").click()", r[1]);
         }
         for (i = 1; i < txt.length;) {
            var fld = txt[i++];
            var val = decodeURIComponent(txt[i++]);

            if (!fld) {
               window[txt[i++]](val);
               continue;
            }
            if (!(fld = document.getElementById(fld)))
               continue;
            if (fld.tagName == "SPAN") {
               if (i != txt.length && txt[i].charAt(0) == "=")
                  ++i;
               if (i == txt.length || txt[i].charAt(0) != "+") {
                  if (fld.firstChild.tagName != "A")
                     fld.firstChild.data = val? val : "\u00A0";
                  else
                     fld.replaceChild(document.createTextNode(val? val : "\u00A0"), fld.firstChild);
               }
               else {
                  var a = document.createElement("A");

                  a.href = decodeURIComponent(txt[i++].substr(1));
                  a.appendChild(document.createTextNode(val));
                  fld.replaceChild(a, fld.firstChild);
               }
            }
            else if (fld.tagName == "A") {
               if (i != txt.length && txt[i].charAt(0) == "=")
                  ++i;
               if (i == txt.length || txt[i].charAt(0) != "+") {
                  fld.replaceChild(document.createTextNode(val? val : "\u00A0"), fld.firstChild);
                  fld.removeAttribute("href");
               }
               else {
                  fld.firstChild.data = val;
                  fld.href = decodeURIComponent(txt[i++].substr(1));
               }
            }
            else if (fld.tagName == "IMG")
               fld.src = val;
            else {
               if (fld.custom != null)
                  putCustom(fld.custom, val);
               else if (fld.type == "checkbox") {
                  fld.checked = val != "";
                  document.getElementsByName(fld.name)[0].value = "";
               }
               else if (fld.type == "select-one") {
                  for (j = 0; j < fld.options.length; ++j) {
                     if (fld.options[j].text == val)
                        fld.selectedIndex = j;
                     fld.options[j].disabled = false;
                  }
               }
               else if (fld.type == "radio") {
                  fld.value = val;
                  fld.checked = txt[i++].charAt(0) != "";
               }
               else if (fld.type == "image")
                  fld.src = val;
               else if (fld.value != val) {
                  fld.value = val;
                  fld.scrollTop = fld.scrollHeight;
               }
               fld.disabled = false;
               if (i < txt.length && txt[i].charAt(0) == "=") {
                  if (fld.type == "select-one") {
                     for (j = 0; j < fld.options.length; ++j)
                        if (fld.options[j].text != val)
                           fld.options[j].disabled = true;
                  }
                  fld.disabled = true;
                  InBtn = 0;  // 'onblur' on won't come when disabled
                  if (fld.type == "checkbox"  &&  fld.checked)
                     document.getElementsByName(fld.name)[0].value = "T";
                  ++i;
               }
               if (fld.custom != null)
                  ableCustom(fld.custom);
            }
            while (i < txt.length && (j = "#*?".indexOf(txt[i].charAt(0))) >= 0) {
               switch (j) {

               case 0:  // '#'
                  var cls;

                  val = txt[i++].substr(1);
                  if ((cls = fld.getAttribute("class")) != null  &&  (j = cls.indexOf(" ")) >= 0)
                     val += cls.substr(j);
                  fld.setAttribute("class", val);
                  break;

               case 1:  // '*'
                  var node = fld.parentNode.parentNode.lastChild;
                  var img = document.createElement("IMG");

                  if (!node.firstChild)
                     node = fld.parentNode.parentNode.parentNode.lastChild;
                  node.removeChild(node.firstChild);
                  img.src = txt[i++].substr(1);
                  if (!txt[i])
                     node.appendChild(img);
                  else {
                     var a = document.createElement("A");

                     a.href = decodeURIComponent(txt[i]);
                     a.appendChild(img);
                     node.appendChild(a);
                  }
                  ++i;
                  break;

               case 2:  // '?'
                  fld.title = decodeURIComponent(txt[i++].substr(1));
                  break;
               }
            }
         }
      }
      form.style.cursor = "";
      if (Queue.length > 0)
         post(Queue.shift(), null);
   }
   var data = "";
   for (var i = 0; i < Btn.length;)
      if (Btn[i].form != form)
         ++i;
      else {
         data += (data? "&":"") + Btn[i].name + "=" + encodeURIComponent(Btn[i].type == "submit"? Btn[i].value : Btn[i].src);
         Btn.splice(i,1);
      }
   for (i = 0; i < form.elements.length; ++i) {
      var fld = form.elements[i];

      if (fld.name  &&  fld.type != "submit") {   // "image" won't come :-(
         var val;

         if (fld.custom != null)
            val = getCustom(fld.custom);
         else if (fld.type == "checkbox")
            val = fld.checked? "T" : "";
         else if (fld.type == "select-one")
            val = fld.options[fld.selectedIndex].text;
         else if (fld.type == "radio" && !fld.checked)
            continue;
         else
            val = fld.value;
         data += "&" + fld.name + "=" + encodeURIComponent(val);
      }
   }
   try {
      if (!file)
         FormReq.send(data);
      else {
         var rd = new FileReader();
         rd.readAsBinaryString(file);
         rd.onload = function() {
            FormReq.setRequestHeader("X-Pil", "*ContLen=");
            FormReq.sendAsBinary(data + "&*Drop=" +
               encodeURIComponent(file.name) + "=" +
               file.size + "\n" + rd.result );
         }
      }
   }
   catch (e) {
      FormReq.abort();
      return true;
   }
   return false;
}

/*** Hints ***/
function doHint(field) {
   if (HintReq) {
      if (!Hint) {
         Hint = document.createElement("div");
         Hint.setAttribute("class", "hint");
         Hint.style.visibility = "hidden";
         Hint.style.position = "absolute";
         Hints = document.createElement("div");
         Hints.setAttribute("class", "hints");
         Hints.style.position = "relative";
         Hints.style.top = "-2px";
         Hints.style.left = "-3px";
         Hint.appendChild(Hints);
      }
      field.parentNode.appendChild(Hint);
      field.onblur = function() {
         Hint.style.visibility = "hidden";
      }
      var top = field.offsetHeight + 2;
      var left = 3;
      for (var obj = field;  obj.id != "main" && obj.id != "menu";  obj = obj.offsetParent) {
         top += obj.offsetTop;
         left += obj.offsetLeft;
      }
      Hint.style.top = top + "px";
      Hint.style.left = left + "px";
   }
}

function hintKey(field, event, tok, coy) {
   var i, data;

   if (!HintReq)
      return true;
   if (event.keyCode == 9 || event.keyCode == 27)
      return false;
   if (Hint.style.visibility == "visible") {
      if (Item >= 0 && event.keyCode == 13) {
         setHint(field, Hints.childNodes[Item]);
         return false;
      }
      if (event.keyCode == 38) {  // Up
         if (Item > 0) {
            hintOff(Item);
            hintOn(--Item);
         }
         return false;
      }
      if (event.keyCode == 40) {  // Down
         if (Item < (lst = Hints.childNodes).length-1) {
            if (Item >= 0)
               hintOff(Item);
            hintOn(++Item);
         }
         return false;
      }
   }
   if (event.keyCode == 13)
      return true;
   if (HintReq.readyState > 0 && HintReq.readyState < 4)
      return false;
   if (tok) {
      for (Beg = field.selectionStart;  Beg > 0 && !field.value.charAt(Beg-1).match(/\s/);  --Beg);
      End = field.selectionEnd;
   }
   else {
      Beg = 0;
      End = field.value.length;
   }
   if (event.keyCode != 45) {  // INS
      if (Beg == End) {
         Hint.style.visibility = "hidden";
         return false;
      }
      if (coy && Hint.style.visibility == "hidden")
         return false;
   }
   try {
      HintReq.open("POST",
         ((i = field.form.action.indexOf("~")) <= 0?
            "" : field.form.action.substr(0, i+1) ) +
         ((i = field.id.lastIndexOf("-")) < 0?
            "!jsHint?$" + field.id : "!jsHint?+" + field.id.substr(i+1) ) );
   }
   catch (e) {return true;}
   HintReq.onload = function() {
      var i, n, lst, str;

      if ((str = HintReq.responseText).length == 0)
         Hint.style.visibility = "hidden";
      else {
         lst = str.split("&");
         while (Hints.hasChildNodes())
            Hints.removeChild(Hints.firstChild);
         for (i = 0, n = 7; i < lst.length; ++i) {
            addHint(i, field, str = decodeURIComponent(lst[i]));
            if (str.length > n)
               n = str.length;
         }
         Hints.style.width = n + 3 + "ex";
         Hint.style.width = n + 4 + "ex";
         Hint.style.visibility = "visible";
         Item = -1;
      }
   }
   var data = "*JsHint=" + encodeURIComponent(field.value.substring(Beg,End));
   for (i = 0; i < field.form.elements.length; ++i) {
      var fld = field.form.elements[i];

      if (fld.name == "*Get")
         data += "&*Get=" + fld.value;
      else if (fld.name == "*Form")
         data += "&*Form=" + fld.value;
   }
   try {HintReq.send(data);}
   catch (e) {
      HintReq.abort();
      return true;
   }
   return (event.keyCode != 45);  // INS
}

function addHint(i, field, str) {
   var item = document.createElement("div");
   item.appendChild(document.createTextNode(str));
   item.onmouseover = function() {
      if (Item >= 0)
         hintOff(Item);
      hintOn(i);
      field.onblur = false;
      field.onchange = false;
      Item = i;
   }
   item.onmouseout = function() {
      hintOff(Item);
      field.onblur = function() {
         Hint.style.visibility = "hidden";
      }
      field.onchange = function() {
         return fldChg(field, item);
      };
      Item = -1;
   }
   item.onclick = function() {
      setHint(field, item);
   }
   Hints.appendChild(item);
}

function setHint(field, item) {
   Hint.style.visibility = "hidden";
   field.value = field.value.substr(0,Beg) + item.firstChild.nodeValue + field.value.substr(End);
   post(field.form, null);
   field.setSelectionRange(Beg + item.firstChild.nodeValue.length, field.value.length);
   field.focus();
   field.onchange = function() {
      return fldChg(field)
   };
}

function hintOn(i) {
   var s = Hints.childNodes[i].style;
   s.background = "black";
   s.color= "white";
}

function hintOff(i) {
   var s = Hints.childNodes[i].style;
   s.background = "white";
   s.color= "black";
}

/*** Lisp calls ***/
function lisp(url) {
   if (!LispReq)
      return true;
   if (arguments.length > 1) {
      url += "?" + arguments[1];  // arguments should be properly encoded
      for (var i = 2; i < arguments.length; ++i)
         url += "&" + arguments[i];
   }
   try {LispReq.open("GET", url);}
   catch (e) {return true;}
   try {LispReq.send(null);}
   catch (e) {
      LispReq.abort();
      return true;
   }
   return false;
}
<|endoftext|>


<commit_before>var Context         = require('../media/js/context')
  , ContextObject   = require('../media/js/context_object')
  , init_definition = require('../media/js/definition')
  , init_game_defs  = require('../media/js/game_defs')
  , BaseGame        = require('../media/js/game')
  , uuid            = require('node-uuid')
  , url             = require('url')
  , missions        = require('./missions')

Number.prototype.degrees = function() {
  return this * (Math.PI / 180)
}

var games = {}

function Game(id, name, map_name) {
  this.id = id
  this.name = name
  this.mission = missions[map_name]

  this.definition_class = init_definition()
  this.context = new Context(this.id, this.definition_class)

  this.context.is_network = true

  this.defs = init_game_defs(this.definition_class, [this.context])
  this.game = new BaseGame(this.context)

  this.game.thread_loop(this.interval(), 33)

  var self = this
  this.mission.load(function(name, values) {
    var obj = self.context.create_object(self.definition_class.all[name])
    for(var key in values) {
      obj[key] = values[key]
    }
  }, this.mission.assets)

  this.clients = {}
}

Game.prototype.interval = function() {
  var self = this
    , ctxt = this.context

  return function(dt) {
    Object.keys(ctxt.objects).forEach(function(key) {
      var item = ctxt.objects[key]
      item.update && item.update(ctxt, dt)
    })
    var all = self.context.create_update({uuid:null, is_thread:true})
    if(all)
      self.send_all('update', all)
  }
}

Game.prototype.send_all = function(what, data) {
  var self = this
  Object.keys(this.clients).forEach(function(id) {
    self.clients[id].socket.emit(what, data)
  })
}

Game.prototype.join = function(client_id, socket, ack_id) {
  this.clients[client_id] = {
      socket  :socket
    , context :new Context(client_id)
  }

  this.clients[client_id].context.is_renderer = true

  var player = this.context.create_object(this.defs.Player)
    , control = this.context.create_object(this.defs.Control)
    , self = this

  control.player_id = player.__uuid__
  control.input_id = client_id+':1'

  var update = self.context.create_full_update()

  self.clients[client_id].control = control

  socket.emit('ack', {ack:ack_id, data:[
    null, self.mission.assets, control.__uuid__, update
  ]})

  socket.on('update', function(payload) { self.recv_update(payload, self.clients[client_id].context) })
  socket.on('disconnect', function() {
    // remove the control and the player object.
    if(self.context.objects[control.player_id]) {
      self.context.objects[control.player_id].delete()
    }
    control.delete()
  })
}

Game.prototype.recv_update = function(update, from_context) {
  this.context.recv_update(update, from_context)
}

Game.prototype.get_absolute_url = function() {
  return '/games/'+this.id
}

Game.prototype.create_client_uuid = function() {
  var arr = new Array(16)
  return uuid.v4(null, arr, 0).map(function(i) { return i.toString(16) }).join('')
}

module.exports = {
  list:function(template, req, resp) {
    template.render({games:games, missions:missions}, function(err, data) {
      resp.writeHead(200, {'Content-Type':'text/html'})
      resp.end(data)
    })
  }
  , create:function(template, req, resp) {
    var data = []
    req.on('data', data.push.bind(data))
    req.on('end', function() {
      data = url.parse('/?'+data.join(''), true).query

      if(!missions[data.map]) {
        resp.writeHead(302, {Location:'/'})
        return resp.end()
      }

      var my_uuid = new Array(16)
      my_uuid = uuid.v4(null, my_uuid, 0)
        .map(function(i) { return i.toString(16) })
        .join('')
      games[my_uuid] = new Game(my_uuid, data.name, data.map)

      resp.writeHead(302, {Location:'/games/'+my_uuid})
      resp.end()
    })
  }
  , join:function(template, req, resp, which) {
    var game = games[which]
    if(!game) {
      resp.writeHead(404, {'Content-Type':'text/html'})
      return resp.end('
not found
')
    }
    template.render({game:game}, function(err, data) {
      resp.writeHead(200, {'Content-Type':'text/html'})
      resp.end(data)
    })
  }
  , socket_join:function(game_id, client_id, socket, ack) {
    var game = games[game_id]
    if(!game) return

    game.join(client_id, socket, ack)
  }
}
<commit_msg>add some comments to lib/game.js explaining the exports.<commit_after>var Context         = require('../media/js/context')
  , ContextObject   = require('../media/js/context_object')
  , init_definition = require('../media/js/definition')
  , init_game_defs  = require('../media/js/game_defs')
  , BaseGame        = require('../media/js/game')
  , uuid            = require('node-uuid')
  , url             = require('url')
  , missions        = require('./missions')

Number.prototype.degrees = function() {
  return this * (Math.PI / 180)
}

var games = {}

function Game(id, name, map_name) {
  this.id = id
  this.name = name
  this.mission = missions[map_name]

  this.definition_class = init_definition()
  this.context = new Context(this.id, this.definition_class)

  this.context.is_network = true

  this.defs = init_game_defs(this.definition_class, [this.context])
  this.game = new BaseGame(this.context)

  this.game.thread_loop(this.interval(), 33)

  var self = this
  this.mission.load(function(name, values) {
    var obj = self.context.create_object(self.definition_class.all[name])
    for(var key in values) {
      obj[key] = values[key]
    }
  }, this.mission.assets)

  this.clients = {}
}

Game.prototype.interval = function() {
  var self = this
    , ctxt = this.context

  return function(dt) {
    Object.keys(ctxt.objects).forEach(function(key) {
      var item = ctxt.objects[key]
      item.update && item.update(ctxt, dt)
    })
    var all = self.context.create_update({uuid:null, is_thread:true})
    if(all)
      self.send_all('update', all)
  }
}

Game.prototype.send_all = function(what, data) {
  var self = this
  Object.keys(this.clients).forEach(function(id) {
    self.clients[id].socket.emit(what, data)
  })
}

Game.prototype.join = function(client_id, socket, ack_id) {
  this.clients[client_id] = {
      socket  :socket
    , context :new Context(client_id)
  }

  this.clients[client_id].context.is_renderer = true

  var player = this.context.create_object(this.defs.Player)
    , control = this.context.create_object(this.defs.Control)
    , self = this

  control.player_id = player.__uuid__
  control.input_id = client_id+':1'

  var update = self.context.create_full_update()

  self.clients[client_id].control = control

  socket.emit('ack', {ack:ack_id, data:[
    null, self.mission.assets, control.__uuid__, update
  ]})

  socket.on('update', function(payload) { self.recv_update(payload, self.clients[client_id].context) })
  socket.on('disconnect', function() {
    // remove the control and the player object.
    if(self.context.objects[control.player_id]) {
      self.context.objects[control.player_id].delete()
    }
    control.delete()
  })
}

Game.prototype.recv_update = function(update, from_context) {
  this.context.recv_update(update, from_context)
}

Game.prototype.get_absolute_url = function() {
  return '/games/'+this.id
}

Game.prototype.create_client_uuid = function() {
  var arr = new Array(16)
  return uuid.v4(null, arr, 0).map(function(i) { return i.toString(16) }).join('')
}

// export the controllers and the socket method for joining a game.
module.exports = {
  // list all the available games.
  list:function(template, req, resp) {
    template.render({games:games, missions:missions}, function(err, data) {
      resp.writeHead(200, {'Content-Type':'text/html'})
      resp.end(data)
    })
  }
  // create a new game.
  , create:function(template, req, resp) {
    var data = []
    req.on('data', data.push.bind(data))
    req.on('end', function() {
      data = url.parse('/?'+data.join(''), true).query

      if(!missions[data.map]) {
        resp.writeHead(302, {Location:'/'})
        return resp.end()
      }

      var my_uuid = new Array(16)
      my_uuid = uuid.v4(null, my_uuid, 0)
        .map(function(i) { return i.toString(16) })
        .join('')
      games[my_uuid] = new Game(my_uuid, data.name, data.map)

      resp.writeHead(302, {Location:'/games/'+my_uuid})
      resp.end()
    })
  }
  // join an existing game.
  , join:function(template, req, resp, which) {
    var game = games[which]
    if(!game) {
      resp.writeHead(404, {'Content-Type':'text/html'})
      return resp.end('
not found
')
    }
    template.render({game:game}, function(err, data) {
      resp.writeHead(200, {'Content-Type':'text/html'})
      resp.end(data)
    })
  }
  // called when the `join` controller is rendered and the client
  // connects its websocket.
  , socket_join:function(game_id, client_id, socket, ack) {
    var game = games[game_id]
    if(!game) return

    game.join(client_id, socket, ack)
  }
}
<|endoftext|>


<commit_before>const Ball = require('./balls');
const Paddle = require('./paddle');
const Brick = require('./brick');
const Colors = require('./colors');

var Game = function(){
  var canvas = document.getElementById("canvas").getContext('2d');
  this.size = { x: canvas.canvas.width, y: canvas.canvas.height };
  var paddle = new Paddle(this);
  this.bodies = createBricks(this).concat(createBall(this, paddle)).concat(paddle);

  this.paddleSound = document.getElementById("paddle-sound");
  this.topSound = document.getElementById("top-sound");
  this.wallSound = document.getElementById("wall-sound");
  this.deathSound = document.getElementById("death-sound");

  var self = this;
  var tick = function() {
    self.move();
    self.draw(canvas);
    requestAnimationFrame(tick);
  };
  tick();
};

var createBall = function(game, paddle) {
  var ball = [];
  ball.push(new Ball(game, paddle));
  return ball;
}

var createBricks = function(game) {
  var bricks = [];
  for (var i = 0; i < 54; i++) {
    var x = (Math.floor(i / 6)) * 88
    var y = 70 + (i % 6) * 19;
    bricks.push(new Brick(game, {x: x, y: y}));
  };
  return bricks;
}

Game.prototype = {

  move: function() {
    for (var i = 0; i < this.bodies.length; i++) {
      if (this.bodies[i].move !== undefined) {
        this.bodies[i].move(canvas);
      }
    }
  },

  draw: function(canvas) {
    canvas.clearRect(0, 0, this.size.x, this.size.y);
    var colorList = new Colors();
    for (var i = 0; i < this.bodies.length; i++) {
      if (this.bodies[i].draw !== undefined) {
        this.bodies[i].draw(canvas, colorList[i].toString());
      }
    }
  }
}

module.exports = Game;<commit_msg>Modified game.js to work with paddle test<commit_after>const Ball = require('./balls');
const Paddle = require('./paddle');
const Brick = require('./brick');
const Colors = require('./colors');

var Game = function(){
  if (document.getElementById('canvas')){
    var canvas = document.getElementById('canvas').getContext('2d');
  } else {
    var context = document.createElement('canvas');
    context.width = 782;
    context.height = 520;
    var canvas = context.getContext('2d');
  }

  this.size = { x: canvas.canvas.width, y: canvas.canvas.height };
  var paddle = new Paddle(this);
  this.bodies = createBricks(this).concat(createBall(this, paddle)).concat(paddle);

  this.paddleSound = document.getElementById("paddle-sound");
  this.topSound = document.getElementById("top-sound");
  this.wallSound = document.getElementById("wall-sound");
  this.deathSound = document.getElementById("death-sound");

  var self = this;
  var tick = function() {
    self.move(canvas);
    self.draw(canvas);
    requestAnimationFrame(tick);
  };
  tick();
};

var createBall = function(game, paddle) {
  var ball = [];
  ball.push(new Ball(game, paddle));
  return ball;
}

var createBricks = function(game) {
  var bricks = [];
  for (var i = 0; i < 54; i++) {
    var x = (Math.floor(i / 6)) * 88
    var y = 70 + (i % 6) * 19;
    bricks.push(new Brick(game, {x: x, y: y}));
  };
  return bricks;
}

Game.prototype = {

  move: function(canvas) {
    for (var i = 0; i < this.bodies.length; i++) {
      if (this.bodies[i].move !== undefined) {
        this.bodies[i].move(canvas.canvas);
      }
    }
  },

  draw: function(canvas) {
    canvas.clearRect(0, 0, this.size.x, this.size.y);
    var colorList = new Colors();
    for (var i = 0; i < this.bodies.length; i++) {
      if (this.bodies[i].draw !== undefined) {
        this.bodies[i].draw(canvas, colorList[i].toString());
      }
    }
  }
}

module.exports = Game;<|endoftext|>


<commit_before>var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;

var $ = require('jquery');

var Boat = require('./boat');
var Bullet = require('./bullet');
var bullets = [];
var fishies = require('./fish').fishies;
var collision = require('./collision');
var boat = new Boat({x: canvasWidth/2, y: 25, width: 200, height: 150, velocity: 5, score: 0});
var gameRunning = false;
var round = 1;
var CanvasPainter = require('./canvas-painter');
var canvasPainter = new CanvasPainter(context);
var CanvasMotion = require('./canvas-motion');
var canvasMotion = new CanvasMotion(canvasWidth, canvasHeight);

canvas.addEventListener('keydown', function(key) {
  if (key.which === 37) {
    canvasMotion.moveBoatLeft(boat);
  } else if (key.which === 39) {
    canvasMotion.moveBoatRight(boat, canvasWidth);
  } else if (key.which === 32 && gameRunning) {
    filterBullets();
    addBullet(bullets);
  } else if (key.which === 13 && !gameRunning) {
    beginScoring();
  } else if (key.which === 71 && !gameRunning) {
    game();
  }
});

function drawObjects() {
  canvasPainter.drawOcean();
  canvasPainter.drawFish(fishies);
  canvasPainter.drawBoat(boat);
  canvasPainter.drawBullet(bullets);
}

function moveObjects() {
  canvasMotion.moveFish(fishies, round);
  canvasMotion.moveBullet(bullets);
}

function addBullet(bullets) {
  if (bullets.length === 0) {
    var bullet = new Bullet({}, boat);
    bullets.push(bullet);
  }
}

function filterBullets() {
  bullets = bullets.filter(function(eachBullet){
    return activeBullet(eachBullet);
  });
}

function activeBullet(bullet) {
  if (bullet.y > canvasHeight) {
    return false;
  } else {
    return true;
  }
}

function checkForCollision() {
  fishies.forEach(function(fish) {
    bullets.forEach(function(bullet) {
      if (collision(fish, bullet)) {
        boat.score += fish.y;
        displayScore();
        fishies = fishies.filter(function(eachFish){
          return eachFish !== fish;
        });
      }
    });
  });
}

function beginScoring() {
  gameRunning = true;
  displayRound();
  removeGameStatus();
  gameTimer();
}

function gameTimer() {
  var seconds_left = 8;
  var interval = setInterval(function() {
    document.getElementById('timer').innerHTML = --seconds_left + " seconds";
    if (seconds_left <= 0) {
      document.getElementById('timer').innerHTML = 'Time\'s up!';
      clearInterval(interval);
      gameRunning = false;
      bullets = [];
      nextRound();
    }
  }, 1000);
}

function nextRound() {
  if (boat.score >= 500 && round === 1) {
    round++;
    advanceRound();
    resetRound();
  } else if (boat.score >= 500 && round === 2) {
    round++;
    advanceRound();
    resetRound(round);
  } else if (boat.score >= 500 && round === 3) {
    playerWins();
  } else {
    playerLoses();
  }
}

function advanceRound() {
  document.getElementById('game-status').innerHTML = 'Nice catch! On to the next round';
}

function resetRound(round) {
  fishies = [];
  startGame(round);
  fishies = require('./fish').fishies;
}

function clearScoreAndRound() {
  boat.score = 0;
  round = 1;
  displayScore();
}

function playerWins() {
  clearScoreAndRound();
  document.getElementById('game-status').innerHTML = 'You win!
musta been born on the bayou!

Press Enter to play again!
';
  displayRound();
  resetRound();
  game();
}

function playerLoses() {
  clearScoreAndRound();
  document.getElementById('game-status').innerHTML = 'Shrimpin\' Ain\'t Easy!
Press Enter to play again!';
  resetRound();
  game();
}

function displayScore() {
  document.getElementById('score').innerHTML = "Current Score: " + boat.score.toString();
}

function displayRound() {
  document.getElementById('round').innerHTML = "Round: " + round.toString();
}

function removeGameStatus() {
  if (gameRunning) {
    document.getElementById('game-status').innerHTML = "";
  }
}

function Game() {
  startGame(round);
}

var startGame = function() {
  clearScreen();
  drawObjects();
  moveObjects();
  checkForCollision();
};

function clearScreen() {
  context.clearRect(0, 0, canvas.width, canvas.height);
}

module.exports = Game;
<commit_msg>Converts javascript listeners except for timer to jquery<commit_after>var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;

var $ = require('jquery');

var Boat = require('./boat');
var Bullet = require('./bullet');
var bullets = [];
var fishies = require('./fish').fishies;
var collision = require('./collision');
var boat = new Boat({x: canvasWidth/2, y: 25, width: 200, height: 150, velocity: 5, score: 0});
var gameRunning = false;
var round = 1;
var CanvasPainter = require('./canvas-painter');
var canvasPainter = new CanvasPainter(context);
var CanvasMotion = require('./canvas-motion');
var canvasMotion = new CanvasMotion(canvasWidth, canvasHeight);

canvas.addEventListener('keydown', function(key) {
  if (key.which === 37) {
    canvasMotion.moveBoatLeft(boat);
  } else if (key.which === 39) {
    canvasMotion.moveBoatRight(boat, canvasWidth);
  } else if (key.which === 32 && gameRunning) {
    filterBullets();
    addBullet(bullets);
  } else if (key.which === 13 && !gameRunning) {
    beginScoring();
  } else if (key.which === 71 && !gameRunning) {
    game();
  }
});

var $round = $('#round');
var $score = $('#score');
var $gameStatus = $('#game-status');

function drawObjects() {
  canvasPainter.drawOcean();
  canvasPainter.drawFish(fishies);
  canvasPainter.drawBoat(boat);
  canvasPainter.drawBullet(bullets);
}

function moveObjects() {
  canvasMotion.moveFish(fishies, round);
  canvasMotion.moveBullet(bullets);
}

function addBullet(bullets) {
  if (bullets.length === 0) {
    var bullet = new Bullet({}, boat);
    bullets.push(bullet);
  }
}

function filterBullets() {
  bullets = bullets.filter(function(eachBullet){
    return activeBullet(eachBullet);
  });
}

function activeBullet(bullet) {
  if (bullet.y > canvasHeight) {
    return false;
  } else {
    return true;
  }
}

function checkForCollision() {
  fishies.forEach(function(fish) {
    bullets.forEach(function(bullet) {
      if (collision(fish, bullet)) {
        boat.score += fish.y;
        displayScore();
        fishies = fishies.filter(function(eachFish){
          return eachFish !== fish;
        });
      }
    });
  });
}

function beginScoring() {
  gameRunning = true;
  displayRound();
  removeGameStatus();
  gameTimer();
}

function gameTimer() {
  var seconds_left = 8;
  var interval = setInterval(function() {
    document.getElementById('timer').innerHTML = --seconds_left + " seconds";
    // $('#timer').text(--seconds_left + " seconds");
    if (seconds_left <= 0) {
      document.getElementById('timer').innerHTML = 'Time\'s up!';
      clearInterval(interval);
      gameRunning = false;
      bullets = [];
      nextRound();
    }
  }, 1000);
}

function nextRound() {
  if (boat.score >= 500 && round === 1) {
    round++;
    advanceRound();
    resetRound();
  } else if (boat.score >= 500 && round === 2) {
    round++;
    advanceRound();
    resetRound(round);
  } else if (boat.score >= 500 && round === 3) {
    playerWins();
  } else {
    playerLoses();
  }
}

function advanceRound() {
  $gameStatus.text('Nice catch! On to the next round');
}

function resetRound(round) {
  fishies = [];
  startGame(round);
  fishies = require('./fish').fishies;
}

function clearScoreAndRound() {
  boat.score = 0;
  round = 1;
  displayScore();
}

function playerWins() {
  clearScoreAndRound();
  $gameStatus.html('You win!
musta been born on the bayou!

Press Enter to play again!
');
  displayRound();
  resetRound();
  game();
}

function playerLoses() {
  clearScoreAndRound();
  $gameStatus.html('Shrimpin\' Ain\'t Easy!
Press Enter to play again!');
  resetRound();
  game();
}

function displayScore() {
  $score.text("Current Score: " + boat.score.toString());
}

function displayRound() {
  $round.text("Round: " + round.toString());
}

function removeGameStatus() {
  if (gameRunning) {
    $gameStatus.text("");
  }
}

function Game() {
  startGame(round);
}

var startGame = function() {
  clearScreen();
  drawObjects();
  moveObjects();
  checkForCollision();
};

function clearScreen() {
  context.clearRect(0, 0, canvas.width, canvas.height);
}

module.exports = Game;
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var glob = require('globby');
var debug = require('debug')('lint-deps:glob');
var uniq = require('array-unique');
var mm = require('minimatch');
var invalid = require('./exclusions').invalid;

function arrayify(arr) {
  return !Array.isArray(arr)
    ? [arr]
    : arr;
}

function union(arr) {
  return uniq([].concat.apply([], arguments));
}

module.exports = function(options, fn) {
  debug('glob: %j', options);

  var opts = options || {};
  opts.cwd = opts.cwd || '.';
  opts.patterns = opts.patterns || '*.js';
  opts.exclusions = union(invalid, opts.exclusions || []);

  var files = fs.readdirSync(opts.cwd).filter(function(fp) {
    debug('glob fp: %s', fp);

    if (fn && typeof fn === 'function') {
      return fn(fp, opts);
    }
    return opts.exclusions.indexOf(fp) === -1;
  });

  return files.reduce(function (acc, cwd) {
    if (fs.statSync(cwd).isFile()) {
      var dir = path.dirname(cwd);
      if (dir !== '.') {
        cwd = dir;
      }

      debug('glob cwd: %s', cwd);
      acc = union(acc, opts.patterns.reduce(function (res, pattern) {
        debug('glob pattern: %s', pattern);
        return union(res, mm.match(arrayify(cwd), pattern));
      }, []));
    }

    var res = glob.sync(opts.patterns, {cwd: cwd}).map(function(fp) {
      debug('glob filepath: %s', fp);
      return path.join(cwd, fp);
    });

    return union(acc, res.filter(function(fp) {
      debug('glob filter: %s', fp);
      if (fn && typeof fn === 'function') {
        opts.cwd = cwd;
        return fn(fp, opts);
      }

      return !(new RegExp(opts.exclusions.join('|')).test(fp));
    }));
  }, []);
};
<commit_msg>formatting<commit_after>'use strict';

/**
 * Module dependencies
 */

var fs = require('fs');
var path = require('path');
var glob = require('globby');
var debug = require('debug')('lint-deps:glob');
var uniq = require('array-unique');
var mm = require('minimatch');
var invalid = require('./exclusions').invalid;

/**
 * Expose `glob`
 */

module.exports = function(options, fn) {
  debug('glob: %j', options);

  var opts = options || {};
  opts.cwd = opts.cwd || '.';
  opts.patterns = opts.patterns || '*.js';
  opts.exclusions = union(invalid, opts.exclusions || []);

  var files = fs.readdirSync(opts.cwd).filter(function(fp) {
    debug('glob fp: %s', fp);

    if (fn && typeof fn === 'function') {
      return fn(fp, opts);
    }
    return opts.exclusions.indexOf(fp) === -1;
  });

  return files.reduce(function (acc, cwd) {
    if (fs.statSync(cwd).isFile()) {
      var dir = path.dirname(cwd);
      if (dir !== '.') {
        cwd = dir;
      }

      debug('glob cwd: %s', cwd);
      acc = union(acc, opts.patterns.reduce(function (res, pattern) {
        debug('glob pattern: %s', pattern);
        return union(res, mm.match(arrayify(cwd), pattern));
      }, []));
    }

    var res = glob.sync(opts.patterns, {cwd: cwd}).map(function(fp) {
      debug('glob filepath: %s', fp);
      return path.join(cwd, fp);
    });

    return union(acc, res.filter(function(fp) {
      debug('glob filter: %s', fp);
      if (fn && typeof fn === 'function') {
        opts.cwd = cwd;
        return fn(fp, opts);
      }

      return !(new RegExp(opts.exclusions.join('|')).test(fp));
    }));
  }, []);
};

function arrayify(arr) {
  return !Array.isArray(arr)
    ? [arr]
    : arr;
}

function union() {
  return uniq([].concat.apply([], arguments));
}
<|endoftext|>


<commit_before>'use strict';

var assert = require('expressive-assertion');
var gpio   = require('../build/Release/gpio.node');
var ts     = require('typesystem');

var assertIsPin = function (pin) {
    assert(function () {
        return ts.isInteger(pin);
    }, function () {
        return pin >= 0;
    }, function () {
        return pin <= 53;
    });
};

exports.input = function (pin) {
    assertIsPin(pin);

    gpio.configureAsInput(pin);

    return function () {
        return !!gpio.getLevel(pin);
    };
};

exports.output = function (pin) {
    assertIsPin(pin);

    gpio.configureAsOutput(pin);

    return function (level) {
        gpio.setLevel(pin, !!level);
    };
};
<commit_msg>Improve exports<commit_after>'use strict';

var assert = require('expressive-assertion');
var gpio   = require('../build/Release/gpio.node');
var ts     = require('typesystem');

var assertIsPin = function (pin) {
    assert(function () {
        return ts.isInteger(pin);
    }, function () {
        return pin >= 0;
    }, function () {
        return pin <= 53;
    });
};

var input = function (pin) {
    assertIsPin(pin);

    gpio.configureAsInput(pin);

    return function () {
        return !!gpio.getLevel(pin);
    };
};

var output = function (pin) {
    assertIsPin(pin);

    gpio.configureAsOutput(pin);

    return function (level) {
        gpio.setLevel(pin, !!level);
    };
};

exports.input  = input;
exports.output = output;
<|endoftext|>


<commit_before>var hgotsAdmin = angular.module('HGOTSAdmin', [ 'HGOTSApp', 'HGOTSServices', 'PasswordStrengthView' ]);

hgotsAdmin.service('AdminShared', [ '$http', '$state', 'AppShared', function($http, $state, AppShared) {
  var obj = {
    userTypes: [ 'User', 'Controller', 'Admin' ],
    showUser: function(user) {
      if ( !!user ) {
        console.log("transition");
        $state.transitionTo('admin.user', {
          userId: user.id
        });
      } else {
        $state.transitionTo('admin.welcome');
      }
    },
    currentUser: AppShared.currentUser,

    // variable
    selectedUser: null
  };

  return obj;
}]);
hgotsAdmin.controller('AdminController', [ '$scope', '$stateParams', '$window', '$location', 'User', 'AdminShared', '$state', function($scope, $stateParams, $window, $location, User, AdminShared, $state) {
  $state.transitionTo('admin.welcome');

  $scope.users = User.query(function() {
    if ( !!AdminShared.selectedUser ) {
      console.log(AdminShared.selectedUser);
      var filteredList = $scope.users.filter(function(user) {
        return ( user.id === parseInt(AdminShared.selectedUser.id) );
      });

      if ( filteredList.length === 1 ) {
        AdminShared.selectedUser = filteredList[0];
      } else {
        console.error("User could not be found.");
      }
    }
  });
  $scope.ifSelectedUserStyle = function(user) {
    if ( !!AdminShared.selectedUser ) {
      if ( AdminShared.selectedUser === user ) {
        return "selected-user";
      }
    }

    return "";
  };

  $scope.showUser = function(user) {
    // redirect to page linked to in link, but on element click already
    AdminShared.selectedUser = user;
    AdminShared.showUser(user);
  };

  $scope.userTypeBackgroundStyle = function(user) {
    if ( user.type === "Admin" ) {
      return "bg-primary";
    } else if ( user.type === "Controller" ) {
      return "bg-info";
    }
  };

  $scope.infoPanelStyle = { "margin-top": "0px" };
  // little scroll "hack"
  $($window).on('scroll', function() {
    var oldOffset = parseInt($scope.infoPanelStyle["margin-top"]);
    var newOffset = oldOffset || 0;

    // this needs a certain min width b/c of the responsive layout
    if ( $window.innerWidth >= 992 ) {
      var navbar = $(".navbar");
      var navbarHeight = navbar.height();
      var navbarMarginBottom = parseInt(navbar.css('margin-bottom'));
      var adminInfoPanelHeight = $('.admin-scroll-info').height();

      // a minimum height is required, otherwise the controls hide
      var minHeight = navbarHeight + navbarMarginBottom + adminInfoPanelHeight;

      if ( $window.innerHeight > minHeight ) {
        var scrollY = $window.scrollY;
        //newOffset = ( scrollY > navbarHeight ) ? ( scrollY - navbarHeight ) : 0;
        newOffset = scrollY - navbarHeight;
      }
    }

    newOffset = ( newOffset >= 0 ) ? newOffset : 0;
    if ( newOffset !== oldOffset ) {
      $scope.infoPanelStyle = { "margin-top": newOffset + "px" };
      $scope.$apply();
    }
  });
}]);
<commit_msg>Fixed admin.welcome not displaying url.<commit_after>var hgotsAdmin = angular.module('HGOTSAdmin', [ 'HGOTSApp', 'HGOTSServices', 'PasswordStrengthView' ]);

hgotsAdmin.service('AdminShared', [ '$http', '$state', 'AppShared', function($http, $state, AppShared) {
  var obj = {
    userTypes: [ 'User', 'Controller', 'Admin' ],
    showUser: function(user) {
      if ( !!user ) {
        console.log("transition");
        $state.transitionTo('admin.user', {
          userId: user.id
        });
      } else {
        $state.transitionTo('admin.welcome');
      }
    },
    currentUser: AppShared.currentUser,

    // variable
    selectedUser: null
  };

  return obj;
}]);
hgotsAdmin.controller('AdminController', [ '$scope', '$stateParams', '$window', '$location', 'User', 'AdminShared', '$state', function($scope, $stateParams, $window, $location, User, AdminShared, $state) {
  $scope.users = User.query(function() {
    if ( !!AdminShared.selectedUser ) {
      console.log(AdminShared.selectedUser);
      var filteredList = $scope.users.filter(function(user) {
        return ( user.id === parseInt(AdminShared.selectedUser.id) );
      });

      if ( filteredList.length === 1 ) {
        AdminShared.selectedUser = filteredList[0];
      } else {
        console.error("User could not be found.");
      }
    }
  });
  $scope.ifSelectedUserStyle = function(user) {
    if ( !!AdminShared.selectedUser ) {
      if ( AdminShared.selectedUser === user ) {
        return "selected-user";
      }
    }

    return "";
  };

  $scope.showUser = function(user) {
    // redirect to page linked to in link, but on element click already
    AdminShared.selectedUser = user;
    AdminShared.showUser(user);
  };

  $scope.userTypeBackgroundStyle = function(user) {
    if ( user.type === "Admin" ) {
      return "bg-primary";
    } else if ( user.type === "Controller" ) {
      return "bg-info";
    }
  };

  $scope.infoPanelStyle = { "margin-top": "0px" };
  // little scroll "hack"
  $($window).on('scroll', function() {
    var oldOffset = parseInt($scope.infoPanelStyle["margin-top"]);
    var newOffset = oldOffset || 0;

    // this needs a certain min width b/c of the responsive layout
    if ( $window.innerWidth >= 992 ) {
      var navbar = $(".navbar");
      var navbarHeight = navbar.height();
      var navbarMarginBottom = parseInt(navbar.css('margin-bottom'));
      var adminInfoPanelHeight = $('.admin-scroll-info').height();

      // a minimum height is required, otherwise the controls hide
      var minHeight = navbarHeight + navbarMarginBottom + adminInfoPanelHeight;

      if ( $window.innerHeight > minHeight ) {
        var scrollY = $window.scrollY;
        //newOffset = ( scrollY > navbarHeight ) ? ( scrollY - navbarHeight ) : 0;
        newOffset = scrollY - navbarHeight;
      }
    }

    newOffset = ( newOffset >= 0 ) ? newOffset : 0;
    if ( newOffset !== oldOffset ) {
      $scope.infoPanelStyle = { "margin-top": newOffset + "px" };
      $scope.$apply();
    }
  });
}]);
<|endoftext|>


<commit_before>var util = require('util');
var RedisKey = require('./Key');
var wrapRedisMethod = require('./utils/wrapRedisMethod');

module.exports = RedisHash;

function RedisHash (key, opts) {
  return RedisKey.apply(this, arguments);
}

util.inherits(RedisHash, RedisKey);

[
  "HDEL",
  "HEXISTS",
  "HGET",
  "HGETALL",
  "HINCRBY",
  "HINCRBYFLOAT",
  "HKEYS",
  "HLEN",
  "HMGET",
  "HMSET",
  "HSET",
  "HSETNX",
  "HVALS",
  "HSCAN"
].forEach(wrapRedisMethod(RedisHash));

// Same without H
[
  "DEL",
  "EXISTS",
  "GET",
  "GETALL",
  "INCRBY",
  "INCRBYFLOAT",
  "KEYS",
  "LEN",
  "MGET",
  "MSET",
  "SET",
  "SETNX",
  "VALS",
  "SCAN"
].forEach(function (command) {
  RedisHash.prototype[command] = RedisHash.prototype['H'+command];
  var lower = command.toLowerCase();
  RedisHash.prototype[lower] = RedisHash.prototype['h'+lower];
});<commit_msg>remove del shortcut from hash<commit_after>var util = require('util');
var RedisKey = require('./Key');
var wrapRedisMethod = require('./utils/wrapRedisMethod');

module.exports = RedisHash;

function RedisHash (key, opts) {
  return RedisKey.apply(this, arguments);
}

util.inherits(RedisHash, RedisKey);

[
  "HDEL",
  "HEXISTS",
  "HGET",
  "HGETALL",
  "HINCRBY",
  "HINCRBYFLOAT",
  "HKEYS",
  "HLEN",
  "HMGET",
  "HMSET",
  "HSET",
  "HSETNX",
  "HVALS",
  "HSCAN"
].forEach(wrapRedisMethod(RedisHash));

// Same without H
[
  // "DEL", conflict with Key.DEL
  "EXISTS",
  "GET",
  "GETALL",
  "INCRBY",
  "INCRBYFLOAT",
  "KEYS",
  "LEN",
  "MGET",
  "MSET",
  "SET",
  "SETNX",
  "VALS",
  "SCAN"
].forEach(function (command) {
  RedisHash.prototype[command] = RedisHash.prototype['H'+command];
  var lower = command.toLowerCase();
  RedisHash.prototype[lower] = RedisHash.prototype['h'+lower];
});<|endoftext|>


<commit_before>
// A Hash is an interable object
var Hash = module.exports = Object.create(Object.prototype, {
  // Make for easy converting objects to hashes.
  new: {value: function (value) {
    value = value || {};
    value.__proto__ = Hash;
    return value;
  }},
  // Implements a forEach much like the one for Array.prototype.forEach.
  forEach: {value: function forEach(callback, thisObject) {
    var keys = Object.keys(this),
        length = keys.length;
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      callback.call(thisObject, this[key], key, this);
    }
  }},
  // Implements a map much like the one for Array.prototype.map.
  // Returns a normal Array instance.
  map: {value: function map(callback, thisObject) {
    var keys = Object.keys(this),
        length = keys.length,
        accum = new Array(length);
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      accum[i] = callback.call(thisObject, this[key], key, this);
    }
    return accum;
  }},
  length: {get: function length() {
    return Object.keys(this).length;
  }}
});
Object.freeze(Hash);
<commit_msg>Minor optimization for Hash<commit_after>
// A Hash is an interable object
var Hash = module.exports = Object.create(Object.prototype, {
  // Make for easy converting objects to hashes.
  new: {value: function (value) {
    if (value === undefined) return Object.create(Hash);
    value.__proto__ = Hash;
    return value;
  }},
  // Implements a forEach much like the one for Array.prototype.forEach.
  forEach: {value: function forEach(callback, thisObject) {
    var keys = Object.keys(this),
        length = keys.length;
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      callback.call(thisObject, this[key], key, this);
    }
  }},
  // Implements a map much like the one for Array.prototype.map.
  // Returns a normal Array instance.
  map: {value: function map(callback, thisObject) {
    var keys = Object.keys(this),
        length = keys.length,
        accum = new Array(length);
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      accum[i] = callback.call(thisObject, this[key], key, this);
    }
    return accum;
  }},
  length: {get: function length() {
    return Object.keys(this).length;
  }}
});
Object.freeze(Hash);
<|endoftext|>


<commit_before>var app = require('./app'),
  pkg = require('../package.json'),
  chalk = require('chalk');

module.exports = {
  showHelp: function(command) {
    switch (command) {

      case 'download':
        console.log('\n' +
                    '  stamplay download\n' +
                    '    Download the current active version of an app,\n' +
                    '\n' +
                    '    You will be prompted to type appId and apiKey, if you don\'t have it\n' +
                    '    go into your app on https://editor.stamplay.com and get them' +
                    '    under Backend -> ApiKey section.\n');
        break;

      case 'deploy':
        console.log('\n' +
                    '  stamplay deploy\n' +
                    '    Deploys the current app to Stamplay and creates a new version,\n' +
                    '\n' +
                    '    Uploads the directory detailed by the "public" attribute in the\n' +
                    '    stamplay.json settings file under. The app must contain an entry point file\n' +
                    '    called index.html at root level of your public directory. If no file\n' +
                    '    is found you\'ll be prompted to create it.\n');
        break;

      case 'start':
        console.log('\n' +
                    '  stamplay start\n' +
                    '    Start serving your app on your localhost\n' +
                    '    the public folder will be served at the following address http://localhost:8080.\n');
        break;

      case 'open':
        console.log('\n' +
                    '  stamplay open\n' +
                    '    Opens the current Stamplay app\'s stamplayapp.com subdomain in a browser.\n');
        break;

      case 'init':
        console.log('\n' +
                    '  stamplay init\n' +
                    '   Initializes an existing Stamplay app in the current directory and prompts \n' +
                    '   you to configuring it for stamplayapp.com. \n' +
                    '\n'+
                    '   Running stamplay init in an existing repository is safe. It will not \n' +
                    '   overwrite things that are already there.  It only Generates a \n' +
                    '   stamplay.json file in the current directory with all the settings \n' +
                    '   required to deploy it. If you don\'t have appId and apiKey yet \n' +
                    '   open https://editor.stamplay.com and create a new app.\n');

        break;

      default:
        this.showVersion();
        console.log('Usage: stamplay <command>\n' +
                    '\n' +
                    '  Available commands are:\n' +
                    '\n' +
                    '  deploy\n' +
                    '    Deploys a new version of the current app to Stamplay\n' +
                    '\n' +
                    '  download\n' +
                    '    Download the current active version of an app,\n' +
                    '    You will be prompted to type appId and apiKey, if you don\'t have it\n' +
                    '    go into your app on https://editor.stamplay.com and get them' +
                    '    under Backend -> ApiKey section.\n' +
                    '\n' +
                    '  init\n' +
                    '    Initialize your project and make it ready to be deployed on Stamplay. Run this command into your project folder.\n' +
                    '    The command will prompt you for AppId and Api Key.\n' +
                    '\n' +
                    '  open\n' +
                    '    Opens the URL of the current Stamplay app in a browser.\n' +
                    '\n' +
                    '  start\n' +
                    '    Run your app in your localhost on http://localhost:8080\n' +
                    '\n' +
                    '  -h, --help\n' +
                    '    Shows this help screen. Use `stamplay <command> --help` for more detailed\n' +
                    '    help instructions.\n' +
                    '\n' +
                    '  -v, --version\n' +
                    '    Displays the current version.\n' +
                    '\n' +
                    'For a quick start guide, see https://stamplay.com\n');

        break;

    }
  },
  showVersion: function() {
    console.log('\n' + 'Stamplay Command Line \nVersion ' + pkg.version + '\n');
    }
};<commit_msg>fix type<commit_after>var app = require('./app'),
  pkg = require('../package.json'),
  chalk = require('chalk');

module.exports = {
  showHelp: function(command) {
    switch (command) {

      case 'download':
        console.log('\n' +
                    '  stamplay download\n' +
                    '    Download the current active version of an app.\n' +
                    '\n' +
                    '    You will be prompted to type appId and apiKey, if you don\'t have it\n' +
                    '    go into your app on https://editor.stamplay.com and get them' +
                    '    under Backend -> ApiKey section.\n');
        break;

      case 'deploy':
        console.log('\n' +
                    '  stamplay deploy\n' +
                    '    Deploys the current app to Stamplay and creates a new version.\n' +
                    '\n' +
                    '    Uploads the directory detailed by the "public" attribute in the\n' +
                    '    stamplay.json settings file under. The app must contain an entry point file\n' +
                    '    called index.html at root level of your public directory. If no file\n' +
                    '    is found you\'ll be prompted to create it.\n');
        break;

      case 'start':
        console.log('\n' +
                    '  stamplay start\n' +
                    '    Start serving your app on your localhost\n' +
                    '    the public folder will be served at the following address http://localhost:8080.\n');
        break;

      case 'open':
        console.log('\n' +
                    '  stamplay open\n' +
                    '    Opens the current Stamplay app\'s stamplayapp.com subdomain in a browser.\n');
        break;

      case 'init':
        console.log('\n' +
                    '  stamplay init\n' +
                    '   Initializes an existing Stamplay app in the current directory and prompts \n' +
                    '   you to configuring it for stamplayapp.com. \n' +
                    '\n'+
                    '   Running stamplay init in an existing repository is safe. It will not \n' +
                    '   overwrite things that are already there.  It only Generates a \n' +
                    '   stamplay.json file in the current directory with all the settings \n' +
                    '   required to deploy it. If you don\'t have appId and apiKey yet \n' +
                    '   open https://editor.stamplay.com and create a new app.\n');

        break;

      default:
        this.showVersion();
        console.log('Usage: stamplay <command>\n' +
                    '\n' +
                    '  Available commands are:\n' +
                    '\n' +
                    '  deploy\n' +
                    '    Deploys a new version of the current app to Stamplay.\n' +
                    '\n' +
                    '  download\n' +
                    '    Download the current active version of an app,\n' +
                    '    You will be prompted to type appId and apiKey, if you don\'t have it\n' +
                    '    go into your app on https://editor.stamplay.com and get them' +
                    '    under Backend -> ApiKey section.\n' +
                    '\n' +
                    '  init\n' +
                    '    Initialize your project and make it ready to be deployed on Stamplay. Run this command into your project folder.\n' +
                    '    The command will prompt you for AppId and Api Key.\n' +
                    '\n' +
                    '  open\n' +
                    '    Opens the URL of the current Stamplay app in a browser.\n' +
                    '\n' +
                    '  start\n' +
                    '    Run your app in your localhost on http://localhost:8080\n' +
                    '\n' +
                    '  -h, --help\n' +
                    '    Shows this help screen. Use `stamplay <command> --help` for more detailed\n' +
                    '    help instructions.\n' +
                    '\n' +
                    '  -v, --version\n' +
                    '    Displays the current version.\n' +
                    '\n' +
                    'For a quick start guide, see https://stamplay.com\n');

        break;

    }
  },
  showVersion: function() {
    console.log('\n' + 'Stamplay Command Line \nVersion ' + pkg.version + '\n');
    }
};<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-2017 Guyon Roche
 * LICENCE: MIT - please refer to LICENCE file included with this module
 * or https://github.com/guyonroche/exceljs/blob/master/LICENSE
 */

'use strict';

var utils = require('../../../utils/utils');
var colCache = require('../../../utils/col-cache');
var BaseXform = require('../base-xform');
var StaticXform = require('../static-xform');

var CellPositionXform = require('./cell-position-xform');
var PicXform = require('./pic-xform');

var TwoCellAnchorXform = module.exports = function() {
  this.map = {
    'xdr:from': new CellPositionXform({tag: 'xdr:from'}),
    'xdr:to': new CellPositionXform({tag: 'xdr:to'}),
    'xdr:pic': new PicXform(),
    'xdr:clientData': new StaticXform({tag: 'xdr:clientData'}),
  };
};

utils.inherits(TwoCellAnchorXform, BaseXform, {
  get tag() { return 'xdr:twoCellAnchor'; },

  prepare: function(model, options) {
    this.map['xdr:pic'].prepare(model.picture, options);

    // convert model.range into tl, br
    if (typeof model.range === 'string') {
      var range = colCache.decode(model.range);
      // Note - zero based
      model.tl = {
        col: range.left - 1,
        row: range.top - 1,
      };
      // zero based but also +1 to cover to bottom right of br cell
      model.br = {
        col: range.right,
        row: range.bottom
      };
    } else {
      model.tl = model.range.tl;
      model.br = model.range.br;
    }
  },

  render: function(xmlStream, model) {
    xmlStream.openNode(this.tag);

    this.map['xdr:from'].render(xmlStream, model.tl);
    this.map['xdr:to'].render(xmlStream, model.br);
    this.map['xdr:pic'].render(xmlStream, model.picture);
    this.map['xdr:clientData'].render(xmlStream, {});

    xmlStream.closeNode();
  },

  parseOpen: function(node) {
    if (this.parser) {
      this.parser.parseOpen(node);
      return true;
    }
    switch (node.name) {
      case this.tag:
        this.reset();
        break;
      default:
        this.parser = this.map[node.name];
        if (this.parser) {
          this.parser.parseOpen(node);
        }
        break;
    }
    return true;
  },

  parseText: function(text) {
    if (this.parser) {
      this.parser.parseText(text);
    }
  },

  parseClose: function(name) {
    if (this.parser) {
      if (!this.parser.parseClose(name)) {
        this.parser = undefined;
      }
      return true;
    }
    switch (name) {
      case this.tag:
        this.model = {
          tl: this.map['xdr:from'].model,
          br: this.map['xdr:to'].model,
          picture: this.map['xdr:pic'].model,
        };
        return false;
      default:
        // could be some unrecognised tags
        return true;
    }
  },

  reconcile: function(model, options) {
    var rel = options.rels[model.picture.rId];
    var match = rel.Target.match(/.*\/media\/(.+[.][a-z]{3,4})/);
    if (match) {
      var name = match[1];
      var mediaId = options.mediaIndex[name];
      model.medium = options.media[mediaId];
    }
    if (Number.isInteger(model.tl.row) && Number.isInteger(model.tl.col) && Number.isInteger(model.br.row) && Number.isInteger(model.br.col)) {
      model.range = colCache.encode(model.tl.row + 1, model.tl.col + 1, model.br.row, model.br.col);
    } else {
      model.range = {
        tl: model.tl,
        br: model.br,
      };
    }
    delete model.tl;
    delete model.br;
  }
});
<commit_msg>Add guards to reconcile<commit_after>/**
 * Copyright (c) 2016-2017 Guyon Roche
 * LICENCE: MIT - please refer to LICENCE file included with this module
 * or https://github.com/guyonroche/exceljs/blob/master/LICENSE
 */

'use strict';

var utils = require('../../../utils/utils');
var colCache = require('../../../utils/col-cache');
var BaseXform = require('../base-xform');
var StaticXform = require('../static-xform');

var CellPositionXform = require('./cell-position-xform');
var PicXform = require('./pic-xform');

var TwoCellAnchorXform = module.exports = function() {
  this.map = {
    'xdr:from': new CellPositionXform({tag: 'xdr:from'}),
    'xdr:to': new CellPositionXform({tag: 'xdr:to'}),
    'xdr:pic': new PicXform(),
    'xdr:clientData': new StaticXform({tag: 'xdr:clientData'}),
  };
};

utils.inherits(TwoCellAnchorXform, BaseXform, {
  get tag() { return 'xdr:twoCellAnchor'; },

  prepare: function(model, options) {
    this.map['xdr:pic'].prepare(model.picture, options);

    // convert model.range into tl, br
    if (typeof model.range === 'string') {
      var range = colCache.decode(model.range);
      // Note - zero based
      model.tl = {
        col: range.left - 1,
        row: range.top - 1,
      };
      // zero based but also +1 to cover to bottom right of br cell
      model.br = {
        col: range.right,
        row: range.bottom
      };
    } else {
      model.tl = model.range.tl;
      model.br = model.range.br;
    }
  },

  render: function(xmlStream, model) {
    xmlStream.openNode(this.tag);

    this.map['xdr:from'].render(xmlStream, model.tl);
    this.map['xdr:to'].render(xmlStream, model.br);
    this.map['xdr:pic'].render(xmlStream, model.picture);
    this.map['xdr:clientData'].render(xmlStream, {});

    xmlStream.closeNode();
  },

  parseOpen: function(node) {
    if (this.parser) {
      this.parser.parseOpen(node);
      return true;
    }
    switch (node.name) {
      case this.tag:
        this.reset();
        break;
      default:
        this.parser = this.map[node.name];
        if (this.parser) {
          this.parser.parseOpen(node);
        }
        break;
    }
    return true;
  },

  parseText: function(text) {
    if (this.parser) {
      this.parser.parseText(text);
    }
  },

  parseClose: function(name) {
    if (this.parser) {
      if (!this.parser.parseClose(name)) {
        this.parser = undefined;
      }
      return true;
    }
    switch (name) {
      case this.tag:
        this.model = {
          tl: this.map['xdr:from'].model,
          br: this.map['xdr:to'].model,
          picture: this.map['xdr:pic'].model,
        };
        return false;
      default:
        // could be some unrecognised tags
        return true;
    }
  },

  reconcile: function(model, options) {
    if (model.picture && model.picture.rId) {
      var rel = options.rels[model.picture.rId];
      var match = rel.Target.match(/.*\/media\/(.+[.][a-z]{3,4})/);
      if (match) {
        var name = match[1];
        var mediaId = options.mediaIndex[name];
        model.medium = options.media[mediaId];
      }
    }
    if (model.tl && Number.isInteger(model.tl.row) && Number.isInteger(model.tl.col) && Number.isInteger(model.br.row) && Number.isInteger(model.br.col)) {
      model.range = colCache.encode(model.tl.row + 1, model.tl.col + 1, model.br.row, model.br.col);
    } else {
      model.range = {
        tl: model.tl,
        br: model.br,
      };
    }
    delete model.tl;
    delete model.br;
  }
});
<|endoftext|>


<commit_before>"use strict";

// this is a basic wrapper for making Request() requests
//  we wrap this so we can have the same debug information for all requests

const needle = require("needle");

// get our project Log function for writing log output
const Log = require("./debugPrint");

/**
 * Make a network request
 * @private
 * @param parameters to pass to request library
 */
function MakeRequest(networkRequest) {
    if (arguments.length != 1) {
        return Promise.reject("HTTP requires 1 argument. The network object configuration");
    }

    // debug log if we're in debug mode
    Log(`Making request to ${networkRequest.url}`);

    // grab method from the request (we'll call .[method] directly using the needle library)
    const requestMethod = networkRequest.method || "get";
    delete networkRequest.method;

    // extract the required URL
    const requestURL = networkRequest.url;
    if (!requestURL) return Promise.reject(`No URL defined for ${requestMethod} request`);
    delete networkRequest.url;

    const requestData = networkRequest.data || networkRequest.body || {};
    delete networkRequest.data;
    delete networkRequest.body;

    // build-in retires into this wrapper (default 3)
    const retries = networkRequest.retries || 3;
    // un-set retries in-case request suddenly supports this or something!
    delete networkRequest.retries;

    // default delay of 2 seconds for each retry attempt
    const retryDelay = networkRequest.retryDelay || 2000;
    delete networkRequest.retryDelay;

    // we will default to returning the body, but can return the full response object if we want
    const returnFullResponse = networkRequest.returnFullResponse || false;
    delete networkRequest.returnFullResponse;

    // add ability to force responses into JSON objects, even if they don't return application/json content header
    let forceJSON = networkRequest.forceJSON || false;
    delete networkRequest.forceJSON;

    // return result as a Promise!
    return new Promise((resolve, reject) => {
        let attempt = 0;

        // make request in an anonymouse function so we can make multiple requests to it easily
        const attemptRequest = function() {
            Log(`Calling ${requestMethod}:${requestURL}`);

            // build Needle request
            needle.request(requestMethod, requestURL, requestData, networkRequest, function(err, resp) {
                if (err || resp.statusCode >= 400 || (resp.statusCode == 200 && !resp.body)) {
                    Log(`Network request failed attempt ${attempt}/${retries} for URL ${requestURL}`);
                    Log(err || (resp.statusCode + ": " + JSON.stringify(resp.body, null, 2)));

                    // if we have retires left, try again!
                    attempt++;
                    if (attempt < retries) {
                        // try again after retryDelay milliseconds
                        setTimeout(attemptRequest, retryDelay);
                        return;
                    } else {
                        return reject(err || (resp.statusCode + ": " + JSON.stringify(resp.body, null, 2)));
                    }
                }

                // no error! return the result
                if (returnFullResponse) {
                    Log(`Successfully fetched response for URL ${requestURL}`);
                    return resolve(resp);
                } else {
                    // enable "forceJSON" if the return header type is "application/json"
                    if (resp.headers && resp.headers["content-type"] && resp.headers["content-type"].indexOf("application/json") >= 0) {
                        Log("Found 'application/json' header from in HTTP request, parsing JSON data");
                        forceJSON = true;
                    }

                    // if we want to force JSON (and we're not already a JSON object!)
                    if (forceJSON && resp.body.constructor !== {}.constructor && resp.body.constructor !== [].constructor) {
                        let JSONData;
                        try {
                            JSONData = JSON.parse(resp.body);
                        } catch (e) {
                            return reject(`Unable to parse ${resp.body} into a JSON object: ${e}`);
                        }
                        Log(`Successfully fetched and parsed JSON from response at ${requestURL}`);
                        return resolve(JSONData);
                    } else {
                        Log(`Successfully fetched body for URL ${requestURL}`);
                        return resolve(resp.body);
                    }
                }
            });
        };

        // make first request attempt
        process.nextTick(attemptRequest);
    });
}

module.exports = MakeRequest;<commit_msg>[+] Add basis of a mock request system, so we can replay data offline<commit_after>"use strict";

// this is a basic wrapper for making Request() requests
//  we wrap this so we can have the same debug information for all requests

const needle = require("needle");

// get our project Log function for writing log output
const Log = require("./debugPrint");

const util = require("util");

// fs lib for writing/reading mock requests
const fs = require("fs");
const fsExists = util.promisify(fs.exists);
const fsReadFile = util.promisify(fs.readFile);
const fsWriteFile = util.promisify(fs.writeFile);

function GetMockFilename(mockName) {
    return __dirname + "/mocks/" + mockName + ".mock";
}

function SetMock(mockName, response) {
    // only store mock responses if THEMEPARKS_MOCKWRITE is set
    if (!process.env.THEMEPARKS_MOCKWRITE) return Promise.resolve(response);

    return fsWriteFile(GetMockFilename(mockName), JSON.stringify(response)).then(() => {
        // always return the actual response object for Promise chaining
        return Promise.resolve(response);
    });
}

function GetMock(mockName) {
    // return undefined result if we're not in mock mode
    if (!process.env.THEMEPARKS_MOCK) return Promise.resolve();

    const filename = GetMockFilename(mockName);
    return fsExists(filename).then(exists => {
        if (!exists) {
            // file doesn't exist! return undefined
            return Promise.resolve();
        }

        // read the file
        return fsReadFile(filename).then((data) => {
            let JSONData = null;
            try {
                JSONData = JSON.parse(data);
            } catch (e) {
                Log(`Failed to read mock file JSON ${mockName}`);
            }

            if (JSONData === null) {
                return Promise.resolve();
            }

            return Promise.resolve(JSONData);
        });
    });
}

/**
 * Make a network request
 * @private
 * @param parameters to pass to request library
 */
function MakeRequest(networkRequest) {
    if (arguments.length != 1) {
        return Promise.reject("HTTP requires 1 argument. The network object configuration");
    }

    return GetMock(networkRequest.mock).then((mockData) => {
        if (mockData !== undefined) {
            Log(`Returning mock request for ${networkRequest.mock}`);
            return Promise.resolve(mockData);
        }

        // debug log if we're in debug mode
        Log(`Making request to ${networkRequest.url}`);

        // grab method from the request (we'll call .[method] directly using the needle library)
        const requestMethod = networkRequest.method || "get";
        delete networkRequest.method;

        // extract the required URL
        const requestURL = networkRequest.url;
        if (!requestURL) return Promise.reject(`No URL defined for ${requestMethod} request`);
        delete networkRequest.url;

        const requestData = networkRequest.data || networkRequest.body || {};
        delete networkRequest.data;
        delete networkRequest.body;

        // build-in retires into this wrapper (default 3)
        const retries = networkRequest.retries || 3;
        // un-set retries in-case request suddenly supports this or something!
        delete networkRequest.retries;

        // default delay of 2 seconds for each retry attempt
        const retryDelay = networkRequest.retryDelay || 2000;
        delete networkRequest.retryDelay;

        // we will default to returning the body, but can return the full response object if we want
        const returnFullResponse = networkRequest.returnFullResponse || false;
        delete networkRequest.returnFullResponse;

        // add ability to force responses into JSON objects, even if they don't return application/json content header
        let forceJSON = networkRequest.forceJSON || false;
        delete networkRequest.forceJSON;

        // return result as a Promise!
        return new Promise((resolve, reject) => {
            let attempt = 0;

            // make request in an anonymous function so we can make multiple requests to it easily
            const attemptRequest = () => {
                Log(`Calling ${requestMethod}:${requestURL}`);

                // build Needle request
                needle.request(requestMethod, requestURL, requestData, networkRequest, (err, resp) => {
                    if (err || resp.statusCode >= 400 || (resp.statusCode == 200 && !resp.body)) {
                        Log(`Network request failed attempt ${attempt}/${retries} for URL ${requestURL}`);
                        Log(err || (resp.statusCode + ": " + JSON.stringify(resp.body, null, 2)));

                        // if we have retires left, try again!
                        attempt++;
                        if (attempt < retries) {
                            // try again after retryDelay milliseconds
                            setTimeout(attemptRequest, retryDelay);
                            return;
                        } else {
                            return reject(err || (resp.statusCode + ": " + JSON.stringify(resp.body, null, 2)));
                        }
                    }

                    // no error! return the result
                    if (returnFullResponse) {
                        Log(`Successfully fetched response for URL ${requestURL}`);
                        return SetMock(networkRequest.mock, resp).then(resolve);
                    } else {
                        // enable "forceJSON" if the return header type is "application/json"
                        if (resp.headers && resp.headers["content-type"] && resp.headers["content-type"].indexOf("application/json") >= 0) {
                            Log("Found 'application/json' header from in HTTP request, parsing JSON data");
                            forceJSON = true;
                        }

                        // if we want to force JSON (and we're not already a JSON object!)
                        if (forceJSON && resp.body.constructor !== {}.constructor && resp.body.constructor !== [].constructor) {
                            let JSONData;
                            try {
                                JSONData = JSON.parse(resp.body);
                            } catch (e) {
                                return reject(`Unable to parse ${resp.body} into a JSON object: ${e}`);
                            }
                            Log(`Successfully fetched and parsed JSON from response at ${requestURL}`);
                            return SetMock(networkRequest.mock, JSONData).then(resolve);
                        } else {
                            Log(`Successfully fetched body for URL ${requestURL}`);
                            return SetMock(networkRequest.mock, resp.body).then(resolve);
                        }
                    }
                });
            };

            // make first request attempt
            process.nextTick(attemptRequest);
        });
    });
}

module.exports = MakeRequest;<|endoftext|>