<commit_before>var this$1=this,Template=function(t){function e(t){var e=this;t=Array.isArray(t)?t:[t];var n=[],i=t.map(function(){return e.content.cloneNode(!0)}).map(r,n);this.innerHTML="";for(var c=0,u=i;c<u.length;c+=1){var a=u[c];e.content.appendChild(a)}return t.map(o,n)&&this}function n(t){return document.querySelector("template[name="+t+"]").cloneNode(!0)||document.createElement("template")}function r(t){var e=function(t){return t.reduce(function(t,e){return(t[e.textContent.match(/{(.+)}/)[1]]=e)&&t},{})};return this.push(e(tokenize(t)))&&t}function o(t,e){var n=this;for(var r in t)n[e][r]&&(n[e][r].textContent=t[r])}return void 0===t&&(t="snuggsi"),Object.assign(n.apply(void 0,t),{bind:e})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.listen=function(t,e){void 0===e&&(e="on"+this$1[t]),this.addEventListener(t,e)},e}(t)},TokenList=function(t){var e=this,n=function(t){return t.match(/(\w+)/g)[0]},r=function(t){return function(n){return e[n]=t}},o=function(t){return t.textContent.match(/{(\w+)}/g).map(n).map(r(t))},i=function(t){return(t.text=t.data)&&t};t.map(i).map(o)};TokenList.prototype.bind=function(t,e){var n=this;for(var r in n)e=n[r],e.data=e.text;for(var o in n)e=n[o],e.data=e.data.replace("{"+o+"}",t[o]);return this};var ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={texts:{},tokens:{}};return e.prototype.selectAll=function(t){return this.listenable(this.querySelectorAll(t))},e.prototype.select=function(t){return this.selectAll(t)[0]},n.texts.get=function(){for(var t,e=function(t,e){return void 0===e&&(e=/({\w+})/g),e.exec(t.data)&&NodeFilter.FILTER_ACCEPT},n=document.createNodeIterator(this,NodeFilter.SHOW_TEXT,e),r=[];t=n.nextNode();)r.push(t);return r},n.tokens.get=function(){return this._tokens||(this._tokens=new TokenList(this.texts))},Object.defineProperties(e.prototype,n),e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.call(this)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.mirror=function(e){var n=this;return Object.getOwnPropertyNames(t).filter(e).forEach(function(e){return!n[e]&&(n[e]=t[e])}),this},e.prototype.register=function(e){var n=this,r=":not(script):not(template):not(style):not(link)",o=Array.from(this.querySelectorAll(r)),i=function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).length>0},c=function(e,n){return void 0===n&&(n=(/{\s*(\w+)\s*}/.exec(e)||[])[1]),n&&t[n]||e||null},u=function(){return function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).filter(function(t){return void 0!==n[t]}).map(a(t))}},a=function(t){return function(e){t[e]=c(t[e])}}[this].concat(o).filter(i).map(u(this));return this},e}(t)};console.log("wtf"),console.warn("Finally");var ElementPrototype=window.Element.prototype,Element=function(t,e){return void 0===t&&(t=Array.isArray(arguments[0])?arguments[0][0]:arguments[0]),void 0===e&&(e=window.customElements),console.warn(arguments),function(n,r){void 0===r&&(r=this===window&&this||{});var o=function(t){function e(){t.call(this),t.prototype.initialize.call(this)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={context:{},templates:{}};return n.context.get=function(){return r},n.context.set=function(t){r=t},n.templates.get=function(){return this.selectAll("template")},e.prototype.render=function(){this.tokens.bind(this.context)},e.prototype.connectedCallback=function(){void(t.prototype.constructor.onconnect||t.prototype.connectedCallback||function(){}).call(this),this.render()},Object.defineProperties(e.prototype,n),e}(ParentNode(EventTarget(GlobalEventHandlers(n))));try{e.define(t,o)}finally{return e.get(t)}}};Element.prototype=ElementPrototype;<commit_msg>Update distribution for snuggsi.min.js<commit_after>var this$1=this,Template=function(t){function e(t){var e=this;t=Array.isArray(t)?t:[t];var n=[],i=t.map(function(){return e.content.cloneNode(!0)}).map(r,n);this.innerHTML="";for(var c=0,u=i;c<u.length;c+=1){var a=u[c];e.content.appendChild(a)}return t.map(o,n)&&this}function n(t){return document.querySelector("template[name="+t+"]").cloneNode(!0)||document.createElement("template")}function r(t){var e=function(t){return t.reduce(function(t,e){return(t[e.textContent.match(/{(.+)}/)[1]]=e)&&t},{})};return this.push(e(tokenize(t)))&&t}function o(t,e){var n=this;for(var r in t)n[e][r]&&(n[e][r].textContent=t[r])}return void 0===t&&(t="snuggsi"),Object.assign(n.apply(void 0,t),{bind:e})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.listen=function(t,e){void 0===e&&(e="on"+this$1[t]),this.addEventListener(t,e)},e}(t)},TokenList=function(t){var e=this,n=function(t){return t.text=t.data,t},r=function(t){return t.match(/(\w+)/g)[0]},o=function(t){return function(n){return e[n]=t}},i=function(t){return t.textContent.match(/{(\w+)}/g).map(r).map(o(t))};t.map(n).map(i)};TokenList.prototype.bind=function(t,e){var n=this;for(var r in n)e=n[r],e.data=e.text;for(var o in n)e=n[o],e.data=e.data.replace("{"+o+"}",t[o]);return this};var ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={texts:{},tokens:{}};return e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},n.texts.get=function(){for(var t,e=function(t,e){return void 0===e&&(e=/({\w+})/g),e.exec(t.data)&&NodeFilter.FILTER_ACCEPT},n=document.createNodeIterator(this,NodeFilter.SHOW_TEXT,e),r=[];t=n.nextNode();)r.push(t);return r},n.tokens.get=function(){return this._tokens=this._tokens||new TokenList(this.texts)},Object.defineProperties(e.prototype,n),e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.call(this)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.mirror=function(e){var n=this;return Object.getOwnPropertyNames(t).filter(e).forEach(function(e){return!n[e]&&(n[e]=t[e])}),this},e.prototype.register=function(e){var n=this,r=":not(script):not(template):not(style):not(link)",o=Array.from(this.querySelectorAll(r)),i=function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).length>0},c=function(e,n){return void 0===n&&(n=(/{\s*(\w+)\s*}/.exec(e)||[])[1]),n&&t[n]||e||null},u=function(){return function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).filter(function(t){return void 0!==n[t]}).map(a(t))}},a=function(t){return function(e){t[e]=c(t[e])}}[this].concat(o).filter(i).map(u(this));return this},e}(t)},ElementPrototype=window.Element.prototype,Element=function(t,e){return void 0===e&&(e=window.customElements),t=t[0],function(n,r){void 0===r&&(r=this===window?this:{});var o=function(t){function e(){t.call(this),t.prototype.initialize&&t.prototype.initialize.call(this)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={context:{},templates:{}};return n.context.get=function(){return r},n.context.set=function(t){r=t},n.templates.get=function(){return this.selectAll("template")},e.prototype.render=function(){},e.prototype.connectedCallback=function(){void(t.prototype.constructor.onconnect||t.prototype.connectedCallback||function(){}).call(this),this.render()},Object.defineProperties(e.prototype,n),e}(ParentNode(EventTarget(GlobalEventHandlers(n))));return e.define(t,o),e.get(t)}};Element.prototype=ElementPrototype;<|endoftext|>


<commit_before>define(['sorttable', 'snabbdom', 'd3-interpolate', 'helper', 'utils/node'],
  function (SortTable, V, d3Interpolate, helper, nodef) {
    'use strict';
    V = V.default;

    function showStatImg(o, d) {
      var subst = {
        '{NODE_ID}': d.node_id,
        '{NODE_NAME}': d.hostname.replace(/[^a-z0-9\-]/ig, '_'),
        '{TIME}': d.lastseen.format('DDMMYYYYHmmss'),
        '{LOCALE}': _.locale()
      };
      return helper.showStat(V, o, subst);
    }

    return function (el, d, linkScale, nodeDict) {
      function nodeLink(node) {
        return V.h('a', {
          props: {
            className: node.is_online ? 'online' : 'offline',
            href: router.generateLink({ node: node.node_id })
          }, on: {
            click: function (e) {
              router.fullUrl({ node: node.node_id }, e);
            }
          }
        }, node.hostname);
      }

      function nodeIdLink(nodeId) {
        if (nodeDict[nodeId]) {
          return nodeLink(nodeDict[nodeId]);
        }
        return nodeId;
      }

      function showGateway(node) {
        var gatewayCols = [
          V.h('span', [
            nodeIdLink(node.gateway_nexthop),
            V.h('br'),
            _.t('node.nexthop')
          ]),
          V.h('span', { props: { className: 'ion-arrow-right-c' } }),
          V.h('span', [
            nodeIdLink(node.gateway),
            V.h('br'),
            'IPv4'
          ])
        ];

        if (node.gateway6 !== undefined) {
          gatewayCols.push(V.h('span', [
            nodeIdLink(node.gateway6),
            V.h('br'),
            'IPv6'
          ]));
        }

        return V.h('td', { props: { className: 'gateway' } }, gatewayCols);
      }

      function renderNeighbourRow(n) {
        var icons = [V.h('span', { props: { className: 'icon ion-' + (n.link.type.indexOf('wifi') === 0 ? 'wifi' : 'share-alt'), title: _.t(n.link.type) } })];
        if (helper.hasLocation(n.node)) {
          icons.push(V.h('span', { props: { className: 'ion-location', title: _.t('location.location') } }));
        }

        return V.h('tr', [
          V.h('td', icons),
          V.h('td', nodeLink(n.node)),
          V.h('td', n.node.clients),
          V.h('td', { style: { color: linkScale((n.link.source_tq + n.link.target_tq) / 2) } }, helper.showTq(n.link.source_tq) + ' - ' + helper.showTq(n.link.target_tq)),
          V.h('td', helper.showDistance(n.link))
        ]);
      }

      var self = this;
      var header = document.createElement('h2');
      var table = document.createElement('table');
      var images = document.createElement('div');
      var neighbours = document.createElement('h3');
      var headings = [{
        name: '',
        sort: function (a, b) {
          return a.link.type.localeCompare(b.link.type);
        }
      }, {
        name: 'node.nodes',
        sort: function (a, b) {
          return a.node.hostname.localeCompare(b.node.hostname);
        },
        reverse: false
      }, {
        name: 'node.clients',
        class: 'ion-people',
        sort: function (a, b) {
          return a.node.clients - b.node.clients;
        },
        reverse: true
      }, {
        name: 'node.tq',
        class: 'ion-connection-bars',
        sort: function (a, b) {
          return a.link.source_tq - b.link.source_tq;
        },
        reverse: true
      }, {
        name: 'node.distance',
        class: 'ion-arrow-resize',
        sort: function (a, b) {
          return (a.link.distance === undefined ? -1 : a.link.distance) -
            (b.link.distance === undefined ? -1 : b.link.distance);
        },
        reverse: true
      }];
      var tableNeighbour = new SortTable(headings, 1, renderNeighbourRow);

      el.appendChild(header);
      el.appendChild(table);
      el.appendChild(neighbours);
      el.appendChild(tableNeighbour.el);
      el.appendChild(images);

      self.render = function render() {
        V.patch(header, V.h('h2', d.hostname));

        var children = [];

        config.nodeAttr.forEach(function (row) {
          var field = d[row.value];
          if (typeof row.value === 'function') {
            field = row.value(d, nodeDict);
          } else if (nodef['show' + row.value] !== undefined) {
            field = nodef['show' + row.value](d);
          }

          if (field) {
            if (typeof field !== 'object') {
              field = V.h('td', field);
            }
            children.push(V.h('tr', [
              row.name !== undefined ? V.h('th', _.t(row.name)) : null,
              field
            ]));
          }
        });

        children.push(V.h('tr', [
          V.h('th', _.t('node.gateway')),
          showGateway(d)
        ]));

        var elNew = V.h('table', children);
        table = V.patch(table, elNew);
        table.elm.classList.add('attributes');

        V.patch(neighbours, V.h('h3', _.t('node.link', d.neighbours.length) + ' (' + d.neighbours.length + ')'));
        if (d.neighbours.length > 0) {
          tableNeighbour.setData(d.neighbours);
          tableNeighbour.el.elm.classList.add('node-links');
        }

        if (config.nodeInfos) {
          var img = [];
          config.nodeInfos.forEach(function (nodeInfo) {
            img.push(V.h('h4', nodeInfo.name));
            img.push(showStatImg(nodeInfo, d));
          });
          images = V.patch(images, V.h('div', img));
        }
      };

      self.setData = function setData(data) {
        if (data.nodeDict[d.node_id]) {
          d = data.nodeDict[d.node_id];
        }
        self.render();
      };
      return self;
    };
  });
<commit_msg>[TASK] Add nodes as title and link to link-infobox<commit_after>define(['sorttable', 'snabbdom', 'd3-interpolate', 'helper', 'utils/node'],
  function (SortTable, V, d3Interpolate, helper, nodef) {
    'use strict';
    V = V.default;

    function showStatImg(o, d) {
      var subst = {
        '{NODE_ID}': d.node_id,
        '{NODE_NAME}': d.hostname.replace(/[^a-z0-9\-]/ig, '_'),
        '{TIME}': d.lastseen.format('DDMMYYYYHmmss'),
        '{LOCALE}': _.locale()
      };
      return helper.showStat(V, o, subst);
    }

    return function (el, d, linkScale, nodeDict) {
      function nodeLink(node) {
        return V.h('a', {
          props: {
            className: node.is_online ? 'online' : 'offline',
            href: router.generateLink({ node: node.node_id })
          }, on: {
            click: function (e) {
              router.fullUrl({ node: node.node_id }, e);
            }
          }
        }, node.hostname);
      }

      function nodeIdLink(nodeId) {
        if (nodeDict[nodeId]) {
          return nodeLink(nodeDict[nodeId]);
        }
        return nodeId;
      }

      function showGateway(node) {
        var gatewayCols = [
          V.h('span', [
            nodeIdLink(node.gateway_nexthop),
            V.h('br'),
            _.t('node.nexthop')
          ]),
          V.h('span', { props: { className: 'ion-arrow-right-c' } }),
          V.h('span', [
            nodeIdLink(node.gateway),
            V.h('br'),
            'IPv4'
          ])
        ];

        if (node.gateway6 !== undefined) {
          gatewayCols.push(V.h('span', [
            nodeIdLink(node.gateway6),
            V.h('br'),
            'IPv6'
          ]));
        }

        return V.h('td', { props: { className: 'gateway' } }, gatewayCols);
      }

      function renderNeighbourRow(n) {
        var icons = [V.h('span', { props: { className: 'icon ion-' + (n.link.type.indexOf('wifi') === 0 ? 'wifi' : 'share-alt'), title: _.t(n.link.type) } })];
        if (helper.hasLocation(n.node)) {
          icons.push(V.h('span', { props: { className: 'ion-location', title: _.t('location.location') } }));
        }

        return V.h('tr', [
          V.h('td', icons),
          V.h('td', nodeLink(n.node)),
          V.h('td', n.node.clients),
          V.h('td', [V.h('a', {
            style: {
              color: linkScale((n.link.source_tq + n.link.target_tq) / 2)
            },
            props: {
              title: n.link.source.hostname + ' - ' + n.link.target.hostname,
              href: router.generateLink({ link: n.link.id })
            }, on: {
              click: function (e) {
                router.fullUrl({ link: n.link.id }, e);
              }
            }
          }, helper.showTq(n.link.source_tq) + ' - ' + helper.showTq(n.link.target_tq))]),
          V.h('td', helper.showDistance(n.link))
        ]);
      }

      var self = this;
      var header = document.createElement('h2');
      var table = document.createElement('table');
      var images = document.createElement('div');
      var neighbours = document.createElement('h3');
      var headings = [{
        name: '',
        sort: function (a, b) {
          return a.link.type.localeCompare(b.link.type);
        }
      }, {
        name: 'node.nodes',
        sort: function (a, b) {
          return a.node.hostname.localeCompare(b.node.hostname);
        },
        reverse: false
      }, {
        name: 'node.clients',
        class: 'ion-people',
        sort: function (a, b) {
          return a.node.clients - b.node.clients;
        },
        reverse: true
      }, {
        name: 'node.tq',
        class: 'ion-connection-bars',
        sort: function (a, b) {
          return a.link.source_tq - b.link.source_tq;
        },
        reverse: true
      }, {
        name: 'node.distance',
        class: 'ion-arrow-resize',
        sort: function (a, b) {
          return (a.link.distance === undefined ? -1 : a.link.distance) -
            (b.link.distance === undefined ? -1 : b.link.distance);
        },
        reverse: true
      }];
      var tableNeighbour = new SortTable(headings, 1, renderNeighbourRow);

      el.appendChild(header);
      el.appendChild(table);
      el.appendChild(neighbours);
      el.appendChild(tableNeighbour.el);
      el.appendChild(images);

      self.render = function render() {
        V.patch(header, V.h('h2', d.hostname));

        var children = [];

        config.nodeAttr.forEach(function (row) {
          var field = d[row.value];
          if (typeof row.value === 'function') {
            field = row.value(d, nodeDict);
          } else if (nodef['show' + row.value] !== undefined) {
            field = nodef['show' + row.value](d);
          }

          if (field) {
            if (typeof field !== 'object') {
              field = V.h('td', field);
            }
            children.push(V.h('tr', [
              row.name !== undefined ? V.h('th', _.t(row.name)) : null,
              field
            ]));
          }
        });

        children.push(V.h('tr', [
          V.h('th', _.t('node.gateway')),
          showGateway(d)
        ]));

        var elNew = V.h('table', children);
        table = V.patch(table, elNew);
        table.elm.classList.add('attributes');

        V.patch(neighbours, V.h('h3', _.t('node.link', d.neighbours.length) + ' (' + d.neighbours.length + ')'));
        if (d.neighbours.length > 0) {
          tableNeighbour.setData(d.neighbours);
          tableNeighbour.el.elm.classList.add('node-links');
        }

        if (config.nodeInfos) {
          var img = [];
          config.nodeInfos.forEach(function (nodeInfo) {
            img.push(V.h('h4', nodeInfo.name));
            img.push(showStatImg(nodeInfo, d));
          });
          images = V.patch(images, V.h('div', img));
        }
      };

      self.setData = function setData(data) {
        if (data.nodeDict[d.node_id]) {
          d = data.nodeDict[d.node_id];
        }
        self.render();
      };
      return self;
    };
  });
<|endoftext|>


<commit_before>/*jshint node:true*/

const flatten = list => list.reduce(
  (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);

const getDefaultUrls = (name) => [`assets/${name}.js`, `assets/${name}.css`];

/***
 * Returns the list of all the bundles. If a bundle isn't defined in config/bundles.js
 * a default is inferred based on the package-names where there is a one to one package-bundle,
 * the bundle has no dependencies and we load from the default URLs that Ember specified
 */

module.exports = function (bundles, packageNames) {
  const configCopy = bundles.slice();
  const packagesInBundle = flatten(configCopy.map(bundle=>bundle.packages));
  const packagesMissingFromBundle = packageNames.filter(name=>
    packagesInBundle.indexOf(name) === -1);
  const configForMissingPackages = packagesMissingFromBundle.map(name=>({
    name,
    packages: [name],
    urls: getDefaultUrls(name),
    handledRoutesPatterns: [`/${name}`]
  }));

  configCopy.forEach(bundle=>{
    if (!bundle.urls) {
      bundle.urls = getDefaultUrls(bundle.name);
    }
  });

  return configCopy.concat(configForMissingPackages);
};
<commit_msg>Removes esnext features from addon code. Tests still rely on it, so travis.yml still uses 4.4.3<commit_after>/*jshint node:true*/

var flatten = function (list) {
  return list.reduce(function (a, b) {
    return a.concat(Array.isArray(b) ? flatten(b) : b);
  }, []);
};

var getDefaultUrls = function (name) {
  return ['assets/' + name + '.js', 'assets/' + name + '.css'];
};

/***
 * Returns the list of all the bundles. If a bundle isn't defined in config/bundles.js
 * a default is inferred based on the package-names where there is a one to one package-bundle,
 * the bundle has no dependencies and we load from the default URLs that Ember specified
 */

module.exports = function (bundles, packageNames) {
  var configCopy = bundles.slice();
  var packagesInBundle = flatten(configCopy.map(function (bundle) {
    return bundle.packages;
  }));
  var packagesMissingFromBundle = packageNames.filter(function (name) {
    return packagesInBundle.indexOf(name) === -1;
  });
  var configForMissingPackages = packagesMissingFromBundle.map(function (name) {
    return {
      name: name,
      packages: [name],
      urls: getDefaultUrls(name),
      handledRoutesPatterns: ['/' + name]
    };
  });

  configCopy.forEach(function (bundle) {
    if (!bundle.urls) {
      bundle.urls = getDefaultUrls(bundle.name);
    }
  });

  return configCopy.concat(configForMissingPackages);
};
<|endoftext|>


<commit_before>function tokenize(t){for(var e=[],n=function(t,e){return!t.after(e)&&e},o=function(t){return t.textContent.match(/({\w+})/)&&(e[e.length]=t)||t},r=0,i=mine(t);r<i.length;r+=1)match=i[r],slice(match.textContent).map(o).reduce(n,match)&&match.remove();return e}function zip(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var n=function(t,e){return t.concat(e)},o=function(t){return function(e,n){return[e,t[n]]}};return t[1].map(o(t[0])).reduce(n)}function slice(t){var e=[],n=/({\w+})/g,o=function(t){return r(t)&&"✂"},r=function(t){return e.push(t)},i=t.replace(n,o).split("✂");return zip(e,i).filter(function(t){return t}).map(function(t){return new Text(t)})}function mine(t){console.time();for(var e=[],n=document.createNodeIterator(t,NodeFilter.SHOW_TEXT,visit);node=n.nextNode();)e.push(node);return console.timeEnd(),e}function visit(t){return/({\w+})/g.test(t.data)&&NodeFilter.FILTER_ACCEPT}function comb(t){if(t.hasChildNodes())for(var e=t.firstChild;e;e=e.nextSibling)DOMComb(e)}var this$1=this,tail=function(t,e){return!t.after(e)&&e},Template=function(t){function e(t){var e=this;t=Array.isArray(t)?t:[t];var n=[],i=t.map(function(){return e.content.cloneNode(!0)}).map(o,n);this.innerHTML="";for(var c=0,u=i;c<u.length;c+=1){var a=u[c];e.content.appendChild(a)}return t.map(r,n)&&this}function n(t){return console.log("im here",document.querySelectorAll("infinity-calendar")),document.querySelector("template[name="+t+"]").cloneNode(!0)||document.createElement("template")}function o(t){var e=function(t){return t.reduce(function(t,e){return(t[e.textContent.match(/{(.+)}/)[1]]=e)&&t},{})};return this.push(e(tokenize(t)))&&t}function r(t,e){var n=this;for(var o in t)n[e][o]&&(n[e][o].textContent=t[o])}return void 0===t&&(t="snuggsi"),Object.assign(n.apply(void 0,t),{bind:e})},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={observedAttributes:{}};return e.prototype.connectedCallback=function(){(t.prototype.initialize||function(){}).call(this),this.render(),t.prototype.constructor.onconnect?t.prototype.constructor.onconnect:t.prototype.connectedCallback.call(this)},e.prototype.listenable=function(t){var e=this;return Array.prototype.map.call(t,function(t){return Object.assign(t,{listen:e.listen.bind(e)})})},e.prototype.listen=function(t,e){void 0===e&&(e=this$1[t]),this.addEventListener(t,e)},e.prototype.adoptedCallback=function(){console.warn("adopted this",this)},e.prototype.stateChangedCallback=function(t,e){console.warn("previous",t,"next",e)},n.observedAttributes.get=function(){return["id"]},e.prototype.attributeChangedCallback=function(t,e,n){console.warn("["+t+"] ["+e+"] to ["+n+"]")},Object.defineProperties(e,n),e}(t)},ElementPrototype=window.Element.prototype,Element=function(t){return t=Array.isArray(t)?t[0]:t,function(e,n){void 0===n&&(n=this!==window?this:{}),console.time();var o=function(t){return Object.getOwnPropertyNames(t)},r=o(e.prototype);console.timeEnd();try{if(!e)return new(window.customElements.get(t))}catch(i){throw"Must define custom element \n(i.e. Element `"+t+"` (class {})"}var c=function(t){function e(){t.call(this),this.context=n}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var o={context:{},templates:{}};return o.context.get=function(){return n},o.context.set=function(t){return console.warn("setting context",t),n=t},o.templates.get=function(){return this.selectAll("template")},e.prototype.render=function(e,n){var o=this;void 0===n&&(n=this.context);for(var i=0,c=o.templates;i<c.length;i+=1){var u=c[i];console.log("i'm in the renderer",n,u)}window.element=this,window.state=this.context;for(var a=0,l=r;a<l.length;a+=1){var s=l[a];console.log(s)}this.append(Template(["days"]).bind(this.days).content);e?this.select(e):this,(t.prototype.render||function(){})(e)},e.prototype.select=function(t){return this.selectAll(t)[0]},e.prototype.selectAll=function(t){return this.listenable(this.querySelectorAll(t))},Object.defineProperties(e.prototype,o),e}(GlobalEventHandlers(e));try{window.customElements.define(t,c)}finally{return window.customElements.get(t)}}};Element.prototype=window.Element.prototype;<commit_msg>Update snuggsi.min.js distribution<commit_after>function tokenize(t){for(var e=[],n=function(t,e){return!t.after(e)&&e},r=function(t){return t.textContent.match(/({\w+})/)&&(e[e.length]=t)||t},o=0,i=mine(t);o<i.length;o+=1)match=i[o],slice(match.textContent).map(r).reduce(n,match)&&match.remove();return e}function zip(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var n=function(t,e){return t.concat(e)},r=function(t){return function(e,n){return[e,t[n]]}};return t[1].map(r(t[0])).reduce(n)}function slice(t){var e=[],n=/({\w+})/g,r=function(t){return o(t)&&"✂"},o=function(t){return e.push(t)},i=t.replace(n,r).split("✂");return zip(e,i).filter(function(t){return t}).map(function(t){return new Text(t)})}function mine(t){for(var e=[],n=document.createNodeIterator(t,NodeFilter.SHOW_TEXT,visit);node=n.nextNode();)e.push(node);return e}function visit(t){return/({\w+})/g.test(t.data)&&NodeFilter.FILTER_ACCEPT}function comb(t){if(t.hasChildNodes())for(var e=t.firstChild;e;e=e.nextSibling)DOMComb(e)}function upgrade(){console.time();var t=function(t){return Object.getOwnPropertyNames(t)},e=t(prototype.prototype),n=t(prototype),r=this.attributes;console.timeEnd(),console.warn(e,n,r)}var this$1=this,tail=function(t,e){return!t.after(e)&&e},Template=function(t){function e(t){var e=this;t=Array.isArray(t)?t:[t];var n=[],i=t.map(function(){return e.content.cloneNode(!0)}).map(r,n);this.innerHTML="";for(var c=0,u=i;c<u.length;c+=1){var a=u[c];e.content.appendChild(a)}return t.map(o,n)&&this}function n(t){return document.querySelector("template[name="+t+"]").cloneNode(!0)||document.createElement("template")}function r(t){var e=function(t){return t.reduce(function(t,e){return(t[e.textContent.match(/{(.+)}/)[1]]=e)&&t},{})};return this.push(e(tokenize(t)))&&t}function o(t,e){var n=this;for(var r in t)n[e][r]&&(n[e][r].textContent=t[r])}return void 0===t&&(t="snuggsi"),Object.assign(n.apply(void 0,t),{bind:e})},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={observedAttributes:{}};return e.prototype.connectedCallback=function(){this.render(),t.prototype.constructor.onconnect?t.prototype.constructor.onconnect:t.prototype.connectedCallback||function(){}.call(this)},e.prototype.listenable=function(t){var e=this;return Array.prototype.map.call(t,function(t){return Object.assign(t,{listen:e.listen.bind(e)})})},e.prototype.listen=function(t,e){void 0===e&&(e=this$1[t]),this.addEventListener(t,e)},e.prototype.adoptedCallback=function(){console.warn("adopted this",this)},e.prototype.stateChangedCallback=function(t,e){console.warn("previous",t,"next",e)},n.observedAttributes.get=function(){return["id"]},e.prototype.attributeChangedCallback=function(t,e,n){console.warn("["+t+"] ["+e+"] to ["+n+"]")},Object.defineProperties(e,n),e}(t)},ElementPrototype=window.Element.prototype,Element=function(t){return void 0===t&&(t=Array.isArray(arguments[0])?arguments[0][0]:arguments[0]),function(e,n){void 0===n&&(n=this!==window?this:{});try{if(!e)return new window.customElements.get(t)}catch(r){throw"Must define custom element \n(i.e. Element `"+t+"` (class {})"}var o=function(t){function e(){t.call(this),this.context=n,t.prototype.initialize&&t.prototype.initialize.call(this)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={context:{},templates:{}};return r.context.get=function(){return n},r.context.set=function(t){return n=t},r.templates.get=function(){return this.selectAll("template")},e.prototype.render=function(e){e?this.select(e):this,t.prototype.render&&t.prototype.render.call(this,e)},e.prototype.selectAll=function(t){return this.listenable(this.querySelectorAll(t))},e.prototype.select=function(t){return this.selectAll(t)[0]},Object.defineProperties(e.prototype,r),e}(GlobalEventHandlers(e));try{window.customElements.define(t,o)}finally{return window.customElements.get(t)}}};Element.prototype=window.Element.prototype;<|endoftext|>


<commit_before>define(["chroma-js", "moment/moment", "tablesort", "helper", "moment/locale/de"],
  function (chroma, moment, Tablesort, helper) {
    "use strict";

    function showGeoURI(d) {
      function showLatitude(d) {
        var suffix = Math.sign(d) > -1 ? "' N" : "' S";
        d = Math.abs(d);
        var a = Math.floor(d);
        var min = (d * 60) % 60;
        a = (a < 10 ? "0" : "") + a;

        return a + "° " + min.toFixed(3) + suffix;
      }

      function showLongitude(d) {
        var suffix = Math.sign(d) > -1 ? "' E" : "' W";
        d = Math.abs(d);
        var a = Math.floor(d);
        var min = (d * 60) % 60;
        a = (a < 100 ? "0" + (a < 10 ? "0" : "") : "") + a;

        return a + "° " + min.toFixed(3) + suffix;
      }

      if (!helper.hasLocation(d)) {
        return undefined;
      }

      return function (el) {
        var latitude = d.nodeinfo.location.latitude;
        var longitude = d.nodeinfo.location.longitude;
        var a = document.createElement("a");
        a.textContent = showLatitude(latitude) + " " +
          showLongitude(longitude);

        a.href = "geo:" + latitude + "," + longitude;
        el.appendChild(a);
      };
    }

    function showStatus(d) {
      return function (el) {
        el.classList.add(d.flags.unseen ? "unseen" : (d.flags.online ? "online" : "offline"));
        if (d.flags.online) {
          el.textContent = "online, letzte Nachricht " + d.lastseen.fromNow() + " (" + d.lastseen.format("DD.MM.YYYY,  H:mm:ss") + ")";
        } else {
          el.textContent = "offline, letzte Nachricht " + d.lastseen.fromNow() + " (" + d.lastseen.format("DD.MM.YYYY,  H:mm:ss") + ")";
        }
      };
    }

    function showFirmware(d) {
      var release = helper.dictGet(d.nodeinfo, ["software", "firmware", "release"]);
      var base = helper.dictGet(d.nodeinfo, ["software", "firmware", "base"]);

      if (release === null || base === null) {
        return undefined;
      }

      return release + " / " + base;
    }

    function showSite(d, config) {
      var site = helper.dictGet(d.nodeinfo, ["system", "site_code"]);
      var rt = site;
      if (config.siteNames) {
        config.siteNames.forEach(function (t) {
          if (site === t.site) {
            rt = t.name;
          }
        });
      }
      return rt;
    }

    function showUptime(d) {
      if (!("uptime" in d.statistics)) {
        return undefined;
      }

      return moment.duration(d.statistics.uptime, "seconds").humanize();
    }

    function showFirstseen(d) {
      if (!("firstseen" in d)) {
        return undefined;
      }

      return d.firstseen.fromNow(true);
    }

    function showClients(d) {
      if (!d.flags.online) {
        return undefined;
      }

      return function (el) {
        el.appendChild(document.createTextNode(d.statistics.clients > 0 ? d.statistics.clients : "keine"));
        el.appendChild(document.createElement("br"));

        var span = document.createElement("span");
        span.classList.add("clients");
        span.innerHTML = "".repeat(d.statistics.clients);
        el.appendChild(span);
      };
    }

    function showIPs(d) {
      var ips = helper.dictGet(d.nodeinfo, ["network", "addresses"]);
      if (ips === null) {
        return undefined;
      }

      ips.sort();

      return function (el) {
        ips.forEach(function (ip, i) {
          var link = !ip.startsWith("fe80:");

          if (i > 0) {
            el.appendChild(document.createElement("br"));
          }

          if (link) {
            var a = document.createElement("a");
            a.href = "http://[" + ip + "]/";
            a.textContent = ip;
            el.appendChild(a);
          } else {
            el.appendChild(document.createTextNode(ip));
          }
        });
      };
    }

    function showBar(v) {
      var span = document.createElement("span");
      span.classList.add("bar");

      var bar = document.createElement("span");
      bar.style.width = (v * 100) + "%";
      span.appendChild(bar);

      var label = document.createElement("label");
      label.textContent = (Math.round(v * 100)) + " %";
      span.appendChild(label);

      return span;
    }

    function showLoadBar(v) {
      var span = document.createElement("span");
      span.classList.add("bar");

      var bar = document.createElement("span");
      if (v >= 1) {
        bar.style.width = ((v * 100) % 100) + "%";
        span.classList.add("warning");
      }
      else {
        bar.style.width = (v * 100) + "%";
      }
      span.appendChild(bar);

      var label = document.createElement("label");
      label.textContent = (v);
      span.appendChild(label);

      return span;
    }

    function showLoad(d) {
      if (!("loadavg" in d.statistics)) {
        return undefined;
      }

      return function (el) {
        el.appendChild(showLoadBar(d.statistics.loadavg.toFixed(2)));
      };
    }

    function showRAM(d) {
      if (!("memory_usage" in d.statistics)) {
        return undefined;
      }

      return function (el) {
        el.appendChild(showBar(d.statistics.memory_usage));
      };
    }

    function showPages(d) {
      var webpages = helper.dictGet(d.nodeinfo, ["pages"]);
      if (webpages === null) {
        return undefined;
      }

      webpages.sort();

      return function (el) {
        webpages.forEach(function (webpage, i) {
          if (i > 0) {
            el.appendChild(document.createElement("br"));
          }

          var a = document.createElement("span");
          var link = document.createElement("a");
          link.href = webpage;
          if (webpage.search(/^https:\/\//i) !== -1) {
            var lock = document.createElement("span");
            lock.classList.add("ion-android-lock");
            a.appendChild(lock);
            var t1 = document.createTextNode(" ");
            a.appendChild(t1);
            link.textContent = webpage.replace(/^https:\/\//i, "");
          }
          else {
            link.textContent = webpage.replace(/^http:\/\//i, "");
          }
          a.appendChild(link);
          el.appendChild(a);
        });
      };
    }

    function showAutoupdate(d) {
      var au = helper.dictGet(d.nodeinfo, ["software", "autoupdater"]);
      if (!au) {
        return undefined;
      }

      return au.enabled ? "aktiviert (" + au.branch + ")" : "deaktiviert";
    }

    function showStatImg(o, d) {
      var subst = {};
      subst["{NODE_ID}"] = d.nodeinfo.node_id ? d.nodeinfo.node_id : "unknown";
      subst["{NODE_NAME}"] = d.nodeinfo.hostname ? d.nodeinfo.hostname.replace(/[^a-z0-9\-]/ig, "_") : "unknown";
      subst["{TIME}"] = d.lastseen.format("DDMMYYYYHmmss");
      return helper.showStat(o, subst);
    }

    return function (config, el, router, d) {
      var linkScale = chroma.scale(chroma.bezier(["#04C714", "#FF5500", "#F02311"])).domain([1, 5]);
      var h2 = document.createElement("h2");
      h2.textContent = d.nodeinfo.hostname;
      el.appendChild(h2);

      var attributes = document.createElement("table");
      attributes.classList.add("attributes");

      helper.attributeEntry(attributes, "Status", showStatus(d));
      helper.attributeEntry(attributes, "Gateway", d.flags.gateway ? "ja" : null);
      helper.attributeEntry(attributes, "Koordinaten", showGeoURI(d));

      if (config.showContact) {
        helper.attributeEntry(attributes, "Kontakt", helper.dictGet(d.nodeinfo, ["owner", "contact"]));
      }

      helper.attributeEntry(attributes, "Hardware", helper.dictGet(d.nodeinfo, ["hardware", "model"]));
      helper.attributeEntry(attributes, "Primäre MAC", helper.dictGet(d.nodeinfo, ["network", "mac"]));
      helper.attributeEntry(attributes, "Node ID", helper.dictGet(d.nodeinfo, ["node_id"]));
      helper.attributeEntry(attributes, "Firmware", showFirmware(d));
      helper.attributeEntry(attributes, "Site", showSite(d, config));
      helper.attributeEntry(attributes, "Uptime", showUptime(d));
      helper.attributeEntry(attributes, "Teil des Netzes", showFirstseen(d));
      helper.attributeEntry(attributes, "Systemlast", showLoad(d));
      helper.attributeEntry(attributes, "Arbeitsspeicher", showRAM(d));
      helper.attributeEntry(attributes, "IP Adressen", showIPs(d));
      helper.attributeEntry(attributes, "Webseite", showPages(d));
      helper.attributeEntry(attributes, "Gewähltes Gateway", helper.dictGet(d.statistics, ["gateway"]));
      helper.attributeEntry(attributes, "Autom. Updates", showAutoupdate(d));
      helper.attributeEntry(attributes, "Clients", showClients(d));

      el.appendChild(attributes);

      if (config.nodeInfos) {
        config.nodeInfos.forEach(function (nodeInfo) {
          var h4 = document.createElement("h4");
          h4.textContent = nodeInfo.name;
          el.appendChild(h4);
          el.appendChild(showStatImg(nodeInfo, d));
        });
      }

      if (d.neighbours.length > 0) {
        var h3 = document.createElement("h3");
        h3.textContent = "Links (" + d.neighbours.length + ")";
        el.appendChild(h3);

        var table = document.createElement("table");
        var thead = document.createElement("thead");

        var tr = document.createElement("tr");
        var th1 = document.createElement("th");
        th1.textContent = " ";
        tr.appendChild(th1);

        var th2 = document.createElement("th");
        th2.textContent = "Knoten";
        th2.classList.add("sort-default");
        tr.appendChild(th2);

        var th3 = document.createElement("th");
        th3.textContent = "TQ";
        tr.appendChild(th3);

        var th4 = document.createElement("th");
        th4.textContent = "Entfernung";
        tr.appendChild(th4);

        thead.appendChild(tr);
        table.appendChild(thead);

        var tbody = document.createElement("tbody");

        d.neighbours.forEach(function (d) {
          var unknown = !(d.node);
          var tr = document.createElement("tr");

          var td1 = document.createElement("td");

          var direction = document.createElement("span");
          direction.classList.add(d.incoming ? "ion-ios-arrow-thin-left" : "ion-ios-arrow-thin-right");
          td1.appendChild(direction);

          if (!unknown && helper.hasLocation(d.node)) {
            var span = document.createElement("span");
            span.classList.add("ion-location");
            td1.appendChild(span);
          }

          tr.appendChild(td1);

          var td2 = document.createElement("td");

          if (!unknown) {
            var a1 = document.createElement("a");
            a1.textContent = d.node.nodeinfo.hostname;
            a1.classList.add("online");
            a1.href = "#";
            a1.onclick = router.node(d.node);
            td2.appendChild(a1);
          } else {
            td2.textContent = d.id;
          }

          tr.appendChild(td2);

          var td3 = document.createElement("td");
          td3.textContent = helper.showTq(d.link);
          td3.style.color = linkScale(d.link.tq).hex();
          tr.appendChild(td3);

          var td4 = document.createElement("td");
          td4.textContent = helper.showDistance(d.link);
          td4.setAttribute("data-sort", d.link.distance !== undefined ? -d.link.distance : 1);
          tr.appendChild(td4);

          tbody.appendChild(tr);
        });

        table.appendChild(tbody);
        table.classList.add("node-links");

        Tablesort(table);

        el.appendChild(table);
      }
    };
  });
<commit_msg>[TASK] One loadavg per core<commit_after>define(["chroma-js", "moment/moment", "tablesort", "helper", "moment/locale/de"],
  function (chroma, moment, Tablesort, helper) {
    "use strict";

    function showGeoURI(d) {
      function showLatitude(d) {
        var suffix = Math.sign(d) > -1 ? "' N" : "' S";
        d = Math.abs(d);
        var a = Math.floor(d);
        var min = (d * 60) % 60;
        a = (a < 10 ? "0" : "") + a;

        return a + "° " + min.toFixed(3) + suffix;
      }

      function showLongitude(d) {
        var suffix = Math.sign(d) > -1 ? "' E" : "' W";
        d = Math.abs(d);
        var a = Math.floor(d);
        var min = (d * 60) % 60;
        a = (a < 100 ? "0" + (a < 10 ? "0" : "") : "") + a;

        return a + "° " + min.toFixed(3) + suffix;
      }

      if (!helper.hasLocation(d)) {
        return undefined;
      }

      return function (el) {
        var latitude = d.nodeinfo.location.latitude;
        var longitude = d.nodeinfo.location.longitude;
        var a = document.createElement("a");
        a.textContent = showLatitude(latitude) + " " +
          showLongitude(longitude);

        a.href = "geo:" + latitude + "," + longitude;
        el.appendChild(a);
      };
    }

    function showStatus(d) {
      return function (el) {
        el.classList.add(d.flags.unseen ? "unseen" : (d.flags.online ? "online" : "offline"));
        if (d.flags.online) {
          el.textContent = "online, letzte Nachricht " + d.lastseen.fromNow() + " (" + d.lastseen.format("DD.MM.YYYY,  H:mm:ss") + ")";
        } else {
          el.textContent = "offline, letzte Nachricht " + d.lastseen.fromNow() + " (" + d.lastseen.format("DD.MM.YYYY,  H:mm:ss") + ")";
        }
      };
    }

    function showFirmware(d) {
      var release = helper.dictGet(d.nodeinfo, ["software", "firmware", "release"]);
      var base = helper.dictGet(d.nodeinfo, ["software", "firmware", "base"]);

      if (release === null || base === null) {
        return undefined;
      }

      return release + " / " + base;
    }

    function showSite(d, config) {
      var site = helper.dictGet(d.nodeinfo, ["system", "site_code"]);
      var rt = site;
      if (config.siteNames) {
        config.siteNames.forEach(function (t) {
          if (site === t.site) {
            rt = t.name;
          }
        });
      }
      return rt;
    }

    function showUptime(d) {
      if (!("uptime" in d.statistics)) {
        return undefined;
      }

      return moment.duration(d.statistics.uptime, "seconds").humanize();
    }

    function showFirstseen(d) {
      if (!("firstseen" in d)) {
        return undefined;
      }

      return d.firstseen.fromNow(true);
    }

    function showClients(d) {
      if (!d.flags.online) {
        return undefined;
      }

      return function (el) {
        el.appendChild(document.createTextNode(d.statistics.clients > 0 ? d.statistics.clients : "keine"));
        el.appendChild(document.createElement("br"));

        var span = document.createElement("span");
        span.classList.add("clients");
        span.innerHTML = "".repeat(d.statistics.clients);
        el.appendChild(span);
      };
    }

    function showIPs(d) {
      var ips = helper.dictGet(d.nodeinfo, ["network", "addresses"]);
      if (ips === null) {
        return undefined;
      }

      ips.sort();

      return function (el) {
        ips.forEach(function (ip, i) {
          var link = !ip.startsWith("fe80:");

          if (i > 0) {
            el.appendChild(document.createElement("br"));
          }

          if (link) {
            var a = document.createElement("a");
            a.href = "http://[" + ip + "]/";
            a.textContent = ip;
            el.appendChild(a);
          } else {
            el.appendChild(document.createTextNode(ip));
          }
        });
      };
    }

    function showBar(v) {
      var span = document.createElement("span");
      span.classList.add("bar");

      var bar = document.createElement("span");
      bar.style.width = (v * 100) + "%";
      span.appendChild(bar);

      var label = document.createElement("label");
      label.textContent = (Math.round(v * 100)) + " %";
      span.appendChild(label);

      return span;
    }

    function showLoadBar(v, p) {
      var span = document.createElement("span");
      span.classList.add("bar");

      var bar = document.createElement("span");
      bar.style.width = ((v * 100) % 100) + "%";
      if (v >= p) {
        span.classList.add("warning");
      }
      span.appendChild(bar);

      var label = document.createElement("label");
      label.textContent = (v);
      span.appendChild(label);

      return span;
    }

    function showLoad(d) {
      if (!("loadavg" in d.statistics)) {
        return undefined;
      }

      return function (el) {
        el.appendChild(showLoadBar(d.statistics.loadavg.toFixed(2), d.nodeinfo.hardware.nproc));
      };
    }

    function showRAM(d) {
      if (!("memory_usage" in d.statistics)) {
        return undefined;
      }

      return function (el) {
        el.appendChild(showBar(d.statistics.memory_usage));
      };
    }

    function showPages(d) {
      var webpages = helper.dictGet(d.nodeinfo, ["pages"]);
      if (webpages === null) {
        return undefined;
      }

      webpages.sort();

      return function (el) {
        webpages.forEach(function (webpage, i) {
          if (i > 0) {
            el.appendChild(document.createElement("br"));
          }

          var a = document.createElement("span");
          var link = document.createElement("a");
          link.href = webpage;
          if (webpage.search(/^https:\/\//i) !== -1) {
            var lock = document.createElement("span");
            lock.classList.add("ion-android-lock");
            a.appendChild(lock);
            var t1 = document.createTextNode(" ");
            a.appendChild(t1);
            link.textContent = webpage.replace(/^https:\/\//i, "");
          }
          else {
            link.textContent = webpage.replace(/^http:\/\//i, "");
          }
          a.appendChild(link);
          el.appendChild(a);
        });
      };
    }

    function showAutoupdate(d) {
      var au = helper.dictGet(d.nodeinfo, ["software", "autoupdater"]);
      if (!au) {
        return undefined;
      }

      return au.enabled ? "aktiviert (" + au.branch + ")" : "deaktiviert";
    }

    function showStatImg(o, d) {
      var subst = {};
      subst["{NODE_ID}"] = d.nodeinfo.node_id ? d.nodeinfo.node_id : "unknown";
      subst["{NODE_NAME}"] = d.nodeinfo.hostname ? d.nodeinfo.hostname.replace(/[^a-z0-9\-]/ig, "_") : "unknown";
      subst["{TIME}"] = d.lastseen.format("DDMMYYYYHmmss");
      return helper.showStat(o, subst);
    }

    return function (config, el, router, d) {
      var linkScale = chroma.scale(chroma.bezier(["#04C714", "#FF5500", "#F02311"])).domain([1, 5]);
      var h2 = document.createElement("h2");
      h2.textContent = d.nodeinfo.hostname;
      el.appendChild(h2);

      var attributes = document.createElement("table");
      attributes.classList.add("attributes");

      helper.attributeEntry(attributes, "Status", showStatus(d));
      helper.attributeEntry(attributes, "Gateway", d.flags.gateway ? "ja" : null);
      helper.attributeEntry(attributes, "Koordinaten", showGeoURI(d));

      if (config.showContact) {
        helper.attributeEntry(attributes, "Kontakt", helper.dictGet(d.nodeinfo, ["owner", "contact"]));
      }

      helper.attributeEntry(attributes, "Hardware", helper.dictGet(d.nodeinfo, ["hardware", "model"]));
      helper.attributeEntry(attributes, "Primäre MAC", helper.dictGet(d.nodeinfo, ["network", "mac"]));
      helper.attributeEntry(attributes, "Node ID", helper.dictGet(d.nodeinfo, ["node_id"]));
      helper.attributeEntry(attributes, "Firmware", showFirmware(d));
      helper.attributeEntry(attributes, "Site", showSite(d, config));
      helper.attributeEntry(attributes, "Uptime", showUptime(d));
      helper.attributeEntry(attributes, "Teil des Netzes", showFirstseen(d));
      helper.attributeEntry(attributes, "Systemlast", showLoad(d));
      helper.attributeEntry(attributes, "Arbeitsspeicher", showRAM(d));
      helper.attributeEntry(attributes, "IP Adressen", showIPs(d));
      helper.attributeEntry(attributes, "Webseite", showPages(d));
      helper.attributeEntry(attributes, "Gewähltes Gateway", helper.dictGet(d.statistics, ["gateway"]));
      helper.attributeEntry(attributes, "Autom. Updates", showAutoupdate(d));
      helper.attributeEntry(attributes, "Clients", showClients(d));

      el.appendChild(attributes);

      if (config.nodeInfos) {
        config.nodeInfos.forEach(function (nodeInfo) {
          var h4 = document.createElement("h4");
          h4.textContent = nodeInfo.name;
          el.appendChild(h4);
          el.appendChild(showStatImg(nodeInfo, d));
        });
      }

      if (d.neighbours.length > 0) {
        var h3 = document.createElement("h3");
        h3.textContent = "Links (" + d.neighbours.length + ")";
        el.appendChild(h3);

        var table = document.createElement("table");
        var thead = document.createElement("thead");

        var tr = document.createElement("tr");
        var th1 = document.createElement("th");
        th1.textContent = " ";
        tr.appendChild(th1);

        var th2 = document.createElement("th");
        th2.textContent = "Knoten";
        th2.classList.add("sort-default");
        tr.appendChild(th2);

        var th3 = document.createElement("th");
        th3.textContent = "TQ";
        tr.appendChild(th3);

        var th4 = document.createElement("th");
        th4.textContent = "Entfernung";
        tr.appendChild(th4);

        thead.appendChild(tr);
        table.appendChild(thead);

        var tbody = document.createElement("tbody");

        d.neighbours.forEach(function (d) {
          var unknown = !(d.node);
          var tr = document.createElement("tr");

          var td1 = document.createElement("td");

          var direction = document.createElement("span");
          direction.classList.add(d.incoming ? "ion-ios-arrow-thin-left" : "ion-ios-arrow-thin-right");
          td1.appendChild(direction);

          if (!unknown && helper.hasLocation(d.node)) {
            var span = document.createElement("span");
            span.classList.add("ion-location");
            td1.appendChild(span);
          }

          tr.appendChild(td1);

          var td2 = document.createElement("td");

          if (!unknown) {
            var a1 = document.createElement("a");
            a1.textContent = d.node.nodeinfo.hostname;
            a1.classList.add("online");
            a1.href = "#";
            a1.onclick = router.node(d.node);
            td2.appendChild(a1);
          } else {
            td2.textContent = d.id;
          }

          tr.appendChild(td2);

          var td3 = document.createElement("td");
          td3.textContent = helper.showTq(d.link);
          td3.style.color = linkScale(d.link.tq).hex();
          tr.appendChild(td3);

          var td4 = document.createElement("td");
          td4.textContent = helper.showDistance(d.link);
          td4.setAttribute("data-sort", d.link.distance !== undefined ? -d.link.distance : 1);
          tr.appendChild(td4);

          tbody.appendChild(tr);
        });

        table.appendChild(tbody);
        table.classList.add("node-links");

        Tablesort(table);

        el.appendChild(table);
      }
    };
  });
<|endoftext|>


<commit_before>var util          = alchemy.use('util'),
    STR_PAD_LEFT  = 1,
    STR_PAD_RIGHT = 2,
    STR_PAD_BOTH  = 3,
    consoleWidth  = process.stdout.columns,
    consoleHeight = process.stdout.rows,
    Janeway       = alchemy.use('janeway'),
    echo,
    key;
alchemy.use('colors');
ansi = alchemy.use('ansi-256-colors')
alchemy.Janeway = Janeway;

// Listen to console resized
process.stdout.on('resize', function() {
	consoleWidth  = process.stdout.columns,
	consoleHeight = process.stdout.rows;
});

/**
 * Log messages, level 2: info
 *
 * Level 0 = error
 * Level 1 = warn
 * Level 2 = info
 * Level 3 = debug
 * Level 4 = verbose
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 */
GLOBAL.log = function log(options, message, obj) {

	if (!Array.isArray(message)) {
		message = [message];
	}

	Janeway.print('info', message, options);
};

// Start Janeway only if run inside a terminal
if (!Blast.isNW && process.stdout.isTTY && process.argv.indexOf('--disable-janeway') == -1) {

	Janeway.started = true;
	Janeway.start();

	echo = function echo(msg) {
		Janeway.print('info', Array.cast(arguments), {level: 4});
	};
} else {
	echo = function echo(msg) {
		process.stdout.write(msg);
	};
}

for (key in Janeway.LEVELS) {
	log[key] = Janeway.LEVELS[key];
}

log.stack = function log_stack(amount) {

	if (typeof amount != 'number') {
		amount = 5;
	}

	var stack = alchemy.Janeway.getCallerInfo(amount);

	// Remove the first 2 entries
	stack.stack.shift();
	stack.stack.shift();

	log.debug(stack, {level: 2});
}

var l = function(level, logname, message, options) {

	var trace = '', callerInfo;

	if (typeof options == 'undefined') options = {};

	if (alchemy.settings.log_trace ||
	    alchemy.settings[logname] === true ||
	    options.stack === true) {

		if (typeof options.level == 'undefined') options.level = 0;
		callerInfo = alchemy.Janeway.getCallerInfo(options.level, options.err);
		trace = '['.grey + callerInfo.file.bold + ':' + callerInfo.line.bold + ']'.grey;
		trace += ' ';
	}

}

/**
 * Log messages, level 0: error
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.error = function error(message, options) {

	var broken = 0,
	    stack,
	    extra,
	    info,
	    temp,
	    top,
	    obj,
	    i;

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Colour the message red if it's a string
	if (typeof message == 'string') message = message.red;

	// Add log options
	if (options.name == null) options.name = 'error';
	options.logLevel = 0;

	if (typeof options.level === 'undefined') {
		options.level = 2;
	}

	log(options, message);

	if (options.err) {

		stack = '';
		extra = '';

		top = '\n';
		top += '  ' + String(options.err.message).bold + '\n';
		top += '  Stacktrace using PATH_ROOT: '.bold + PATH_ROOT.yellow.bold;

		info = Janeway.getCallerInfo(0, options.err);

		for (i = 0; i < info.stack.length; i++) {

			obj = info.stack[i];
			temp = (obj.path || '').trim();

			if (obj.name == 'anonymous' && obj.path == 'unknown' && obj.line == 'unknown') {
				broken++;
				continue;
			}

			if (temp.startsWith(PATH_ROOT)) {
				temp = temp.slice(PATH_ROOT.length);
			}

			extra += '\n';
			extra += '  ' + 'Fnc'.bold.underline + ' ' + Number(obj.line||0).toPaddedString(3).bold + ' ' + obj.name.white  + '\n';
			extra += '  ' + '    ' + Number(obj.char||0).toPaddedString(3).bold + ' ' + temp.trim() + ' ' + '\n';
		}

		if (broken) {
			top += '\n' + ('  Error with stack: ' + broken + ' garbage lines!').bold;
		}

		extra = top + '\n' + extra;

		console.log(ansi.reset + ansi.bg.getRgb(3, 0, 0) + extra + ansi.reset);
	}
};

/**
 * Todo messages
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {String}   message   The message to print
 * @param    {Object}   options   Extra options
 */
log.todo = function todo(message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'todo';
	options.logLevel = 0;

	if (!options.level) options.level = 2;

	return log.error(message, options);
};

/**
 * Log messages, level 1: warning
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.warn = function warn(message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'warn';
	options.logLevel = 1;

	if (!options.level) options.level = 2;

	return log(options, message);
};

/**
 * Log messages, level 2: info
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.info = function info(message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'info';
	options.logLevel = 2;

	if (!options.level) options.level = 2;

	return log(options, message);
}

/**
 * Log messages, level 3: debug
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.debug = function debug(message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'debug';
	options.logLevel = 3;

	if (!options.level) options.level = 2;

	return log(options, message);
};

/**
 * Log messages, level 4: verbose
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.verbose = function verbose (message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'verbose';
	options.logLevel = 4;

	if (!options.level) options.level = 2;

	return log(options, message);
}

/**
 * Something to grab attention
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 */
log.attn = function attn(message, options) {

	console.log('\n\n');
	log.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'.yellow.bold, options);
	log.debug(message, {colorize: '\x1B[1m\x1B[34m', level: options.level});
	log.debug('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n'.yellow.bold, options);
};

log.getCallerInfo = Janeway.getCallerInfo;
log.extractLineInfo = Janeway.extractLineInfo;

/**
 * Pretty print debug option, wrapper for log.debug
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 */
global.pr = function pr(message, attn) {
	if (attn) {
		return log.attn(message, {level: 3});
	} else {
		return log.debug(message, {level: 2});
	}
};

/**
 * Print out the keys inside an object
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 */
log.keys = function logKeys (object) {
	pr('>>>>>>>> Logging Keys: ')
	for (var name in object) {
		pr('Keyname: "' + name + '"');
	}
	pr('<<<<<<<<')
}

global.die = function die (message) {
	log.error(message, {level: 2, force: true});
	process.exit();
}<commit_msg>Re-order loggin file to load janeway at the and<commit_after>var STR_PAD_LEFT  = 1,
    STR_PAD_RIGHT = 2,
    STR_PAD_BOTH  = 3,
    consoleWidth  = process.stdout.columns,
    consoleHeight = process.stdout.rows,
    Janeway,
    echo,
    ansi,
    key;

// Listen to console resized
process.stdout.on('resize', function onConsoleResize() {
	consoleWidth  = process.stdout.columns,
	consoleHeight = process.stdout.rows;
});

/**
 * Log messages, level 2: info
 *
 * Level 0 = error
 * Level 1 = warn
 * Level 2 = info
 * Level 3 = debug
 * Level 4 = verbose
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 */
GLOBAL.log = function log(options, message, obj) {

	if (!Array.isArray(message)) {
		message = [message];
	}

	if (Janeway != null) {
		Janeway.print('info', message, options);
	} else {
		console.log(message);
	}
};

log.stack = function log_stack(amount) {

	if (typeof amount != 'number') {
		amount = 5;
	}

	var stack = alchemy.Janeway.getCallerInfo(amount);

	// Remove the first 2 entries
	stack.stack.shift();
	stack.stack.shift();

	log.debug(stack, {level: 2});
}

var l = function(level, logname, message, options) {

	var trace = '', callerInfo;

	if (typeof options == 'undefined') options = {};

	if (alchemy.settings.log_trace ||
	    alchemy.settings[logname] === true ||
	    options.stack === true) {

		if (typeof options.level == 'undefined') options.level = 0;
		callerInfo = alchemy.Janeway.getCallerInfo(options.level, options.err);
		trace = '['.grey + callerInfo.file.bold + ':' + callerInfo.line.bold + ']'.grey;
		trace += ' ';
	}

}

/**
 * Log messages, level 0: error
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.error = function error(message, options) {

	var broken = 0,
	    stack,
	    extra,
	    info,
	    temp,
	    top,
	    obj,
	    i;

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Colour the message red if it's a string
	if (typeof message == 'string') message = message.red;

	// Add log options
	if (options.name == null) options.name = 'error';
	options.logLevel = 0;

	if (typeof options.level === 'undefined') {
		options.level = 2;
	}

	log(options, message);

	if (options.err) {

		stack = '';
		extra = '';

		top = '\n';
		top += '  ' + String(options.err.message).bold + '\n';
		top += '  Stacktrace using PATH_ROOT: '.bold + PATH_ROOT.yellow.bold;

		if (Janeway != null) {
			info = Janeway.getCallerInfo(0, options.err);

			for (i = 0; i < info.stack.length; i++) {

				obj = info.stack[i];
				temp = (obj.path || '').trim();

				if (obj.name == 'anonymous' && obj.path == 'unknown' && obj.line == 'unknown') {
					broken++;
					continue;
				}

				if (temp.startsWith(PATH_ROOT)) {
					temp = temp.slice(PATH_ROOT.length);
				}

				extra += '\n';
				extra += '  ' + 'Fnc'.bold.underline + ' ' + Number(obj.line||0).toPaddedString(3).bold + ' ' + obj.name.white  + '\n';
				extra += '  ' + '    ' + Number(obj.char||0).toPaddedString(3).bold + ' ' + temp.trim() + ' ' + '\n';
			}
		}

		if (broken) {
			top += '\n' + ('  Error with stack: ' + broken + ' garbage lines!').bold;
		}

		extra = top + '\n' + extra;

		if (ansi != null) {
			console.log(ansi.reset + ansi.bg.getRgb(3, 0, 0) + extra + ansi.reset);
		} else {
			console.log(extra);
		}
	}
};

/**
 * Todo messages
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {String}   message   The message to print
 * @param    {Object}   options   Extra options
 */
log.todo = function todo(message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'todo';
	options.logLevel = 0;

	if (!options.level) options.level = 2;

	return log.error(message, options);
};

/**
 * Log messages, level 1: warning
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.warn = function warn(message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'warn';
	options.logLevel = 1;

	if (!options.level) options.level = 2;

	return log(options, message);
};

/**
 * Log messages, level 2: info
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.info = function info(message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'info';
	options.logLevel = 2;

	if (!options.level) options.level = 2;

	return log(options, message);
}

/**
 * Log messages, level 3: debug
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  1.0.0
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.debug = function debug(message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'debug';
	options.logLevel = 3;

	if (!options.level) options.level = 2;

	return log(options, message);
};

/**
 * Log messages, level 4: verbose
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {string}   message   The message to print
 * @param    {object}   options   Extra options
 */
log.verbose = function verbose (message, options) {

	// Make sure the options var is an object
	if (typeof options == 'undefined') options = {};

	// Add log options
	options.name = 'verbose';
	options.logLevel = 4;

	if (!options.level) options.level = 2;

	return log(options, message);
}

/**
 * Something to grab attention
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 */
log.attn = function attn(message, options) {

	console.log('\n\n');
	log.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'.yellow.bold, options);
	log.debug(message, {colorize: '\x1B[1m\x1B[34m', level: options.level});
	log.debug('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n'.yellow.bold, options);
};

/**
 * Pretty print debug option, wrapper for log.debug
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 */
global.pr = function pr(message, attn) {
	if (attn) {
		return log.attn(message, {level: 3});
	} else {
		return log.debug(message, {level: 2});
	}
};

/**
 * Print out the keys inside an object
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 */
log.keys = function logKeys (object) {
	pr('>>>>>>>> Logging Keys: ')
	for (var name in object) {
		pr('Keyname: "' + name + '"');
	}
	pr('<<<<<<<<')
}

global.die = function die (message) {
	log.error(message, {level: 2, force: true});
	process.exit();
}

alchemy.use('colors');
Janeway = alchemy.use('janeway');
ansi = alchemy.use('ansi-256-colors')
alchemy.Janeway = Janeway;

log.getCallerInfo = Janeway.getCallerInfo;
log.extractLineInfo = Janeway.extractLineInfo;

// Start Janeway only if run inside a terminal
if (!Blast.isNW && process.stdout.isTTY && process.argv.indexOf('--disable-janeway') == -1) {

	Janeway.started = true;
	Janeway.start();

	echo = function echo(msg) {
		Janeway.print('info', Array.cast(arguments), {level: 4});
	};
} else {
	echo = function echo(msg) {
		process.stdout.write(msg);
	};
}

for (key in Janeway.LEVELS) {
	log[key] = Janeway.LEVELS[key];
}<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 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 _ = require('../../../utils/under-dash');

var utils = require('../../../utils/utils');
var colCache = require('../../../utils/col-cache');
var XmlStream = require('../../../utils/xml-stream');

var BaseXform = require('../base-xform');
var StaticXform = require('../static-xform');
var ListXform = require('../list-xform');
var DefinedNameXform = require('./defined-name-xform');
var SheetXform = require('./sheet-xform');
var WorkbookViewXform = require('./workbook-view-xform');
var WorkbookPropertiesXform = require('./workbook-properties-xform');

var WorkbookXform = module.exports = function() {
  this.map = {
    fileVersion: WorkbookXform.STATIC_XFORMS.fileVersion,
    workbookPr: new WorkbookPropertiesXform(),
    bookViews: new ListXform({tag: 'bookViews', count: false, childXform: new WorkbookViewXform()}),
    sheets: new ListXform({tag: 'sheets', count: false, childXform: new SheetXform()}),
    definedNames: new ListXform({tag: 'definedNames', count: false, childXform: new DefinedNameXform()}),
    calcPr: WorkbookXform.STATIC_XFORMS.calcPr
  };
};

utils.inherits(WorkbookXform, BaseXform, {
  WORKBOOK_ATTRIBUTES: {
    xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
    'xmlns:r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
    'xmlns:mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
    'mc:Ignorable': 'x15',
    'xmlns:x15': 'http://schemas.microsoft.com/office/spreadsheetml/2010/11/main'
  },
  STATIC_XFORMS: {
    fileVersion: new StaticXform({tag: 'fileVersion', $: {appName: 'xl', lastEdited: 5, lowestEdited: 5, rupBuild: 9303}}),
    calcPr: new StaticXform({tag: 'calcPr', $: {calcId: 171027}})
  }
}, {

  prepare: function(model) {
    model.sheets = model.worksheets;

    // collate all the print areas from all of the sheets and add them to the defined names
    var printAreas = [];
    var index = 0; // sheets is sparse array - calc index manually
    model.sheets.forEach(function(sheet) {
      if (sheet.pageSetup && sheet.pageSetup.printArea) {
        var definedName = {
          name: '_xlnm.Print_Area',
          ranges: ['\'' + sheet.name + '\'!' + sheet.pageSetup.printArea],
          localSheetId: index
        };
        printAreas.push(definedName);
      }
      index++;
    });
    if (printAreas.length) {
      model.definedNames = model.definedNames.concat(printAreas);
    }

    model.media && model.media.forEach(function(medium, i) {
      // assign name
      medium.name = medium.type + (i + 1);
    });
  },

  render: function(xmlStream, model) {
    xmlStream.openXml(XmlStream.StdDocAttributes);
    xmlStream.openNode('workbook', WorkbookXform.WORKBOOK_ATTRIBUTES);

    this.map.fileVersion.render(xmlStream);
    this.map.workbookPr.render(xmlStream, model.properties);
    this.map.bookViews.render(xmlStream, model.views);
    this.map.sheets.render(xmlStream, model.sheets);
    this.map.definedNames.render(xmlStream, model.definedNames);
    this.map.calcPr.render(xmlStream);

    xmlStream.closeNode();
  },

  parseOpen: function(node) {
    if (this.parser) {
      this.parser.parseOpen(node);
      return true;
    }
    switch (node.name) {
      case 'workbook':
        return true;
      default:
        this.parser = this.map[node.name];
        if (this.parser) {
          this.parser.parseOpen(node);
        }
        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 'workbook':
        this.model = {
          sheets: this.map.sheets.model,
          properties: this.map.workbookPr.model,
          views: this.map.bookViews.model
        };
        if (this.map.definedNames.model) {
          this.model.definedNames = this.map.definedNames.model;
        }

        return false;
      default:
        // not quite sure how we get here!
        return true;
    }
  },

  reconcile: function(model) {
    var rels = model.workbookRels.reduce(function(map, rel) {
      map[rel.Id] = rel;
      return map;
    }, {});

    // reconcile sheet ids, rIds and names
    var worksheets = [];
    var worksheet;
    var index = 0;

    model.sheets.forEach(function(sheet) {
      var rel = rels[sheet.rId];
      if (!rel) {
        return;
      }
      worksheet = model.worksheetHash['xl/' + rel.Target];
      worksheet.name = sheet.name;
      worksheet.id = sheet.id;
      worksheets[index++] = worksheet;
    });

    // reconcile print areas
    var definedNames = [];
    _.each(model.definedNames, function(definedName) {
      if (definedName.name === '_xlnm.Print_Area') {
        worksheet = worksheets[definedName.localSheetId];
        if (worksheet) {
          if (!worksheet.pageSetup) { worksheet.pageSetup = {}; }
          var range = colCache.decodeEx(definedName.ranges[0]);
          worksheet.pageSetup.printArea = range.dimensions;
        }
      } else {
        definedNames.push(definedName);
      }
    });
    model.definedNames = definedNames;

    // used by sheets to build their image models
    model.media.forEach((media, i) => {
      media.index = i;
    });
  }
});
<commit_msg>printTitlesRow support<commit_after>/**
 * Copyright (c) 2016 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 _ = require('../../../utils/under-dash');

var utils = require('../../../utils/utils');
var colCache = require('../../../utils/col-cache');
var XmlStream = require('../../../utils/xml-stream');

var BaseXform = require('../base-xform');
var StaticXform = require('../static-xform');
var ListXform = require('../list-xform');
var DefinedNameXform = require('./defined-name-xform');
var SheetXform = require('./sheet-xform');
var WorkbookViewXform = require('./workbook-view-xform');
var WorkbookPropertiesXform = require('./workbook-properties-xform');

var WorkbookXform = module.exports = function() {
  this.map = {
    fileVersion: WorkbookXform.STATIC_XFORMS.fileVersion,
    workbookPr: new WorkbookPropertiesXform(),
    bookViews: new ListXform({tag: 'bookViews', count: false, childXform: new WorkbookViewXform()}),
    sheets: new ListXform({tag: 'sheets', count: false, childXform: new SheetXform()}),
    definedNames: new ListXform({tag: 'definedNames', count: false, childXform: new DefinedNameXform()}),
    calcPr: WorkbookXform.STATIC_XFORMS.calcPr
  };
};

utils.inherits(WorkbookXform, BaseXform, {
  WORKBOOK_ATTRIBUTES: {
    xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
    'xmlns:r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
    'xmlns:mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
    'mc:Ignorable': 'x15',
    'xmlns:x15': 'http://schemas.microsoft.com/office/spreadsheetml/2010/11/main'
  },
  STATIC_XFORMS: {
    fileVersion: new StaticXform({tag: 'fileVersion', $: {appName: 'xl', lastEdited: 5, lowestEdited: 5, rupBuild: 9303}}),
    calcPr: new StaticXform({tag: 'calcPr', $: {calcId: 171027}})
  }
}, {

  prepare: function(model) {
    model.sheets = model.worksheets;

    // collate all the print areas from all of the sheets and add them to the defined names
    var printAreas = [];
    var index = 0; // sheets is sparse array - calc index manually
    model.sheets.forEach(function(sheet) {
      if (sheet.pageSetup && sheet.pageSetup.printArea) {
        var definedName = {
          name: '_xlnm.Print_Area',
          ranges: ['\'' + sheet.name + '\'!' + sheet.pageSetup.printArea],
          localSheetId: index
        };
        printAreas.push(definedName);
      }
      if (sheet.pageSetup && sheet.pageSetup.printTitlesRow) {

                var titlesRows = sheet.pageSetup.printTitlesRow.split(':');

                var definedName = {
                    name: '_xlnm.Print_Titles',
                    ranges: ['\'' + sheet.name + '\'!$' + titlesRows[0] + ':$' + titlesRows[1]],
                    localSheetId: index
                };
                printAreas.push(definedName);
            }
      index++;
    });
    if (printAreas.length) {
      model.definedNames = model.definedNames.concat(printAreas);
    }

    model.media && model.media.forEach(function(medium, i) {
      // assign name
      medium.name = medium.type + (i + 1);
    });
  },

  render: function(xmlStream, model) {
    xmlStream.openXml(XmlStream.StdDocAttributes);
    xmlStream.openNode('workbook', WorkbookXform.WORKBOOK_ATTRIBUTES);

    this.map.fileVersion.render(xmlStream);
    this.map.workbookPr.render(xmlStream, model.properties);
    this.map.bookViews.render(xmlStream, model.views);
    this.map.sheets.render(xmlStream, model.sheets);
    this.map.definedNames.render(xmlStream, model.definedNames);
    this.map.calcPr.render(xmlStream);

    xmlStream.closeNode();
  },

  parseOpen: function(node) {
    if (this.parser) {
      this.parser.parseOpen(node);
      return true;
    }
    switch (node.name) {
      case 'workbook':
        return true;
      default:
        this.parser = this.map[node.name];
        if (this.parser) {
          this.parser.parseOpen(node);
        }
        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 'workbook':
        this.model = {
          sheets: this.map.sheets.model,
          properties: this.map.workbookPr.model,
          views: this.map.bookViews.model
        };
        if (this.map.definedNames.model) {
          this.model.definedNames = this.map.definedNames.model;
        }

        return false;
      default:
        // not quite sure how we get here!
        return true;
    }
  },

  reconcile: function(model) {
    var rels = model.workbookRels.reduce(function(map, rel) {
      map[rel.Id] = rel;
      return map;
    }, {});

    // reconcile sheet ids, rIds and names
    var worksheets = [];
    var worksheet;
    var index = 0;

    model.sheets.forEach(function(sheet) {
      var rel = rels[sheet.rId];
      if (!rel) {
        return;
      }
      worksheet = model.worksheetHash['xl/' + rel.Target];
      worksheet.name = sheet.name;
      worksheet.id = sheet.id;
      worksheets[index++] = worksheet;
    });

    // reconcile print areas
    var definedNames = [];
    _.each(model.definedNames, function(definedName) {
      if (definedName.name === '_xlnm.Print_Area') {
        worksheet = worksheets[definedName.localSheetId];
        if (worksheet) {
          if (!worksheet.pageSetup) { worksheet.pageSetup = {}; }
          var range = colCache.decodeEx(definedName.ranges[0]);
          worksheet.pageSetup.printArea = range.dimensions;
        }
      } else {
        definedNames.push(definedName);
      }
    });
    model.definedNames = definedNames;

    // used by sheets to build their image models
    model.media.forEach((media, i) => {
      media.index = i;
    });
  }
});
<|endoftext|>


<commit_before>module.exports = class {
  constructor(app, log, container) {
    this.app = app
    this.log = log
    this.container = container
  }

  async run() {
    let files = this.app.glob('initializers/*.js', { dirs: ['quadro', 'app'] })
    return Promise.map(files, _ => this.runInitializer(_))
  }

  async runInitializer(file) {
    Q.profiler.profile({ file }, `Initializer`, async () => {
      let Init = require(file)
      if (typeof Init === 'function') {
        try {
          await this.container.create(Init)
        } catch (err) {
          this.log.error({ err, file }, 'Error initializing. Stopping...')
          process.exit(1)
        }
      }
    })
  }
}
<commit_msg>Issue:125 Allow restricting initializers in environments<commit_after>const path = require('path')
module.exports = class {
  constructor(app, log, container, config) {
    this.app = app
    this.log = log
    this.container = container
    this.config = config
  }

  async run() {
    let files = this.app.glob('initializers/*.js', { dirs: ['quadro', 'app'] })
    return Promise.filter(files, _ => this.shouldInitialize(_)).map(_ => this.runInitializer(_))
  }

  async runInitializer(file) {
    Q.profiler.profile({ file }, `Initializer`, async () => {
      let Init = require(file)
      if (typeof Init === 'function') {
        try {
          await this.container.create(Init)
        } catch (err) {
          this.log.error({ err, file }, 'Error initializing. Stopping...')
          process.exit(1)
        }
      }
    })
  }

  async shouldInitialize(file) {
    return this.config.get(`quadro.initializers.${path.basename(file, path.extname(file))}`, true)
  }
}
<|endoftext|>