text:
var StatsModel = {};

(function (self) {
  // starts future.get with given ajaxOptions and arranges invocation
  // of 'body' with value or if future is cancelled invocation of body
  // with 'cancelledValue'.
  //
  // NOTE: this is not normal future as normal futures deliver values
  // to cell, but this one 'delivers' values to given function 'body'.
  function getCPS(ajaxOptions, cancelledValue, body) {
    // this wrapper calls 'body' instead of delivering value to it's
    // cell
    var futureWrapper = future.wrap(function (ignoredDataCallback, startGet) {
      return startGet(body);
    });
    var async = future.get(ajaxOptions, undefined, undefined, futureWrapper);
    async.cancel = (function (realCancel) {
      return function () {
        if (realCancel) {
          realCancel.call(this);
        }
        body(cancelledValue);
      }
    })(async.cancel);
    // we need any cell here to satisfy our not yet perfect API
    async.start(new Cell());
    return async;
  }

  function createSamplesFuture(statsURL, statsData, bufferDepth, realTimeRestorer) {
    var cancelMark = {};
    var mark404 = {};

    function doGet(data, body) {
      if (mainAsync.cancelled) {
        return body(cancelMark);
      }

      function onCancel() {
        async.cancel();
      }
      function unbind() {
        $(mainAsync).unbind('cancelled', onCancel);
      }
      $(mainAsync).bind('cancelled', onCancel);

      var async;
      return async = getCPS({url: statsURL, data: data, missingValue: mark404}, cancelMark, function (value, status, xhr) {
        unbind();
        if (value !== cancelMark && value !== mark404) {
          var date = xhr.getResponseHeader('date');
          value.serverDate = parseHTTPDate(date).valueOf();
          value.clientDate = (new Date()).valueOf();
        }
        body(value, status, xhr);
      });
    }

    var mainAsync = future(function (dataCallback) {
      function deliverValue(value) {
        return dataCallback.continuing(value);
      }
      nonRealtimeLoop(deliverValue);
    });
    mainAsync.cancel = function () {
      $(this).trigger('cancelled');
    }

    return mainAsync;

    function nonRealtimeLoop(deliverValue) {
      doGet(statsData, function (value) {
        if (value === cancelMark || value === mark404) {
          return;
        }

        deliverValue(value);

        // this is the only non-generic place in this function. We're
        // able to extract interval from specific and from normal
        // stats
        var interval = value.interval || value.op.interval;
        if (interval < 2000) {
          startRealTimeLoop(deliverValue, value);
        } else {
          setTimeout(function () {
            nonRealtimeLoop(deliverValue);
          }, Math.min(interval/2, 60000));
        }
      });
    }

    function startRealTimeLoop(realDeliverValue, value) {
      // we're going to actually deliver values each second and
      // deliverValue we pass to loop just stores last value
      function deliverValue(val) {
        value = val;
      }
      var intervalId = setInterval(function () {
        realDeliverValue(_.clone(value));
      }, 1000);

      function onCancel() {
        clearInterval(intervalId);
        unbind();
      }
      function unbind() {
        $(mainAsync).unbind('cancelled', onCancel);
      }
      $(mainAsync).bind('cancelled', onCancel);

      realTimeLoop(deliverValue, value, realTimeRestorer);
    }

    function realTimeLoop(deliverValue, lastValue, realTimeRestorer) {
      realTimeRestorer(lastValue, statsData, bufferDepth, function (data, restorer) {
        doGet(data, function (rawStats) {
          if (rawStats === cancelMark || rawStats === mark404) {
            return;
          }

          var restoredValue = restorer(rawStats);
          deliverValue(restoredValue);
          realTimeLoop(deliverValue, restoredValue, realTimeRestorer);
        });
      });
    }
  }

  // Prepares data for stats request and returns it and stats
  // restoring function. This code is calling continuation 'cont' with
  // two arguments rather then returning array with two elements (and
  // then having to unpack at call-site).
  //
  // Returned stats restoring function will then be called with result
  // of get request and is responsible for building complete stats
  // from old sample it has and new result.
  function aggregateRealTimeRestorer(lastValue, statsData, bufferDepth, mvReturn) {
    var keepCount = lastValue.op.samplesCount + bufferDepth;
    var data = statsData;

    if (lastValue.op.lastTStamp) {
      data = _.extend({haveTStamp: lastValue.op.lastTStamp}, data);
    } else {
      // if we don't have any stats, pause a bit, dont send new stats
      // request immediately. Because doing so will return immediately
      // making us send another request and so on, spamming server.
      setTimeout(function () {
        mvReturn(data, restorer);
      }, 1000);
      return;
    }

    return mvReturn(data, restorer);
    function restorer(rawStats) {
      var op = rawStats.op;

      var samples = op.samples;
      // if we have empty stats re-use previous value instead of rendering empty stats
      if (samples && samples.timestamp.length === 0) {
        return lastValue;
      }

      if (lastValue === undefined) {
        return rawStats;
      }

      var newSamples = {};
      var prevSamples = lastValue.op.samples;

      if (prevSamples.timestamp === undefined ||
          prevSamples.timestamp.length === 0 ||
          prevSamples.timestamp[prevSamples.timestamp.length - 1] != samples.timestamp[0]) {
        return rawStats;
      }

      for (var keyName in samples) {
        newSamples[keyName] = prevSamples[keyName].concat(samples[keyName].slice(1)).slice(-keepCount);
      }

      var restored = _.clone(rawStats);
      restored.op = _.clone(op);
      restored.op.samples = newSamples;

      return restored;
    }
  }

  function specificStatsRealTimeRestorer(lastValue, statsData, bufferDepth, mvReturn) {
    var keepCount = lastValue.samplesCount + bufferDepth;
    var data = statsData;

    if (lastValue.lastTStamp) {
      data = _.extend({haveTStamp: lastValue.lastTStamp}, data);
    } else {
      // if we don't have any stats, pause a bit, dont send new stats
      // request immediately. Because doing so will return immediately
      // making us send another request and so on, spamming server.
      setTimeout(function () {
        mvReturn(data, restorer);
      }, 1000);
      return;
    }

    return mvReturn(data, restorer);
    function restorer(rawStats) {
      // if we have empty stats re-use previous value instead of rendering empty stats
      if (rawStats.timestamp.length === 0) {
        return lastValue;
      }

      if (lastValue === undefined ||
          lastValue.timestamp === undefined ||
          lastValue.timestamp.length === 0 ||
          lastValue.timestamp[lastValue.timestamp.length - 1] != rawStats.timestamp[0]) {
        return rawStats;
      }

      var samples = rawStats.nodeStats;

      var newSamples = {};
      var prevSamples = lastValue.nodeStats;

      for (var keyName in samples) {
        newSamples[keyName] = prevSamples[keyName].concat(samples[keyName].slice(1)).slice(-keepCount);
      }

      var newTimestamp = lastValue.timestamp.concat(rawStats.timestamp.slice(1)).slice(-keepCount);

      var restored = _.clone(rawStats);
      restored.nodeStats = newSamples;
      restored.timestamp = newTimestamp;

      return restored;
    }
  }

  var statsBucketURL = self.statsBucketURL = new StringHashFragmentCell("statsBucket");
  var statsHostname = self.statsHostname = new StringHashFragmentCell("statsHostname");
  var statsStatName = self.statsStatName = new StringHashFragmentCell("statsStatName");

  // contains bucket details of statsBucketURL bucket (or default if there are no such bucket)
  var statsBucketDetails = self.statsBucketDetails = Cell.compute(function (v) {
    var uri = v(statsBucketURL);
    var buckets = v.need(DAL.cells.bucketsListCell);
    var rv;
    if (uri !== undefined) {
      rv = _.detect(buckets, function (info) {return info.uri === uri});
    } else {
      rv = _.detect(buckets, function (info) {return info.name === "default"}) || buckets[0];
    }
    return rv;
  }).name("statsBucketDetails");

  self.knownHostnamesCell = Cell.compute(function (v) {
    var allNames = _.pluck(v.need(DAL.cells.serversCell).allNodes, 'hostname').sort();
    var activeNames = _.pluck(v.need(DAL.cells.serversCell).active, 'hostname').sort();
    return {all: allNames, active: activeNames};
  }).name("knownHostnamesCell");
  self.knownHostnamesCell.equality = _.isEqual;

  // contains list of links to per-node stats for particular bucket
  var statsNodesCell = self.statsNodesCell = Cell.compute(function (v) {
    v.need(self.knownHostnamesCell); // this cell should be refreshed
                                     // when list of known nodes
                                     // changes
    return future.get({url: v.need(statsBucketDetails).stats.nodeStatsListURI});
  }).name("statsNodesCell");

  var statsOptionsCell = self.statsOptionsCell = (new Cell()).name("statsOptionsCell");
  statsOptionsCell.setValue({nonQ: ['keysInterval', 'nonQ'], resampleForUI: '1'});
  _.extend(statsOptionsCell, {
    update: function (options) {
      this.modifyValue(_.bind($.extend, $, {}), options);
    },
    equality: _.isEqual
  });

  var samplesBufferDepthRAW = new StringHashFragmentCell("statsBufferDepth");
  self.samplesBufferDepth = Cell.computeEager(function (v) {
    return v(samplesBufferDepthRAW) || 1;
  });

  var statsDirectoryURLCell = self.statsDirectoryURLCell = Cell.compute(function (v) {
    if (v.need(DAL.cells.mode) !== 'analytics') {
      return;
    }
    return v.need(statsBucketDetails).stats.directoryURI;
  }).name("statsDirectoryURLCell");

  var rawStatsDescCell = self.rawStatsDescCell = Cell.compute(function (v) {
    return future.get({url: v.need(statsDirectoryURLCell)});
  }).name("rawStatsDescCell");

  var nameToStatInfoCell = Cell.compute(function (v) {
    var desc = v.need(rawStatsDescCell);
    var allStatsInfos = [].concat.apply([], _.pluck(desc.blocks, 'stats'));
    var rv = {};
    _.each(allStatsInfos, function (info) {
      rv[info.name] = info;
    });
    return rv;
  }).name("nameToStatInfoCell");

  var specificStatsInfo = Cell.compute(function (v) {
    var statName = v(statsStatName);
    if (!statName) {
      return {url: null, statName: null, desc: null};
    }
    var mapping = v.need(nameToStatInfoCell);
    if (!mapping[statName]) {
      return {url: null, statName: null, desc: null};
    }
    return {url: mapping[statName].specificStatsURL,
            statName: statName, desc: mapping[statName].desc};
  }).name("specificStatsInfo");

  var effectiveSpecificStatName = self.effectiveSpecificStatName = Cell.compute(function (v) {
    return v.need(specificStatsInfo).statName;
  }).name("effectiveSpecificStatName");
  effectiveSpecificStatName.equality = function (a,b) {return a===b};

  var specificStatsURLCell = self.specificStatsURLCell = Cell.compute(function (v) {
    return v.need(specificStatsInfo).url;
  }).name("specificStatsURLCell");
  specificStatsURLCell.equality = function (a,b) {return a===b};

  var specificStatDescriptionCell = self.specificStatDescriptionCell = Cell.compute(function (v) {
    return v.need(specificStatsInfo).desc;
  }).name("specificStatDescriptionCell");
  specificStatDescriptionCell.equality = function (a,b) {return a===b};

  // true if we should be displaying specific stats and false if we should be displaying normal stats
  var displayingSpecificStatsCell = self.displayingSpecificStatsCell = Cell.compute(function (v) {
    return !!v.need(specificStatsURLCell);
  }).name("displayingSpecificStatsCell");

  // contains either bucket info or per-node stat info (as found in
  // statsNodesCell response) for which (normal) stats are displayed
  var targetCell = self.targetCell = Cell.compute(function (v) {
    if (v.need(DAL.cells.mode) !== 'analytics' || v.need(displayingSpecificStatsCell)) {
      return;
    }

    var hostname = v(statsHostname);
    if (!hostname) {
      return v.need(statsBucketDetails);
    }

    var nodes = v.need(statsNodesCell);
    var nodeInfo = _.detect(nodes.servers, function (info) {return info.hostname === hostname});
    if (!nodeInfo) {
      return v.need(statsBucketDetails);
    }

    return nodeInfo;
  }).name("targetCell");

  var statsURLCell = self.statsURLCell = Cell.compute(function (v) {
    return v.need(targetCell).stats.uri;
  }).name("statsURLCell");

  var zoomLevel;
  (function () {
    var slider = $("#js_date_slider").slider({
      orientation: "vertical",
      range: "min",
      min: 1,
      max: 6,
      value: 6,
      step: 1,
      slide: function(event, ui) {
        var dateSwitchers = $("#js_date_slider_container .js_click");
        dateSwitchers.eq(dateSwitchers.length - ui.value).trigger('click');
      }
    });

    zoomLevel = (new LinkSwitchCell('zoom', {
      firstItemIsDefault: true
    })).name("zoomLevel");

    _.each('minute hour day week month year'.split(' '), function (name) {
      zoomLevel.addItem('js_zoom_' + name, name);
    });

    zoomLevel.finalizeBuilding();

    zoomLevel.subscribeValue(function (zoomLevel) {
      var z = $('#js_zoom_' + zoomLevel);
      slider.slider('value', 6 - z.index());
      self.statsOptionsCell.update({
        zoom: zoomLevel
      });
    });
  })();

  self.zoomLevel = zoomLevel;

  var statsCell = self.statsCell = Cell.compute(function (v) {
    if (v.need(DAL.cells.mode) != 'analytics') {
      return;
    }
    var options = v.need(statsOptionsCell);
    var url = v.need(statsURLCell);

    var data = _.extend({}, options);
    _.each(data.nonQ, function (n) {
      delete data[n];
    });

    var bufferDepth = v.need(self.samplesBufferDepth);

    return createSamplesFuture(url, data, bufferDepth, aggregateRealTimeRestorer);
  }).name("statsCell");

  var specificStatsCell = self.specificStatsCell = Cell.compute(function (v) {
    if (v.need(DAL.cells.mode) != 'analytics') {
      return;
    }

    var url = v(specificStatsURLCell);
    if (!url) { // we're 'expecting' null here too
      return;
    }
    var options = v.need(statsOptionsCell);

    var data = _.extend({}, options);
    _.each(data.nonQ, function (n) {
      delete data[n];
    });

    var bufferDepth = v.need(self.samplesBufferDepth);

    return createSamplesFuture(url, data, bufferDepth, specificStatsRealTimeRestorer);
  }).name("specificStatsCell");

  // containts list of hostnames for specific stats ordered by natural
  // sort order of hostname or ip
  var specificStatsNodesCell = Cell.compute(function (v) {
    return _.keys(v.need(specificStatsCell).nodeStats).sort(naturalSort);
  }).name("specificStatsNodesCell");

  var visibleStatsDescCell = self.visibleStatsDescCell = Cell.compute(function (v) {
    if (v.need(displayingSpecificStatsCell)) {
      var nodes = v.need(specificStatsNodesCell);
      var statsDesc = v.need(specificStatDescriptionCell);
      return {thisISSpecificStats: true,
              blocks: [{blockName: "Specific Stats", hideThis: true,
                        stats: _.map(nodes, function (hostname) {
                          return {title: ViewHelpers.maybeStripPort(hostname, nodes),
                                  name: hostname, desc: statsDesc};
                        })}]};
    } else {
      return v.need(rawStatsDescCell);
    }
  }).name("visibleStatsDescCell");

  self.infosCell = Cell.needing(visibleStatsDescCell).compute(function (v, statDesc) {
    statDesc = JSON.parse(JSON.stringify(statDesc)); // this makes deep copy of statDesc

    var infos = [];
    infos.byName = {};

    var statItems = [];
    var blockIDs = [];

    var hadServerResources = false;
    if (statDesc.blocks[0].serverResources) {
      // We want it last so that default stat name (which is first
      // statItems entry) is not from ServerResourcesBlock
      hadServerResources = true;
      statDesc.blocks = statDesc.blocks.slice(1).concat([statDesc.blocks[0]]);
    }
    _.each(statDesc.blocks, function (aBlock) {
      var blockName = aBlock.blockName;
      aBlock.id = _.uniqueId("GB");
      blockIDs.push(aBlock.id);
      var stats = aBlock.stats;
      statItems = statItems.concat(stats);
      _.each(stats, function (statInfo) {
        statInfo.id = _.uniqueId("G");
        statInfo.blockId = aBlock.id;
      });
    });
    // and now make ServerResourcesBlock first for rendering
    if (hadServerResources) {
      statDesc.blocks.unshift(statDesc.blocks.pop());
    }
    _.each(statItems, function (item) {
      infos.push(item);
      infos.byName[item.name] = item;
    });
    infos.blockIDs = blockIDs;

    return {statDesc: statDesc, infos: infos};
  }).name("infosCell");

  self.statsDescInfoCell = Cell.needing(self.infosCell).compute(function (v, infos) {
    return infos.statDesc;
  }).name("statsDescInfoCell");

  self.selectedGraphNameCell = (new StringHashFragmentCell("graph")).name("selectedGraphNameCell");

  self.configurationExtra = (new Cell()).name("configurationExtra");

  self.smallGraphSelectionCellCell = Cell.compute(function (v) {
    return v.need(displayingSpecificStatsCell) ? self.statsHostname : self.selectedGraphNameCell;
  }).name("smallGraphSelectionCellCell");

  self.aggregateGraphsConfigurationCell = Cell.compute(function (v) {
    var selectedGraphName = v(self.selectedGraphNameCell);
    var stats = v.need(self.statsCell);
    var selected;

    var infos = v.need(self.infosCell).infos;
    if (!selectedGraphName || !(selectedGraphName in infos.byName)) {
      selected = infos[0];
    } else {
      selected = infos.byName[selectedGraphName];
    }

    var op = stats.op;
    if (!op) {
      BUG();
    }

    if (!op.samples[selected.name]) {
      selected = _.detect(infos, function (info) {return op.samples[info.name];}) || selected;
    }

    return {
      interval: op.interval,
      zoomLevel: v.need(zoomLevel),
      selected: selected,
      samples: op.samples,
      timestamp: op.samples.timestamp,
      serverDate: stats.serverDate,
      clientDate: stats.clientDate,
      infos: infos,
      extra: v(self.configurationExtra)
    };
  }).name("aggregateGraphsConfigurationCell");

  self.specificGraphsConfigurationCell = Cell.compute(function (v) {
    var infos = v.need(self.infosCell).infos;
    var stats = v.need(specificStatsCell);
    var selectedHostname = v(statsHostname);
    var selected;

    var infos = v.need(self.infosCell).infos;
    if (!selectedHostname || !(selectedHostname in infos.byName)) {
      selected = infos[0];
    } else {
      selected = infos.byName[selectedHostname];
    }

    if (!stats.nodeStats[selected.name]) {
      selected = _.detect(infos, function (info) {return stats.nodeStats[info.name];}) || selected;
    }

    return {
      interval: stats.interval,
      zoomLevel: v.need(zoomLevel),
      selected: selected,
      samples: stats.nodeStats,
      timestamp: stats.timestamp,
      serverDate: stats.serverDate,
      clientDate: stats.clientDate,
      infos: infos,
      extra: v(self.configurationExtra)
    };
  }).name("specificGraphsConfigurationCell");

  self.specificStatsNamesSetCell = Cell.compute(function (v) {
    var rawDesc = v.need(rawStatsDescCell);
    var knownDescTexts = {};
    var allStatInfos = [].concat.apply([], _.pluck(rawDesc.blocks, 'stats'));

    _.each(allStatInfos, function (statInfo) {
      if (statInfo.missing) {
        return;
      }
      knownDescTexts[statInfo.title] = (knownDescTexts[statInfo.title] || 0) + 1;
    });

    var markedNames = {};
    var result = [];
    _.each(rawDesc.blocks, function (blockInfo) {
      _.each(blockInfo.stats, function (statInfo, idx) {
        var title = statInfo.title;
        if (!title) {
          throw new Error();
        }
        if (knownDescTexts[title] > 1 && blockInfo.columns) {
          // we have 'shared name'. So let's 'unshare' it be prepending column name
          title = blockInfo.columns[idx % 4] + ' ' + title;
        }
        var name = statInfo.name;
        if (markedNames[name]) {
          return;
        }
        result.push([name, title]);
        markedNames[name] = true;
      });
    });

    result = _.sortBy(result, function (r) {return r[1]});

    var byName = result.byName = {};
    _.each(result, function (pair) {
      byName[pair[0]] = pair;
    });

    return result;
  }).name("specificStatsNamesSetCell");

  self.graphsConfigurationCell = Cell.compute(function (v) {
    if (v.need(self.displayingSpecificStatsCell)) {
      return v.need(self.specificGraphsConfigurationCell);
    } else {
      return v.need(self.aggregateGraphsConfigurationCell);
    }
  }).name("graphsConfigurationCell");

  self.hotKeysCell = Cell.compute(function (v) {
    if (v.need(displayingSpecificStatsCell)) {
      return null;
    }
    return v.need(statsCell).hot_keys;
  }).name("hotKeysCell");
  self.hotKeysCell.equality = function (a,b) {return a===b;};

})(StatsModel);

var maybeReloadAppDueToLeak = (function () {
  var counter = 300;

  return function () {
    if (!window.G_vmlCanvasManager)
      return;

    if (!--counter)
      reloadPage();
  };
})();

;(function (global) {

  var queuedUpdates = [];

  function flushQueuedUpdate() {
    var i = queuedUpdates.length;
    while (--i >= 0) {
      queuedUpdates[i]();
    }
    queuedUpdates.length = 0;
  }

  var shadowSize = 3;

  if (window.G_vmlCanvasManager) {
    shadowSize = 0;
  }

  function renderSmallGraph(jq, options) {
    function reqOpt(name) {
      var rv = options[name];
      if (rv === undefined)
        throw new Error("missing option: " + name);
      return rv;
    }
    var data = reqOpt('data');
    var now = reqOpt('now');
    var plotSeries = buildPlotSeries(data,
                                     reqOpt('timestamp'),
                                     reqOpt('breakInterval'),
                                     reqOpt('timeOffset')).plotSeries;

    var lastY = data[data.length-1];
    var maxString = isNaN(lastY) ? '?' : ViewHelpers.formatQuantity(lastY, options.isBytes ? 1024 : 1000);
    queuedUpdates.push(function () {
      jq.find('#js_small_graph_value').text(maxString);
    });
    if (queuedUpdates.length == 1) {
      setTimeout(flushQueuedUpdate, 0);
    }

    var color = reqOpt('isSelected') ? '#e2f1f9' : '#d95e28';

    var yaxis = {min:0, ticks:0, autoscaleMargin: 0.04}

    if (options.maxY)
      yaxis.max = options.maxY;

    $.plot(jq.find('#js_small_graph_block'),
           _.map(plotSeries, function (plotData) {
             return {color: color,
                     shadowSize: shadowSize,
                     data: plotData};
           }),
           {xaxis: {ticks:0,
                    autoscaleMargin: 0.04,
                    min: now - reqOpt('zoomMillis'),
                    max: now},
            yaxis: yaxis,
            grid: {show:false}});
  }

  global.renderSmallGraph = renderSmallGraph;
})(this);

var GraphsWidget = mkClass({
  initialize: function (largeGraphJQ, smallGraphsContainerJQ, descCell, configurationCell) {
    this.largeGraphJQ = largeGraphJQ;
    this.smallGraphsContainerJQ = smallGraphsContainerJQ;

    this.drawnDesc = this.drawnConfiguration = {};
    Cell.subscribeMultipleValues($m(this, 'renderAll'), descCell, configurationCell);
  },
  // renderAll (and subscribeMultipleValues) exist to strictly order renderStatsBlock w.r.t. updateGraphs
  renderAll: function (desc, configuration) {
    if (this.drawnDesc !== desc) {
      this.renderStatsBlock(desc);
      this.drawnDesc = desc;
    }
    if (this.drawnConfiguration !== configuration) {
      this.updateGraphs(configuration);
      this.drawnConfiguration = configuration;
    }
  },
  unrenderNothing: function () {
    if (this.spinners) {
      _.each(this.spinners, function (s) {s.remove()});
      this.spinners = null;
    }
  },
  renderNothing: function () {
    if (this.spinners) {
      return;
    }
    this.spinners = [
      overlayWithSpinner(this.largeGraphJQ, undefined, undefined, 1)
    ];
    this.smallGraphsContainerJQ.find('#js_small_graph_value').text('?')
  },
  renderStatsBlock: function (descValue) {
    if (!descValue) {
      this.smallGraphsContainerJQ.html('');
      this.renderNothing();
      return;
    }
    this.unrenderNothing();
    renderTemplate('js_new_stats_block', descValue, this.smallGraphsContainerJQ[0]);
    $(this).trigger('menelaus.graphs-widget.rendered-stats-block');
  },
  zoomToSeconds: {
    minute: 60,
    hour: 3600,
    day: 86400,
    week: 691200,
    month: 2678400,
    year: 31622400
  },
  forceNextRendering: function () {
    this.lastCompletedTimestamp = undefined;
  },
  updateGraphs: function (configuration) {
    var self = this;

    if (!configuration) {
      self.lastCompletedTimestamp = undefined;
      return self.renderNothing();
    }

    self.unrenderNothing();

    var nowTStamp = (new Date()).valueOf();
    if (self.lastCompletedTimestamp && nowTStamp - self.lastCompletedTimestamp < 200) {
      // skip this sample as we're too slow
      return;
    }

    var stats = configuration.samples;

    var timeOffset = configuration.clientDate - configuration.serverDate;

    // TODO: empty stats should be maybe handled elsewhere
    if (!stats) {
      stats = {timestamp: []};
      _.each(_.keys(configuration.infos), function (name) {
        stats[name] = [];
      });
    }

    var zoomMillis = (self.zoomToSeconds[configuration.zoomLevel] || 60) * 1000;
    var selected = configuration.selected;
    var now = (new Date()).valueOf();
    if (configuration.interval < 2000) {
      now -= StatsModel.samplesBufferDepth.value * 1000;
    }

    maybeReloadAppDueToLeak();

    plotStatGraph(self.largeGraphJQ, stats[selected.name], configuration.timestamp, {
      color: '#1d88ad',
      verticalMargin: 1.02,
      fixedTimeWidth: zoomMillis,
      timeOffset: timeOffset,
      lastSampleTime: now,
      breakInterval: configuration.interval * 2.5,
      maxY: configuration.infos.byName[selected.name].maxY,
      isBytes: configuration.selected.isBytes
    });

    try {
      var visibleBlockIDs = {};
      _.each($(_.map(configuration.infos.blockIDs, $i)).filter(":has(.js_stats:visible)"), function (e) {
        visibleBlockIDs[e.id] = e;
      });
    } catch (e) {
      debugger
      throw e;
    }

    _.each(configuration.infos, function (statInfo) {
      if (!visibleBlockIDs[statInfo.blockId]) {
        return;
      }
      var statName = statInfo.name;
      var graphContainer = $($i(statInfo.id));
      if (graphContainer.length == 0) {
        return;
      }
      renderSmallGraph(graphContainer, {
        data: stats[statName] || [],
        breakInterval: configuration.interval * 2.5,
        timeOffset: timeOffset,
        now: now,
        zoomMillis: zoomMillis,
        isSelected: selected.name == statName,
        timestamp: configuration.timestamp,
        maxY: configuration.infos.byName[statName].maxY,
        isBytes: statInfo.isBytes
      });
    });

    self.lastCompletedTimestamp = (new Date()).valueOf();

    $(self).trigger('menelaus.graphs-widget.rendered-graphs');
  }
});

var AnalyticsSection = {
  onKeyStats: function (hotKeys) {
    $('#js_top_keys_block').toggle(hotKeys !== null);
    if (hotKeys == null) {
      return;
    }
    renderTemplate('js_top_keys', _.map(hotKeys, function (e) {
      return $.extend({}, e, {total: 0 + e.gets + e.misses});
    }));
  },
  init: function () {
    var self = this;

    StatsModel.hotKeysCell.subscribeValue($m(self, 'onKeyStats'));
    prepareTemplateForCell('js_top_keys', StatsModel.hotKeysCell);

    $('#js_analytics .js_block-expander').live('click', function () {
      // this forces configuration refresh and graphs redraw
      self.widget.forceNextRendering();
      StatsModel.configurationExtra.setValue({});
    });

    IOCenter.staleness.subscribeValue(function (stale) {
      $('#js_stats-period-container')[stale ? 'hide' : 'show']();
      $('#js_analytics .js_staleness-notice')[stale ? 'show' : 'hide']();
    });

    (function () {
      var cell = Cell.compute(function (v) {
        var mode = v.need(DAL.cells.mode);
        if (mode != 'analytics') {
          return;
        }

        var allBuckets = v.need(DAL.cells.bucketsListCell);
        var selectedBucket = v.need(StatsModel.statsBucketDetails);
        return {list: _.map(allBuckets, function (info) {return [info.uri, info.name]}),
                selected: selectedBucket.uri};
      });
      $('#js_analytics_buckets_select').bindListCell(cell, {
        onChange: function (e, newValue) {
          StatsModel.statsBucketURL.setValue(newValue);
        }
      });
    })();

    (function () {
      var cell = Cell.compute(function (v) {
        var mode = v.need(DAL.cells.mode);
        if (mode != 'analytics') {
          return;
        }

        var allNodes = v.need(StatsModel.statsNodesCell);
        var selectedNode;
        var statsHostname = v(StatsModel.statsHostname);

        if (statsHostname) {
          selectedNode = v.need(StatsModel.targetCell);
        }

        var list = _.map(allNodes.servers, function (srv) {
          var name = ViewHelpers.maybeStripPort(srv.hostname, allNodes.servers);
          return [srv.hostname, name];
        });
        // natural sort by full hostname (which includes port number)
        list.sort(mkComparatorByProp(0, naturalSort));
        list.unshift(['', 'All Server Nodes (' + allNodes.servers.length + ')' ]);

        return {list: list,
                selected: selectedNode && selectedNode.hostname};
      });
      $('#js_analytics_servers_select').bindListCell(cell, {
        onChange: function (e, newValue) {
          StatsModel.statsHostname.setValue(newValue || undefined);
        }
      });
    })();

    self.widget = new GraphsWidget($('#js_analytics_main_graph'), $('#js_stats_container'), StatsModel.statsDescInfoCell, StatsModel.graphsConfigurationCell);

    Cell.needing(StatsModel.graphsConfigurationCell).compute(function (v, configuration) {
      return configuration.timestamp.length == 0;
    }).subscribeValue(function (missingSamples) {
      $('#js_stats-period-container').toggleClass('dynamic_missing-samples', !!missingSamples);
    });
    Cell.needing(StatsModel.graphsConfigurationCell).compute(function (v, configuration) {
      var zoomMillis = GraphsWidget.prototype.zoomToSeconds[configuration.zoomLevel] * 1000;
      return Math.ceil(Math.min(zoomMillis, configuration.serverDate - configuration.timestamp[0]) / 1000);
    }).subscribeValue(function (visibleSeconds) {
      $('#js_stats_visible_period').text(isNaN(visibleSeconds) ? '?' : formatUptime(visibleSeconds));
    });

    (function () {
      var selectionCell;
      StatsModel.smallGraphSelectionCellCell.subscribeValue(function (cell) {
        selectionCell = cell;
      });

      $(".js_analytics-small-graph").live("click", function (e) {
        // don't intercept right arrow clicks
        if ($(e.target).is(".js_right-arrow, .js_right-arrow *")) {
          return;
        }
        e.preventDefault();
        var graphParam = this.getAttribute('data-graph');
        if (!graphParam) {
          debugger
          throw new Error("shouldn't happen");
        }
        if (!selectionCell) {
          return;
        }
        selectionCell.setValue(graphParam);
        self.widget.forceNextRendering();
      });
    })();

    (function () {
      function handler() {
        var val = effectiveSelected.value;
        val = val && val.name;
        $('.js_analytics-small-graph.dynamic_selected').removeClass('dynamic_selected');
        if (!val) {
          return;
        }
        $(_.filter($('.js_analytics-small-graph[data-graph]'), function (el) {
          return String(el.getAttribute('data-graph')) === val;
        })).addClass('dynamic_selected');
      }
      var effectiveSelected = Cell.compute(function (v) {return v.need(StatsModel.graphsConfigurationCell).selected});
      effectiveSelected.subscribeValue(handler);
      $(self.widget).bind('menelaus.graphs-widget.rendered-stats-block', handler);
    })();

    $(self.widget).bind('menelaus.graphs-widget.rendered-graphs', function () {
      var graph = StatsModel.graphsConfigurationCell.value.selected;
      $('#js_analytics .js_current-graph-name').text(graph.title);
      $('#js_analytics .js_current-graph-desc').text(graph.desc);
    });

    $(self.widget).bind('menelaus.graphs-widget.rendered-stats-block', function () {
      $('#js_stats_container').hide();
      _.each($('.js_analytics-small-graph:not(.dynamic_dim)'), function (e) {
        e = $(e);
        var graphParam = e.attr('data-graph');
        if (!graphParam) {
          debugger
          throw new Error("shouldn't happen");
        }
        var ul = e.find('.js_right-arrow .js_inner').need(1);

        var params = {sec: 'analytics', statsBucket: StatsModel.statsBucketDetails.value.uri};
        var aInner;

        if (!StatsModel.displayingSpecificStatsCell.value) {
          params.statsStatName = graphParam;
          aInner = "show by server";
        } else {
          params.graph = StatsModel.statsStatName.value;
          params.statsHostname = graphParam;
          aInner = "show this server";
        }

        ul[0].appendChild(jst.analyticsRightArrow(aInner, params));
      });
      $('#js_stats_container').show();
    });

    StatsModel.displayingSpecificStatsCell.subscribeValue(function (displayingSpecificStats) {
      displayingSpecificStats = !!displayingSpecificStats;
      $('#js_analytics .js_when-normal-stats').toggle(!displayingSpecificStats);
      $('#js_analytics .js_when-specific-stats').toggle(displayingSpecificStats);
    });

    Cell.subscribeMultipleValues(function (specificStatsNamesSet, statsStatName) {
      var text = '?';
      if (specificStatsNamesSet && statsStatName) {
        var pair = specificStatsNamesSet.byName[statsStatName];
        if (pair) {
          text = pair[1];
        } else {
          debugger
        }
      }
      $('.js_specific-stat-description').text(text);
    }, StatsModel.specificStatsNamesSetCell, StatsModel.effectiveSpecificStatName);
  },
  onLeave: function () {
    setHashFragmentParam("zoom", undefined);
    StatsModel.statsHostname.setValue(undefined);
    StatsModel.statsBucketURL.setValue(undefined);
    StatsModel.selectedGraphNameCell.setValue(undefined);
    StatsModel.statsStatName.setValue(undefined);
  },
  onEnter: function () {
  }
};


text:
package org.leguan.file;

import org.leguan.language.file.FileContainer;
import org.leguan.language.file.GenericFile;
import org.leguan.language.file.Module;
import org.leguan.language.file.ModuleReader;

import java.io.File;

/**
 * demo how to read java types in a java project in standalone application
 */
public class FileFilterExample {

  public static void main (final String args []) {
    File currentPath = new File ("").getAbsoluteFile();
    Module module = new ModuleReader (currentPath).getModule();
    FileContainer fileContainer = module.getRootPath().getFileContainer();
    for (GenericFile genericFile: fileContainer.filteredBySuffix(".properties").getAllItems()) {
      System.out.println ("Propertyfile " + genericFile.getFile().getAbsolutePath() + " found");
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Model;

use Oro\Bundle\WorkflowBundle\Model\ProcessFactory;
use Oro\Bundle\WorkflowBundle\Entity\ProcessDefinition;

use Oro\Component\Action\Action\ActionAssembler;
use Oro\Component\ConfigExpression\ExpressionFactory;

class ProcessFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testCreate()
    {
        /** @var \PHPUnit_Framework_MockObject_MockObject|ActionAssembler $actionAssembler */
        $actionAssembler = $this->getMockBuilder('Oro\Component\Action\Action\ActionAssembler')
            ->disableOriginalConstructor()
            ->getMock();

        /** @var \PHPUnit_Framework_MockObject_MockObject|ProcessDefinition $processDefinition */
        $processDefinition = $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Entity\ProcessDefinition')
            ->disableOriginalConstructor()
            ->getMock();

        /** @var \PHPUnit_Framework_MockObject_MockObject|ExpressionFactory $conditionFactory */
        $conditionFactory = $this->getMockBuilder('Oro\Component\ConfigExpression\ExpressionFactory')
            ->disableOriginalConstructor()
            ->getMock();

        $processFactory = new ProcessFactory($actionAssembler, $conditionFactory);
        $this->assertInstanceOf(
            'Oro\Bundle\WorkflowBundle\Model\Process',
            $processFactory->create($processDefinition)
        );
    }
}


text:
use std::collections::HashMap;

use serde::Serialize;

use crate::{ErrorCode, Request, RequestId, Response, ResponseError};

/// Manages the set of pending requests, both incoming and outgoing.
#[derive(Debug)]
pub struct ReqQueue<I, O> {
    pub incoming: Incoming<I>,
    pub outgoing: Outgoing<O>,
}

impl<I, O> Default for ReqQueue<I, O> {
    fn default() -> ReqQueue<I, O> {
        ReqQueue {
            incoming: Incoming { pending: HashMap::default() },
            outgoing: Outgoing { next_id: 0, pending: HashMap::default() },
        }
    }
}

#[derive(Debug)]
pub struct Incoming<I> {
    pending: HashMap<RequestId, I>,
}

#[derive(Debug)]
pub struct Outgoing<O> {
    next_id: i32,
    pending: HashMap<RequestId, O>,
}

impl<I> Incoming<I> {
    pub fn register(&mut self, id: RequestId, data: I) {
        self.pending.insert(id, data);
    }

    pub fn cancel(&mut self, id: RequestId) -> Option<Response> {
        let _data = self.complete(id.clone())?;
        let error = ResponseError {
            code: ErrorCode::RequestCanceled as i32,
            message: "canceled by client".to_string(),
            data: None,
        };
        Some(Response { id, result: None, error: Some(error) })
    }

    pub fn complete(&mut self, id: RequestId) -> Option<I> {
        self.pending.remove(&id)
    }

    pub fn is_completed(&self, id: &RequestId) -> bool {
        !self.pending.contains_key(id)
    }
}

impl<O> Outgoing<O> {
    pub fn register<P: Serialize>(&mut self, method: String, params: P, data: O) -> Request {
        let id = RequestId::from(self.next_id);
        self.pending.insert(id.clone(), data);
        self.next_id += 1;
        Request::new(id, method, params)
    }

    pub fn complete(&mut self, id: RequestId) -> Option<O> {
        self.pending.remove(&id)
    }
}


text:
layout: categories_list
cat_name: welcome
---

{% for post in site.categories.welcome %}

  {% include teaser.html %}

{% endfor %}


text:
namespace net {
namespace test {

class MockQuicDispatcher : public QuicSimpleDispatcher {
 public:
  MockQuicDispatcher(
      const QuicConfig& config,
      const QuicCryptoServerConfig* crypto_config,
      QuicVersionManager* version_manager,
      std::unique_ptr<QuicConnectionHelperInterface> helper,
      std::unique_ptr<QuicCryptoServerStream::Helper> session_helper,
      std::unique_ptr<QuicAlarmFactory> alarm_factory);

  ~MockQuicDispatcher() override;

  MOCK_METHOD3(ProcessPacket,
               void(const IPEndPoint& server_address,
                    const IPEndPoint& client_address,
                    const QuicReceivedPacket& packet));

 private:
  DISALLOW_COPY_AND_ASSIGN(MockQuicDispatcher);
};

}  // namespace test
}  // namespace net

#endif  // NET_QUIC_TEST_TOOLS_MOCK_QUIC_DISPATCHER_H_


text:
name             'ad-auth'
maintainer       'Peter Crossley, Tim Smith'
maintainer_email 'peterc@xley.com, tsmith@llnw.com'
license          'Apache 2.0'
description      'Configures Active Directory authentication support using Likewise Open 6'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '1.0.7'

depends          'sudo'

%w{ redhat centos fedora ubuntu debian amazon scientific oracle }.each do |os|
  supports os
end


text:
    <meta charset="UTF-8">
    <title>CGGlyph.
        <init> -
    </title>
    <link rel="stylesheet" href="../../style.css">

com.agog.mathdisplay.render / CGGlyph / <init>

<init>

CGGlyph(<span class="identifier"
                                                                                id="com.agog.mathdisplay.render.CGGlyph$<init>(kotlin.Int, kotlin.Float, kotlin.Float, kotlin.Float)/gid">gid: Int = 0, <span class="identifier"
                                                                          id="com.agog.mathdisplay.render.CGGlyph$<init>(kotlin.Int, kotlin.Float, kotlin.Float, kotlin.Float)/glyphAscent">glyphAscent: Float = 0.0f, <span class="identifier"
                                                                             id="com.agog.mathdisplay.render.CGGlyph$<init>(kotlin.Int, kotlin.Float, kotlin.Float, kotlin.Float)/glyphDescent">glyphDescent: Float = 0.0f, <span class="identifier"
                                                                             id="com.agog.mathdisplay.render.CGGlyph$<init>(kotlin.Int, kotlin.Float, kotlin.Float, kotlin.Float)/glyphWidth">glyphWidth: Float = 0.0f)


text:
/** @module core */
export * from './Component';
export * from './MeshComponent';
export * from './LightComponent';
export * from './CameraComponent';
export * from './App';
export * from './Loop';
export * from './ModuleManager';


text:
<!DOCTYPE html>
<html>
<head>
	<title>Line Waiting Game</title>
</head>
<body>
	<canvas id="myCanvas" width="1024" height="400"></canvas>
</body>
</html>


text:
#ifndef __AE_SOCKET_FACTORY_H
#define __AE_SOCKET_FACTORY_H

#include <ICommunicationSocket.h>

class ISocketFactory
{
public:
    virtual ~ISocketFactory() {}

    virtual ICommunicationSocket* NewCommunicationSocket() = 0;
};

#endif


text:
<?php
header("Location: summary.php");
?>


text:
class Profiler
{
public:
#ifdef SFML_CLOCK
	class Clock
	{
	public:
		typedef int64_t rep;
		typedef std::micro period;
		typedef std::chrono::duration<rep, period> duration;
		typedef std::chrono::time_point<Clock> time_point;

		static const bool is_steady;
		static time_point now();
	};
#else
	typedef std::chrono::high_resolution_clock Clock;
#endif

	typedef Clock::time_point TimePoint;
	typedef Clock::duration TimeSpan;

	class Iterator;
	class Node;

	static void startBlock(const std::string& name);
	static void endBlock();
	static void resetBlocks();
	static void releaseMemory();

	static Node* getRoot();

	static Iterator begin();
	static Iterator end();

	struct Block
	{
		Block(const std::string& name);
		~Block();
	};

	class Node
	{
	public:
		Node(const std::string& name, Node* parent = nullptr);
		~Node();

		Iterator begin() const;
		Iterator end() const;

		void startCall();
		bool endCall();

		void reset();
		void cleanup();

		Node* getChild(const std::string& name);

		friend std::ostream& operator<<(std::ostream& os, const Node& node)
		{
			node.toStream(os);
			return os;
		}
		void toStream(std::ostream&, unsigned int level = 0) const;

		std::string getName() const;

		TimeSpan getAvgTime() const;
		TimeSpan getMinTime() const;
		TimeSpan getMaxTime() const;
		TimeSpan getTotalTime() const;

		unsigned int getCallCount() const;

	private:
		std::string mName;
		TimePoint mStartTime;
		TimeSpan mMaxTime, mMinTime, mTotalTime;
		unsigned int mCallCount, mRecursion;

		Node *mParent, *mChild, *mSibling;

		friend class Profiler;
		friend class Iterator;
	};

	class Iterator
	{
	public:
		typedef std::ptrdiff_t difference_type;
        typedef Node value_type;
        typedef const Node& reference;
        typedef const Node* pointer;
        typedef std::forward_iterator_tag iterator_category;

		Iterator(const Iterator&);
		Iterator(Iterator&&);
		~Iterator();

		Iterator& operator=(const Iterator&);
		Iterator& operator++();
		Iterator& operator+=(int);

		reference operator*() const;
		pointer operator->() const;

		pointer getParent() const;

		friend bool operator==(const Iterator& lhs, const Iterator& rhs)
		{
			return lhs.mCurChild == rhs.mCurChild &&
				lhs.mCurParent == rhs.mCurParent;
		}
		friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
		{
			return lhs.mCurChild != rhs.mCurChild ||
				lhs.mCurParent != rhs.mCurParent;
		}
		friend void swap(Profiler::Iterator& l, Profiler::Iterator& r)
		{
			using std::swap;

			swap(l.mCurChild, r.mCurChild);
			swap(l.mCurParent, r.mCurParent);
		}

	private:
		Iterator(const Node* node, bool atEnd = false);

		const Node *mCurChild, *mCurParent;

		friend class Profiler;
		friend class Node;
	};
};


text:
package study.hard.javalib.jackson;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import study.hard.javalib.entity.User;
import study.hard.javalib.entity.UserHasInnerClass;

/**
 * @author SeomGi, Han(iandmyhand@gmail.com)
 */
public class JacksonTest {

	private static final String PATHNAME = "user.json";
	private static final String USER_NAME = "tester";
	private static final Integer USER_AGE = 20;

	ObjectMapper mapper;
	private File file;
	private User user;

	@Before
	public void setUp() {
		mapper = new ObjectMapper();

		file = new File(PATHNAME);
		System.out.println("Absolute path: " + file.getAbsoluteFile() + "\n");

		user = new User(USER_NAME, USER_AGE);
	}

	@Test
	public void testBasicUsageOfJackson() {
		try {
			//1. Convert Java object to JSON format
			mapper.writeValue(file, user);

			//2. Convert JSON to Java object
			User user2 = mapper.readValue(file, User.class);
			System.out.println("user2: " + user2 + "\n");

			JsonNode jsonNode = mapper.readValue(file, JsonNode.class);
			System.out.println("jsonNode: " + jsonNode + "\n");

			User user3 = mapper.readValue(jsonNode, User.class);
			System.out.println("user3: " + user3 + "\n");

		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testDeserialiseArrayOfObjects() {
		try {
			mapper.writeValue(file, user);
			JsonNode jsonNode = mapper.readValue(file, JsonNode.class);

			// 1. As Array:
			String[] messagesAsStringArray = mapper.readValue(jsonNode.get("messages"), String[].class);
			for (String message : messagesAsStringArray) {
				System.out.println("message: " + message);
			}
			System.out.println();

			// 2. As List:
			List<String> messagesAsStringList = mapper.readValue(jsonNode.get("messages"), new TypeReference<List<String>>() {
			});
			System.out.println("messagesAsStringList: " + messagesAsStringList + "\n");

			// 3. Another way to specify the List type:
			List<String> messagesAsStringList2 = mapper.readValue(jsonNode.get("messages"), mapper.getTypeFactory().constructCollectionType(List.class, String.class));
			System.out.println("messagesAsStringList2: " + messagesAsStringList2 + "\n");
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testDeserializeArrayOfObjectsWithNonStaticMemberClass() {
		UserHasInnerClass user = new UserHasInnerClass(USER_NAME, USER_AGE);
		user.setDetailInfo(user.new DetailInfo(170F, 80F));
		try {
			mapper.writeValue(file, user);
			JsonNode jsonNode = mapper.readValue(file, JsonNode.class);

			UserHasInnerClass deserializedUser = mapper.readValue(jsonNode, UserHasInnerClass.class);
			System.out.println("deserializedUser: " + deserializedUser + "\n");

		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			assertEquals(JsonMappingException.class, e.getClass());
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@After
	public void rollBack() {
		file.delete();
	}

}


text:
require 'helen'
require 'graph_factory'

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus
  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'

  # Have a default client always.
  config.before(:each) do
    Helen::Client.configure do |c|
      c.host = 'localhost'
      c.port = 8184
      c.graph = 'test'
    end
  end

  config.around(:each) do |example|
    # GraphFactory.new.load!
    example.run
    GraphFactory.new.teardown!
  end
end

def helen(opts = {})
  opts = { host: 'localhost', port: 8184, graph: 'test' }.merge(opts)
  @_helen ||= Helen::Client.new(opts)
end

def assert_vertex(vertex, attributes = {})
  attributes.each { |k, v| expect(vertex.send(k)).to eq(v) }
end


text:
layout: post
title:  "자바와 해외 시간"
author: "glqdlt"
---

해외 게임 런칭 플랫폼 개발을 하면서 있던 일화이다.

자바에서 시간 기능은 금기어와 같다. 이유는 Date 라는 일관성 없는 API 디자인 때문이다. 월에 대한 개념이 0월 부터 시작하지를 않나, 멀티 스레드 동기화 문제도 있고 말이 많다. 이후 Schedule 이란 것도 나왔지만, 동기화 문제만 해결했을 뿐 괴랄한 API 생김새는 큰 차이가 없다.

이후 이 꼴을 못 참던 이가 joda Time 라는 오픈소스 라이브러리가 개발 되었다. 끔찍한 java 의 시간을 다루던 여러 프로그래머들은 열광했고 joda-time 은 급속도로 사용되어져 갔다. 훗날 이는 JDK8 의 시간인 ```Temporal``` 시간 관련 모델링을 설계하는 데에 많은 도움이 되었으며, 실제로 몇몇 구현체는 Joda-Time 클래스를 그대로 사용하는 것도 있다.

Temporal 은 서브 타입으로 (Chrono)LocalDatetime 과 (Chrono)ZoneDateTime 2가지 갈래로 나뉜다.

이 API들의 차이점은 시차에 대한 정보가 있냐 없냐로 나뉠 뿐, 생김새는 거의 흡사하다. 이름에서 알겠지만 ZoneDateTime 은 시차에 대한 정보가 있다. 예를 들어 아래 코드를 사용해보면 시차 정보에 대한 데이터가 없다는 에러를 마주하게 된다.

```java
@Test
    public void timeParse() {
        LocalDateTime time = LocalDateTime.of(2019, 1, 1, 1, 1);
        Assert.assertEquals("2019-01-01T01:01:01.000000001+09:00", time.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

		// java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds
    }

```

반면 아래의 ZoneDateTime 의 경우 LocalDateTime과는 달리 생성자 인자로 ZoneId를 받는 부분이 추가 되어있는 걸 알 수 있다.

```java
	@Test
    public void timeParse() {
        ZonedDateTime time = ZonedDateTime.of(2019, 1, 1, 1, 1, 1, 1, ZoneId.of("Asia/Seoul"));
		// 아래도 같은 효과로, ZoneOffSet.ofHours()는 Time Zone에 따른 시차를 직접 지정하는 정적 메소드이다.
		// ZonedDateTime time = ZonedDateTime.of(2019, 1, 1, 1, 1, 1, 1, ZoneOffset.ofHours(9));
        Assert.assertEquals("2019-01-01T01:01:01.000000001+09:00", time.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
	}
```

위 코드에서 ISO_OFFSET_DATE_TIME는 ISO 8601 기반의 포맷을 의미한다. [ISO 8601](https://ko.wikipedia.org/wiki/ISO_8601)은 시간 관련 국제 표준 포맷이다. 내가 태어난 해인 1988년에 발표되었다. ISO 8601은 UTC 시간에 대한 표기 방법도 정의가 되어있다.
아래 포맷은 2016-10-27 의 17시 13분 40초 [UTC](https://ko.wikipedia.org/wiki/협정_세계시) 표준 시간을 의미한다.
```
2016-10-27T17:13:40+00:00
2016-10-27T17:13:40Z
20161027T171340Z
```

참고로 UTC 는 Coordinated Universal Time 라는 뜻으로 전 세계 시차에 대한 기준 시간을 의미 한다. 여기서 기준은 영국 시간을 0, root 로 두고 얼마만큼 거리에 따라 시차가 있는 지를 의미 한다. 만약 영국 시간을 UTC 로 표기할 경우 +00:00 으로 표기해도 되지만, 제로(0)라는 의미의 Z라고 표현을 해도 된다. 그래서 위에  ```2016-10-27T17:13:40+00:00```  와 ```2016-10-27T17:13:40Z``` 는 같다.

ISO 8601 에서 UTC 표기법은, 기준인 영국 시간에서 얼마만큼 차이가 있는지를 표기하게 되있다. 예를 들어 한국은 9시간이나 더 늦기 때문에
```2016-10-27T17:13:40+09:00 ``` 로 표현할 수 있다.

영국이 +00:00 이라면

ZoneDateTime 에 ZoneId는 뭘까? [oracle 문서](https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html) 를 보면 time-zone ID 를 뜻하는 것을 알 수 있다. 지원하는 time zone 목록은 ZoneId 내부에 하드코딩 되어있는 목록을 통해 알 수 가 있다.

```java
    @Test
    public void echoTimeZone() {

        ZoneId.getAvailableZoneIds()
                .stream()
                .forEach(System.out::println);

    }
```

```
Asia/Aden
America/Cuiaba
Etc/GMT+9
Etc/GMT+8
Africa/Nairobi
America/Marigot
Asia/Aqtau
Pacific/Kwajalein
America/El_Salvador
Asia/Pontianak
Africa/Cairo
Pacific/Pago_Pago
Africa/Mbabane
Asia/Kuching
Pacific/Honolulu
Pacific/Rarotonga
America/Guatemala
Australia/Hobart
Europe/London
America/Belize
America/Panama
Asia/Chungking
America/Managua
America/Indiana/Petersburg
Asia/Yerevan
Europe/Brussels
GMT
Europe/Warsaw
America/Chicago
Asia/Kashgar
Chile/Continental
Pacific/Yap
CET
Etc/GMT-1
Etc/GMT-0
Europe/Jersey
America/Tegucigalpa
Etc/GMT-5
Europe/Istanbul
America/Eirunepe
Etc/GMT-4
America/Miquelon
Etc/GMT-3
Europe/Luxembourg
Etc/GMT-2
Etc/GMT-9
America/Argentina/Catamarca
Etc/GMT-8
Etc/GMT-7
Etc/GMT-6
Europe/Zaporozhye
Canada/Yukon
Canada/Atlantic
Atlantic/St_Helena
Australia/Tasmania
Libya
Europe/Guernsey
America/Grand_Turk
US/Pacific-New
Asia/Samarkand
America/Argentina/Cordoba
Asia/Phnom_Penh
Africa/Kigali
Asia/Almaty
US/Alaska
Asia/Dubai
Europe/Isle_of_Man
America/Araguaina
Cuba
Asia/Novosibirsk
America/Argentina/Salta
Etc/GMT+3
Africa/Tunis
Etc/GMT+2
Etc/GMT+1
Pacific/Fakaofo
Africa/Tripoli
Etc/GMT+0
Israel
Africa/Banjul
Etc/GMT+7
Indian/Comoro
Etc/GMT+6
Etc/GMT+5
Etc/GMT+4
Pacific/Port_Moresby
US/Arizona
Antarctica/Syowa
Indian/Reunion
Pacific/Palau
Europe/Kaliningrad
America/Montevideo
Africa/Windhoek
Asia/Karachi
Africa/Mogadishu
Australia/Perth
Brazil/East
Etc/GMT
Asia/Chita
Pacific/Easter
Antarctica/Davis
Antarctica/McMurdo
Asia/Macao
America/Manaus
Africa/Freetown
Europe/Bucharest
Asia/Tomsk
America/Argentina/Mendoza
Asia/Macau
Europe/Malta
Mexico/BajaSur
Pacific/Tahiti
Africa/Asmera
Europe/Busingen
America/Argentina/Rio_Gallegos
Africa/Malabo
Europe/Skopje
America/Catamarca
America/Godthab
Europe/Sarajevo
Australia/ACT
GB-Eire
Africa/Lagos
America/Cordoba
Europe/Rome
Asia/Dacca
Indian/Mauritius
Pacific/Samoa
America/Regina
America/Fort_Wayne
America/Dawson_Creek
Africa/Algiers
Europe/Mariehamn
America/St_Johns
America/St_Thomas
Europe/Zurich
America/Anguilla
Asia/Dili
America/Denver
Africa/Bamako
Europe/Saratov
GB
Mexico/General
Pacific/Wallis
Europe/Gibraltar
Africa/Conakry
Africa/Lubumbashi
Asia/Istanbul
America/Havana
NZ-CHAT
Asia/Choibalsan
America/Porto_Acre
Asia/Omsk
Europe/Vaduz
US/Michigan
Asia/Dhaka
America/Barbados
Europe/Tiraspol
Atlantic/Cape_Verde
Asia/Yekaterinburg
America/Louisville
Pacific/Johnston
Pacific/Chatham
Europe/Ljubljana
America/Sao_Paulo
Asia/Jayapura
America/Curacao
Asia/Dushanbe
America/Guyana
America/Guayaquil
America/Martinique
Portugal
Europe/Berlin
Europe/Moscow
Europe/Chisinau
America/Puerto_Rico
America/Rankin_Inlet
Pacific/Ponape
Europe/Stockholm
Europe/Budapest
America/Argentina/Jujuy
Australia/Eucla
Asia/Shanghai
Universal
Europe/Zagreb
America/Port_of_Spain
Europe/Helsinki
Asia/Beirut
Asia/Tel_Aviv
Pacific/Bougainville
US/Central
Africa/Sao_Tome
Indian/Chagos
America/Cayenne
Asia/Yakutsk
Pacific/Galapagos
Australia/North
Europe/Paris
Africa/Ndjamena
Pacific/Fiji
America/Rainy_River
Indian/Maldives
Australia/Yancowinna
SystemV/AST4
Asia/Oral
America/Yellowknife
Pacific/Enderbury
America/Juneau
Australia/Victoria
America/Indiana/Vevay
Asia/Tashkent
Asia/Jakarta
Africa/Ceuta
Asia/Barnaul
America/Recife
America/Buenos_Aires
America/Noronha
America/Swift_Current
Australia/Adelaide
America/Metlakatla
Africa/Djibouti
America/Paramaribo
Europe/Simferopol
Europe/Sofia
Africa/Nouakchott
Europe/Prague
America/Indiana/Vincennes
Antarctica/Mawson
America/Kralendijk
Antarctica/Troll
Europe/Samara
Indian/Christmas
America/Antigua
Pacific/Gambier
America/Indianapolis
America/Inuvik
America/Iqaluit
Pacific/Funafuti
UTC
Antarctica/Macquarie
Canada/Pacific
America/Moncton
Africa/Gaborone
Pacific/Chuuk
Asia/Pyongyang
America/St_Vincent
Asia/Gaza
Etc/Universal
PST8PDT
Atlantic/Faeroe
Asia/Qyzylorda
Canada/Newfoundland
America/Kentucky/Louisville
America/Yakutat
Asia/Ho_Chi_Minh
Antarctica/Casey
Europe/Copenhagen
Africa/Asmara
Atlantic/Azores
Europe/Vienna
ROK
Pacific/Pitcairn
America/Mazatlan
Australia/Queensland
Pacific/Nauru
Europe/Tirane
Asia/Kolkata
SystemV/MST7
Australia/Canberra
MET
Australia/Broken_Hill
Europe/Riga
America/Dominica
Africa/Abidjan
America/Mendoza
America/Santarem
Kwajalein
America/Asuncion
Asia/Ulan_Bator
NZ
America/Boise
Australia/Currie
EST5EDT
Pacific/Guam
Pacific/Wake
Atlantic/Bermuda
America/Costa_Rica
America/Dawson
Asia/Chongqing
Eire
Europe/Amsterdam
America/Indiana/Knox
America/North_Dakota/Beulah
Africa/Accra
Atlantic/Faroe
Mexico/BajaNorte
America/Maceio
Etc/UCT
Pacific/Apia
GMT0
America/Atka
Pacific/Niue
Australia/Lord_Howe
Europe/Dublin
Pacific/Truk
MST7MDT
America/Monterrey
America/Nassau
America/Jamaica
Asia/Bishkek
America/Atikokan
Atlantic/Stanley
Australia/NSW
US/Hawaii
SystemV/CST6
Indian/Mahe
Asia/Aqtobe
America/Sitka
Asia/Vladivostok
Africa/Libreville
Africa/Maputo
Zulu
America/Kentucky/Monticello
Africa/El_Aaiun
Africa/Ouagadougou
America/Coral_Harbour
Pacific/Marquesas
Brazil/West
America/Aruba
America/North_Dakota/Center
America/Cayman
Asia/Ulaanbaatar
Asia/Baghdad
Europe/San_Marino
America/Indiana/Tell_City
America/Tijuana
Pacific/Saipan
SystemV/YST9
Africa/Douala
America/Chihuahua
America/Ojinaga
Asia/Hovd
America/Anchorage
Chile/EasterIsland
America/Halifax
Antarctica/Rothera
America/Indiana/Indianapolis
US/Mountain
Asia/Damascus
America/Argentina/San_Luis
America/Santiago
Asia/Baku
America/Argentina/Ushuaia
Atlantic/Reykjavik
Africa/Brazzaville
Africa/Porto-Novo
America/La_Paz
Antarctica/DumontDUrville
Asia/Taipei
Antarctica/South_Pole
Asia/Manila
Asia/Bangkok
Africa/Dar_es_Salaam
Poland
Atlantic/Madeira
Antarctica/Palmer
America/Thunder_Bay
Africa/Addis_Ababa
Asia/Yangon
Europe/Uzhgorod
Brazil/DeNoronha
Asia/Ashkhabad
Etc/Zulu
America/Indiana/Marengo
America/Creston
America/Punta_Arenas
America/Mexico_City
Antarctica/Vostok
Asia/Jerusalem
Europe/Andorra
US/Samoa
PRC
Asia/Vientiane
Pacific/Kiritimati
America/Matamoros
America/Blanc-Sablon
Asia/Riyadh
Iceland
Pacific/Pohnpei
Asia/Ujung_Pandang
Atlantic/South_Georgia
Europe/Lisbon
Asia/Harbin
Europe/Oslo
Asia/Novokuznetsk
CST6CDT
Atlantic/Canary
America/Knox_IN
Asia/Kuwait
SystemV/HST10
Pacific/Efate
Africa/Lome
America/Bogota
America/Menominee
America/Adak
Pacific/Norfolk
Europe/Kirov
America/Resolute
Pacific/Tarawa
Africa/Kampala
Asia/Krasnoyarsk
Greenwich
SystemV/EST5
America/Edmonton
Europe/Podgorica
Australia/South
Canada/Central
Africa/Bujumbura
America/Santo_Domingo
US/Eastern
Europe/Minsk
Pacific/Auckland
Africa/Casablanca
America/Glace_Bay
Canada/Eastern
Asia/Qatar
Europe/Kiev
Singapore
Asia/Magadan
SystemV/PST8
America/Port-au-Prince
Europe/Belfast
America/St_Barthelemy
Asia/Ashgabat
Africa/Luanda
America/Nipigon
Atlantic/Jan_Mayen
Brazil/Acre
Asia/Muscat
Asia/Bahrain
Europe/Vilnius
America/Fortaleza
Etc/GMT0
US/East-Indiana
America/Hermosillo
America/Cancun
Africa/Maseru
Pacific/Kosrae
Africa/Kinshasa
Asia/Kathmandu
Asia/Seoul
Australia/Sydney
America/Lima
Australia/LHI
America/St_Lucia
Europe/Madrid
America/Bahia_Banderas
America/Montserrat
Asia/Brunei
America/Santa_Isabel
Canada/Mountain
America/Cambridge_Bay
Asia/Colombo
Australia/West
Indian/Antananarivo
Australia/Brisbane
Indian/Mayotte
US/Indiana-Starke
Asia/Urumqi
US/Aleutian
Europe/Volgograd
America/Lower_Princes
America/Vancouver
Africa/Blantyre
America/Rio_Branco
America/Danmarkshavn
America/Detroit
America/Thule
Africa/Lusaka
Asia/Hong_Kong
Iran
America/Argentina/La_Rioja
Africa/Dakar
SystemV/CST6CDT
America/Tortola
America/Porto_Velho
Asia/Sakhalin
Etc/GMT+10
America/Scoresbysund
Asia/Kamchatka
Asia/Thimbu
Africa/Harare
Etc/GMT+12
Etc/GMT+11
Navajo
America/Nome
Europe/Tallinn
Turkey
Africa/Khartoum
Africa/Johannesburg
Africa/Bangui
Europe/Belgrade
Jamaica
Africa/Bissau
Asia/Tehran
WET
Europe/Astrakhan
Africa/Juba
America/Campo_Grande
America/Belem
Etc/Greenwich
Asia/Saigon
America/Ensenada
Pacific/Midway
America/Jujuy
Africa/Timbuktu
America/Bahia
America/Goose_Bay
America/Virgin
America/Pangnirtung
Asia/Katmandu
America/Phoenix
Africa/Niamey
America/Whitehorse
Pacific/Noumea
Asia/Tbilisi
America/Montreal
Asia/Makassar
America/Argentina/San_Juan
Hongkong
UCT
Asia/Nicosia
America/Indiana/Winamac
SystemV/MST7MDT
America/Argentina/ComodRivadavia
America/Boa_Vista
America/Grenada
Asia/Atyrau
Australia/Darwin
Asia/Khandyga
Asia/Kuala_Lumpur
Asia/Famagusta
Asia/Thimphu
Asia/Rangoon
Europe/Bratislava
Asia/Calcutta
America/Argentina/Tucuman
Asia/Kabul
Indian/Cocos
Japan
Pacific/Tongatapu
America/New_York
Etc/GMT-12
Etc/GMT-11
Etc/GMT-10
SystemV/YST9YDT
Europe/Ulyanovsk
Etc/GMT-14
Etc/GMT-13
W-SU
America/Merida
EET
America/Rosario
Canada/Saskatchewan
America/St_Kitts
Arctic/Longyearbyen
America/Fort_Nelson
America/Caracas
America/Guadeloupe
Asia/Hebron
Indian/Kerguelen
SystemV/PST8PDT
Africa/Monrovia
Asia/Ust-Nera
Egypt
Asia/Srednekolymsk
America/North_Dakota/New_Salem
Asia/Anadyr
Australia/Melbourne
Asia/Irkutsk
America/Shiprock
America/Winnipeg
Europe/Vatican
Asia/Amman
Etc/UTC
SystemV/AST4ADT
Asia/Tokyo
America/Toronto
Asia/Singapore
Australia/Lindeman
America/Los_Angeles
SystemV/EST5EDT
Pacific/Majuro
America/Argentina/Buenos_Aires
Europe/Nicosia
Pacific/Guadalcanal
Europe/Athens
US/Pacific
Europe/Monaco

```

### 섬머타임

시차에 대한 이슈 중에 가장 머리가 아팠던 것은 섬머타임이다. 북미에 런칭하는 게임이 있었는데, 섬머타임에 따른 이슈가 있었다.

중부표준시(CST) 라고 하는 시간대는 UTC를 기준으로 -6시간의 시차를 가진다. 다만 섬머타임이 적용되는 기간에는 -5:00~-5:21 의 시간대를 가진다.

ZoneDateTime 에는 이 섬머타임제가 적용이 되어있다. 다만 다른 API에는 섬머타임제도가 적용되어 있지 않다.

아래는 국가의 시차를 보여주는 기능에서 사용하는 국제시간 이름을 나타내는 테스트이다. 글을 쓰는 시점으로는 섬머타임이 적용된 시점인데, -6 의 시차로 나온다.
문제는 ZoneDateTime 의 경우에는 섬머타임을 적용한 시차 offset 을 잘 적용하고 있는 데에서 오는 차이에서 발생한다.

```java

    @Test
    public void isSummertTime() {
        TimeZone timezone = TimeZone.getTimeZone("America/Chicago");
        String displayName = timezone.getDisplayName(true, 1, Locale.KOREA);

        Assert.assertEquals("중부 일광절약시간", displayName);
        Assert.assertTrue(timezone.useDaylightTime());
        Assert.assertEquals(-6, TimeUnit.MILLISECONDS.toHours(timezone.getRawOffset()));
        Assert.assertEquals(-6, TimeUnit.MILLISECONDS.toHours(timezone.getOffset(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC))));

        ZonedDateTime currentNorthAmeriaTime = ZonedDateTime.now(ZoneId.of("America/Chicago"));
        Assert.assertEquals("-05:00", currentNorthAmeriaTime.getOffset().toString());
    }

```

이는 java.util.TimeZone 의 문제인데, 섬머타임이 제대로 적용이 되지 않아서 발생한다.
TimeZone 을 사용하는 이유는, 시차 offset 정보를 포함하고 있는 객체이기 때문인데, 문제가 발생하는 것이다.

이 경우 아래처럼 새로운 API를 사용하면 해결이 된다.

```java

    @Test
    public void zoneSummerTime() {
        ZonedDateTime currentNorthAmeriaTime = ZonedDateTime.now(ZoneId.of("America/Chicago"));
        Assert.assertEquals("-05:00", currentNorthAmeriaTime.getOffset().toString());

        ZoneId zoneId = ZoneId.of("America/Chicago");
        Assert.assertEquals("중부 표준시", zoneId.getDisplayName(TextStyle.FULL, Locale.KOREA));

        ZoneRules zoneRules = zoneId.getRules();
        ZoneOffset zoneOffset = zoneRules.getOffset(LocalDateTime.now());
        Assert.assertEquals(-5, TimeUnit.SECONDS.toHours(zoneOffset.getTotalSeconds()));
    }
```

포인트는 ZoneId 와 ZoneRules 그리고 ZoneOffset 이다. America/Chicago 와 같은 타임존을 가르키는 프리셋은 ZoneId 객체로 변환이 가능하다.
그리고 이 ZoneId 클래스는 자신과 연관있는 ZoneRules 라는 규정정보를 가지고 있는 객체로 변환이 가능하다. 최종적으로 ZoneRules 안에는 시차 정보를 담고 있으며, 그를 담당하는 클래스명은 ZoneOffset이다.

ZoneDateTime 은 이 Zone 접두어가 붙은 객체들을 활용해서 시간정보가 만들어진다.

아래는 ZoneDateTime의 정적생성 메소드들 중 일부를 발췌한다.

```java

public final class ZonedDateTime
        implements Temporal, ChronoZonedDateTime<LocalDate>, Serializable {

//...
    public static ZonedDateTime from(TemporalAccessor temporal) {
        if (temporal instanceof ZonedDateTime) {
            return (ZonedDateTime) temporal;
        }
        try {
            ZoneId zone = ZoneId.from(temporal);
            if (temporal.isSupported(INSTANT_SECONDS)) {
                long epochSecond = temporal.getLong(INSTANT_SECONDS);
                int nanoOfSecond = temporal.get(NANO_OF_SECOND);
                return create(epochSecond, nanoOfSecond, zone);
            } else {
                LocalDate date = LocalDate.from(temporal);
                LocalTime time = LocalTime.from(temporal);
                return of(date, time, zone);
            }
        } catch (DateTimeException ex) {
            throw new DateTimeException("Unable to obtain ZonedDateTime from TemporalAccessor: " +
                    temporal + " of type " + temporal.getClass().getName(), ex);
        }
    }

    private static ZonedDateTime create(long epochSecond, int nanoOfSecond, ZoneId zone) {
        ZoneRules rules = zone.getRules();
        Instant instant = Instant.ofEpochSecond(epochSecond, nanoOfSecond);  // TODO: rules should be queryable by epochSeconds
        ZoneOffset offset = rules.getOffset(instant);
        LocalDateTime ldt = LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, offset);
        return new ZonedDateTime(ldt, offset, zone);
    }
//...

}
```

보면 내부적으로 ZoneRules와 ZoneId를 잘 사용하고 있는 것을 알수있다.


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ParquetSharp.Hadoop.Metadata
{
    /**
     * Block metadata stored in the footer and passed in an InputSplit
     *
     * @author Julien Le Dem
     *
     */
    public class BlockMetaData
    {
        private readonly List<ColumnChunkMetaData> columns = new List<ColumnChunkMetaData>();
        private long rowCount;
        private long totalByteSize;
        private string path;

        public BlockMetaData()
        {
        }

        /**
         * @param path the path to the file containing the data. Or null if same file the metadata was found
         */
        public void setPath(string path)
        {
            this.path = path;
        }

        /**
         * @return the path relative to the parent of this file where the data is. Or null if it is in the same file.
         */
        public string getPath()
        {
            return path;
        }

        /**
         * @return the rowCount
         */
        public long getRowCount()
        {
            return rowCount;
        }

        /**
         * @param rowCount the rowCount to set
         */
        public void setRowCount(long rowCount)
        {
            this.rowCount = rowCount;
        }

        /**
         * @return the totalByteSize
         */
        public long getTotalByteSize()
        {
            return totalByteSize;
        }

        /**
         * @param totalByteSize the totalByteSize to set
         */
        public void setTotalByteSize(long totalByteSize)
        {
            this.totalByteSize = totalByteSize;
        }

        /**
         *
         * @param column the metadata for a column
         */
        public void addColumn(ColumnChunkMetaData column)
        {
            columns.Add(column);
        }

        /**
         *
         * @return the metadata for columns
         */
        public ReadOnlyCollection<ColumnChunkMetaData> getColumns()
        {
            return columns.AsReadOnly();
        }

        /**
         *
         * @return the starting pos of first column
         */
        public long getStartingPos()
        {
            return columns[0].getStartingPos();
        }

        public override string ToString()
        {
            return "BlockMetaData{" + rowCount + ", " + totalByteSize + " " + columns + "}";
        }

        /**
         * @return the compressed size of all columns
         */
        public long getCompressedSize()
        {
            long totalSize = 0;
            foreach (ColumnChunkMetaData col in getColumns())
            {
                totalSize += col.getTotalSize();
            }
            return totalSize;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DbUp.Engine;
using DbUp.Engine.Transactions;

namespace DbUp.ScriptProviders
{
    ///
    /// Alternate <see cref="IScriptProvider"/> implementation which retrieves upgrade scripts via a directory
    ///
    public class FileSystemScriptProvider : IScriptProvider
    {
        private readonly string directoryPath;
        private readonly Func<string, bool> filter;
        private readonly Encoding encoding;

        ///
        ///
        ///<param name="directoryPath">Path to SQL upgrade scripts</param>
        public FileSystemScriptProvider(string directoryPath)
        {
            this.directoryPath = directoryPath;
            this.filter = null;
            this.encoding = Encoding.Default;
        }

        ///
        ///
        ///<param name="directoryPath">Path to SQL upgrade scripts</param>
        ///<param name="filter">The filter.</param>
        public FileSystemScriptProvider(string directoryPath, Func<string, bool> filter)
        {
            this.directoryPath = directoryPath;
            this.filter = filter;
            this.encoding = Encoding.Default;
        }

        ///
        ///
        ///<param name="directoryPath">Path to SQL upgrade scripts</param>
        ///<param name="encoding">The encoding.</param>
        public FileSystemScriptProvider(string directoryPath, Encoding encoding)
        {
            this.directoryPath = directoryPath;
            this.filter = null;
            this.encoding = encoding;
        }

        ///
        ///
        ///<param name="directoryPath">Path to SQL upgrade scripts</param>
        ///<param name="filter">The filter.</param>
        ///<param name="encoding">The encoding.</param>
        public FileSystemScriptProvider(string directoryPath, Func<string, bool> filter, Encoding encoding)
        {
            this.directoryPath = directoryPath;
            this.filter = filter;
            this.encoding = encoding;
        }

        ///
        /// Gets all scripts that should be executed.
        ///
        public IEnumerable<SqlScript> GetScripts(IConnectionManager connectionManager)
        {
            var files = Directory.GetFiles(directoryPath, "*.sql").AsEnumerable();
            if (this.filter != null)
            {
                files = files.Where(filter);
            }
            return files.Select(x => SqlScript.FromFile(x, encoding)).ToList();
        }

    }
}


text:
package org.datacite.mds.validation.constraints;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

import org.datacite.mds.validation.constraints.impl.SymbolValidator;

/**
 * This annotation is used for any "symbol" field: Allocator symbol (e.g. "BL")
 * or datacentre symbol (e.g. "BL.SOUNDS").
 *
 * Accept only datacentres symbol:
 *
 *

 * @Symbol(Type.DATACENTRE)
 * String symbol;
 *

 *
 * Accept both symbol types:
 *
 *

 * @Symbol( { Symbol.Type.DATACENTRE, Symbol.Type.ALLOCATOR })
 * String symbol;
 *

 *
 * It also possible to ensure the symbol is already in the database. The symbol
 * is not checked to be well formed cause in the database there should be only
 * well formed symbols.
 *
 *

 *   @Symbol(hasToExist = true; value = {Symbol.Type.DATACENTRE});
 *   String symbol;
 *

 *
 * The appropriate tables for lookup are chosen based on the given symbol types.
 *
 * @see org.datacite.mds.validation.constraints.Symbol.Type
 */
@Documented
@Constraint(validatedBy = SymbolValidator.class)
@Target( { ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Symbol {
    enum Type {
        ALLOCATOR, DATACENTRE
    }

    /**
     * the symbol types to accept
     */
    Type[] value();

    /**
     * do a database lookup for existance of the symbol
     */
    boolean hasToExist() default false;

    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}


text:
from flask import render_template,redirect,url_for

from flask.ext.assets import Environment
import re

#import basic utlities
from base.utils.core import (load_blueprint_settings, load_blueprints,	    error_handler,)

#import bundles
from assets import bundles

import os
import yaml

from flask import Flask as BaseFlask, Config as BaseConfig

class Config(BaseConfig):
    """Flask config enhanced with a `from_yaml` method."""

    def from_yaml(self, config_file):

        with open(config_file) as f:
            c = yaml.load(f)

        for key in c.iterkeys():
            if key.isupper():
                self[key] = c[key]
                #print key

class Flask(BaseFlask):
    """Extended version of `Flask` that implements custom config class"""

    def make_config(self, instance_relative=False):
        root_path = self.root_path
        if instance_relative:
            root_path = self.instance_path
        return Config(root_path, self.default_config)

def create_app(mode="development"):
    """Create webapp instance."""
    app = Flask(__name__)
    #Initilise DB
    from bluespot.extensions import db
    db.init_app(app)
    # Load the default configuration
    app.config.from_object('config.default')
    #Load user specified config
    app.config.from_yaml(os.path.join(app.root_path,'..','config.yaml'))
    #initlize assets
    assets = Environment(app)
    assets.register(bundles)
    # simple load all blueprint settings, enabled in config
    load_blueprint_settings(app,blueprint_path='bluespot')
    # simple load all blueprints, enabled in config
    load_blueprints(app,blueprint_path='bluespot')
    # Enable DebugToolbar on debug
    # Enable error handler on productive mode
    if app.config['DEBUG']:
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
        app.logger.error( "DEV")

    else:
        # add errorhandler
        #error_handler(app)
        app.logger.error( "PROD")

    @app.route("/")
    def home():
        return "OK"

    return app

def remove_db_session(exception=None):
    db_session.remove()


text:
PLUGIN.name = "Business Permits"
PLUGIN.desc = "Adds business permits which are needed to purchase certain goods."
PLUGIN.author = "Chessnut"

function PLUGIN:CanPlayerUseBusiness(client, uniqueID)
	local itemTable = nut.item.list[uniqueID]
	if (itemTable and itemTable.permit) then
		if (client:getChar():getInv():hasItem("permit_"..itemTable.permit)) then
			return true
		end
	end
end


text:
package com.coolweather.app.model;

public class ResultInfo {

	private String weatherinfo;

	public String getWeatherinfo() {
		return weatherinfo;
	}

	public void setWeatherinfo(String weatherinfo) {
		this.weatherinfo = weatherinfo;
	}

	@Override
	public String toString() {
		return "ResultInfo [weatherinfo=" + weatherinfo + "]";
	}

}


text:
Project to quickly restore my working environment.

## Usage

```bash
make
# or
make [task-name]
```

### License

see [`MIT`](./LICENSE).


text:
module CommonMark.Util.Parsing
    (
    -- * Success and failure
      success
    , failure

    -- * Combinators
    , discard
    , optional
    , notFollowedBy
    , countOrMore

    -- * Predicate/count parsers
    , takeWhileLo
    , takeWhileHi
    , takeWhileLoHi
    ) where

import Control.Applicative ( Applicative, (<|>), liftA2, many )
import Data.Text ( Text )
import qualified Data.Text as T
import Prelude hiding ( takeWhile )

import Data.Attoparsec.Text ( Parser, count, peekChar, scan, takeWhile )

-- | @success@ is a parser that always succeeds.
success :: Parser ()
success = return ()

-- | @failure@ is a parser that always fails.
failure :: Parser a
failure = fail "no parse"

-- | @discard p@ applies parser @p@ and discards the latter's result.
discard :: Parser a -> Parser ()
discard p = () <$ p

-- | @optional p@ tries to apply parser @p@ and discard the latter's result,
-- or simply succeeds. Does not fail.
optional :: Parser a -> Parser ()
optional p = discard p <|> success

-- | The parser @notFollowedBy p@ succeeds if there is no input left or if
-- the next character does not satisfy predicate @p@. Consumes no input.
notFollowedBy :: (Char -> Bool) -> Parser ()
notFollowedBy p = do
    maybeChar <- peekChar
    case maybeChar of
        Nothing -> success
        Just c | p c       -> failure
               | otherwise -> success

-- | @countOrMore n p@ applies action @p@ repeatedly, @n@ or more times,
-- and returns a list of the results.
-- Generalizes 'Data.Attoparsec.Combinator.many1'.
countOrMore :: Int -> Parser a -> Parser [a]
countOrMore n p = count n p <++> many p

-- | Plain old '(++)' lifted to applicative functors.
infixr 5 <++>
(<++>) :: (Applicative f) => f [a] -> f [a] -> f [a]
(<++>) = liftA2 (++)

-- | @takeWhileLo f lo@ consumes @lo@ characters or more as long as
-- predicate @f@ returns 'True', and returns the consumed input.
--
-- Requires the predicate to succeed on at least @lo@ characters of input.
-- Fails if the predicate never returns 'True' or if the end of the input
-- has been reached.
takeWhileLo :: (Char -> Bool) -> Int -> Parser Text
takeWhileLo f lo =
    takeWhile f >>= \t ->
    case T.compareLength t lo of
        LT -> failure
        EQ -> return t
        GT -> return t

-- | @takeWhileHi f hi@ consumes up to @hi@ characters as long as predicate
-- @f@ returns 'True', and returns the consumed input.
--
-- Does not fail. Returns an empty string if the predicate returns 'False' on
-- the first character of input.
takeWhileHi :: (Char -> Bool) -> Int -> Parser Text
takeWhileHi f hi =
    scan 0 $ \n c -> if n < hi && f c
                     then Just $! n + 1
                     else Nothing

-- | @takeWhileLoHi f lo hi@ consumes from @lo@ to @hi@ characters as long as
-- predicate @f@ returns 'True', and returns the consumed input.
--
-- Requires the predicate to succeed on at least @lo@ characters of input.
-- Fails if the predicate never returns 'True' or if the end of the input
-- has been reached.
takeWhileLoHi :: (Char -> Bool) -> Int -> Int -> Parser Text
takeWhileLoHi f lo hi =
    takeWhileHi f hi >>= \t ->
    case T.compareLength t lo of
        LT -> failure
        EQ -> return t
        GT -> return t


text:
<?php

namespace phpDocumentor\Reflection\Php;

use Mockery as m;
use phpDocumentor\Reflection\Php\Factory\DummyFactoryStrategy;

/**
 * Test case for ProjectFactory
 *
 * @coversDefaultClass phpDocumentor\Reflection\Php\ProjectFactory
 */
class ProjectFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     */
    public function testStrategiesAreChecked()
    {
        new ProjectFactory(array(new DummyFactoryStrategy()));
    }

    /**
     * @covers ::create
     * @covers ::<private>
     */
    public function testCreate()
    {
        $someOtherStrategy = m::mock(ProjectFactoryStrategy::class);
        $someOtherStrategy->shouldReceive('matches')->twice()->andReturn(false);
        $someOtherStrategy->shouldReceive('create')->never();

        $fileStrategyMock = m::mock(ProjectFactoryStrategy::class);
        $fileStrategyMock->shouldReceive('matches')->twice()->andReturn(true);
        $fileStrategyMock->shouldReceive('create')
            ->twice()
            ->andReturnValues(
                array(
                    new File(md5('some/file.php'), 'some/file.php'),
                    new File(md5('some/other.php'), 'some/other.php')
                )
            );

        $projectFactory = new ProjectFactory(array($someOtherStrategy, $fileStrategyMock));

        $files = array('some/file.php', 'some/other.php');
        $project = $projectFactory->create($files);

        $this->assertInstanceOf(Project::class, $project);

        $projectFilePaths = array_keys($project->getFiles());
        $this->assertEquals($files, $projectFilePaths);
    }

    /**
     * @covers ::create
     * @covers ::<private>
     *
     * @expectedException \OutOfBoundsException
     */
    public function testCreateThrowsExceptionWhenStrategyNotFound()
    {
        $projectFactory = new ProjectFactory(array());
        $projectFactory->create(array('aa'));
    }
}


text:
/*

*/

const express = require('express');
const app     = express();
const router  = express.Router();

//Rotas
const index       = require('./routes/index');
const personRoute = require('./routes/personRoute');

app.use('/',        index);
app.use('/persons', personRoute);

module.exports = app;


text:
@interface SnapshotSnapGalleryView()
@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) NSTrackingArea *trackingArea;
@end

@implementation SnapshotSnapGalleryView

- (instancetype)init
{
    self = [super init];
    if (!self) { return nil; }

    self.queue = dispatch_queue_create("io.orta.snapshots_peek_image_queue", DISPATCH_QUEUE_SERIAL);
    self.trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:NSTrackingInVisibleRect | NSTrackingActiveAlways | NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited owner:self userInfo:nil];
    self.wantsLayer = YES;

    return self;
}

// Ensure that we get frame changes

- (void)viewDidMoveToWindow
{
    [super viewDidMoveToWindow];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowResized) name:
     NSWindowWillStartLiveResizeNotification object:self.window];
}

- (void)windowResized
{
    self.frame = CGRectMake(0, 0, CGRectGetWidth(self.superview.bounds), [self maxDimension]);
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/// NSURL -> NSImage

- (void)updateWithURLs:(NSArray <NSURL *>*)URLs
{
    dispatch_async(self.queue, ^{
        NSMutableArray <NSImage *> *images = [NSMutableArray array];
        for (NSURL *url in URLs) {
            NSImage *image = [[NSImage alloc] initByReferencingURL:url];
            if (image) { [images addObject:image]; }
        }

        dispatch_sync(dispatch_get_main_queue(), ^{
            [self updateWithImages:images];
        });
    });
}

// NSImage -> CALayer

- (void)updateWithImages:(NSArray <NSImage *>*)images
{
    [self setAlphaValue:0];
    [self.animator setAlphaValue:1];

    [self.subviews.copy makeObjectsPerformSelector:@selector(removeFromSuperview)];

    for (NSImage *image in images) {
        CALayer *layer = [CALayer layer];
        layer.contents = image;
        [self.layer addSublayer:layer];
    }

    [self updateLayersWithMouseXLocation:100000];
    self.frame = CGRectMake(0, 0, CGRectGetWidth(self.superview.bounds), [self maxDimension]);
}

- (CGFloat)maxDimension
{
    return CGRectGetHeight(self.superview.bounds) / 2;
}

// Taken from my ActionScript 3 Dock implementation:
// https://github.com/orta/virtualapps/blob/master/src/dock/Dock.as#L139

// Lays out the screenshots with a dock-like animation

- (void)updateLayersWithMouseXLocation:(CGFloat)mouseX
{
    CGFloat maxDimension = [self maxDimension];
    CGFloat totalPixelsOfCurve = maxDimension * 1.2;
    CGFloat bottomScale = 0.3;

    CGFloat halfPixelsOfCurve = totalPixelsOfCurve / 2;
    CGFloat itemMargin = 20;
    CGFloat offset = 0;

    for (CALayer *layer in self.layer.sublayers) {
        NSImage *image = layer.contents;
        CGFloat aspectRatio = image.size.width / image.size.height;

        CGFloat distanceFromMouseX = CGRectGetMidX(layer.frame) - mouseX;
        CGFloat scale = bottomScale;

        /// Support fancy dock-like animation
        if ((distanceFromMouseX < halfPixelsOfCurve) && (distanceFromMouseX > (halfPixelsOfCurve * -1))) {

            CGFloat curvedDistanceFromMouseX = ((distanceFromMouseX / halfPixelsOfCurve) * 90) + 90;
            CGFloat radians = curvedDistanceFromMouseX * (M_PI / 180.0);
            CGFloat newScale = sin(radians);

            if(newScale > 1) newScale = 1;
            if(newScale < bottomScale) newScale = bottomScale;
            scale = newScale;
        }

        CGFloat coreWidth = scale * maxDimension;

        CGFloat width = MIN(aspectRatio * coreWidth, maxDimension);
        CGFloat height = MIN(maxDimension * scale,  maxDimension / aspectRatio );

        CGFloat x = offset + itemMargin;

        layer.frame = CGRectMake(x, 0, width, height);
        offset += width + itemMargin;
    }
}

- (NSView *)hitTest:(NSPoint)aPoint
{
    return nil;
}

/// Fades out, then removes the view

- (void)fadeAndRemove
{
    [self.animator setAlphaValue:0];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self.subviews.copy makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self removeFromSuperview];
    });
}

/// Lets the view do mouse tracking

- (void)updateTrackingAreas
{
    [super updateTrackingAreas];
    if (![[self trackingAreas] containsObject:self.trackingArea]) {
        [self addTrackingArea:self.trackingArea];
    }
}

/// Converts the window location into one
/// relative to the view

- (void)mouseMoved:(NSEvent *)event
{
    NSPoint location = [self convertPoint:event.locationInWindow toView:self.superview];
    CGFloat xOffset = [self convertRect:self.bounds fromView:nil].origin.x;
    [self updateLayersWithMouseXLocation:location.x + xOffset];
}

/// Resets the dock-like animation

- (void)mouseExited:(NSEvent *)theEvent
{
    [self updateLayersWithMouseXLocation:100000];
}

@end


text:
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Devices.Tpm;

static class AzureIoTHub
{
    //
    // Note: this device application connects secure to an Azure IoT Hub through TPM. Look here for more information: https://github.com/Azure/azure-iot-hub-vs-cs/wiki/Device-Provisioning-with-TPM
    // To monitor messages sent to device "WeatherStation" use iothub-explorer as follows:
    //    iothub-explorer HostName=MSTIoTHub.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=ApPvR7XCogLnPqGZzdZyuSjL3/Sxl/kG4+saFMZ/1Zc= monitor-events "WeatherStation"
    //

    // Refer to http://aka.ms/azure-iot-hub-vs-cs-cpp for more information on Microsoft Azure IoT Connected Service

    const int logicalDeviceID = 0;   // Use logical device 0 on the TPM

    public static async Task SendDeviceToCloudMessageAsync(string payload)
    {
        TpmDevice myDevice = new TpmDevice(logicalDeviceID);
        string hubUri = myDevice.GetHostName();
        string deviceId = myDevice.GetDeviceId();
        string sasToken = myDevice.GetSASToken();

        var deviceClient = DeviceClient.Create(
            hubUri,
            AuthenticationMethodFactory.
                CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp);

        var message = new Message(Encoding.ASCII.GetBytes(payload));

        await deviceClient.SendEventAsync(message);
    }

    public static async Task SendDeviceToCloudMessageAsync()
    {
#if WINDOWS_UWP
        var str = "Hello, Cloud from a secure UWP C# service!";
#else
        var str = "Hello, Cloud from a secure C# service!";
#endif
        await SendDeviceToCloudMessageAsync(str);
    }

    public static async Task<string> ReceiveCloudToDeviceMessageAsync()
    {
        TpmDevice myDevice = new TpmDevice(logicalDeviceID); // Use logical device 0 on the TPM
        string hubUri = myDevice.GetHostName();
        string deviceId = myDevice.GetDeviceId();
        string sasToken = myDevice.GetSASToken();

        var deviceClient = DeviceClient.Create(
            hubUri,
            AuthenticationMethodFactory.
                CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp);

        while (true)
        {
            var receivedMessage = await deviceClient.ReceiveAsync();

            if (receivedMessage != null)
            {
                var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                await deviceClient.CompleteAsync(receivedMessage);
                return messageData;
            }

            //  Note: In this sample, the polling interval is set to
            //  10 seconds to enable you to see messages as they are sent.
            //  To enable an IoT solution to scale, you should extend this
            //  interval. For example, to scale to 1 million devices, set
            //  the polling interval to 25 minutes.
            //  For further information, see
            //  https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
    }
}


text:
vlogcomp -work work ${XILINX}/verilog/src/glbl.v
vlogcomp -work work ../../../Clock35MHz.v
vlogcomp -work work ../../example_design/Clock35MHz_exdes.v
vlogcomp -work work ../Clock35MHz_tb.v

# compile the project
fuse work.Clock35MHz_tb work.glbl -L unisims_ver -o Clock35MHz_isim.exe

# run the simulation script
./Clock35MHz_isim.exe -gui -tclbatch simcmds.tcl


text:
<?php

namespace ITDoors\HaccpBundle\Services;
use ITDoors\HaccpBundle\Entity\PointGroupCharacteristicRepository;
use Symfony\Component\DependencyInjection\Container;

/**
 * PointGroupService Class
 */
class PointGroupApiV1Service
{
    /**
     * @var Container $container
     */
    protected $container;

    /**
     * __construct()
     *
     * @param Container $container
     */
    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Returns collection of group characteristics
     *
     * @param int $id
     *
     * @return mixed[]
     */
    public function getCharacteristics($id)
    {
        /** @var PointGroupCharacteristicRepository $pgcr */
        $pgcr = $this->container->get('point.group.characteristic.repository');

        $data = $pgcr->getCharacteristicsQueryByGroupId($id);

        return $data->getResult();
    }
}


text:
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var ssumkbn = require( './ssumkbn.native.js' );
var ndarray = require( './ndarray.native.js' );

// MAIN //

setReadOnly( ssumkbn, 'ndarray', ndarray );

// EXPORTS //

module.exports = ssumkbn;


text:
<?php

declare(strict_types = 1);

namespace KoolKode\Async\Postgres;

use AsyncInterop\Promise;
use KoolKode\Async\Success;

/**
 * Connection backed by a pooled PostgreSQL client.
 *
 * @author Martin Schröder
 */
class PooledConnection extends PostgresConnection
{
    protected $disposer;

    public function __construct(Client $client, callable $disposer, string $prefix = '')
    {
        parent::__construct($client, $prefix);

        $this->disposer = $disposer;
    }

    public function shutdown(\Throwable $e = null): Promise
    {
        if (!$this->disposed) {
            $this->disposed = true;

            ($this->disposer)($this->client);
        }

        return new Success();
    }
}


text:
package org.netbeans.cubeon.jira.repository;

import java.awt.Image;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.netbeans.cubeon.jira.remote.JiraException;
import org.netbeans.cubeon.jira.repository.ui.ConfigurationHandlerImpl;
import org.netbeans.cubeon.jira.tasks.JiraTask;
import org.netbeans.cubeon.jira.utils.JiraExceptionHandler;
import org.netbeans.cubeon.tasks.core.api.TaskEditorFactory;
import org.netbeans.cubeon.tasks.spi.query.TaskQuery;
import org.netbeans.cubeon.tasks.spi.repository.TaskRepository;
import org.netbeans.cubeon.tasks.spi.repository.TaskRepositoryType;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.filesystems.Repository;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.ImageUtilities;
import org.openide.util.lookup.Lookups;

/**
 *
 * @author Anuradha G
 */
public class JiraTaskRepositoryProvider implements TaskRepositoryType {

    static final String BASE_PATH = "cubeon/jira_repositories/";//NOI18N
    private List<JiraTaskRepository> taskRepositorys = new ArrayList<JiraTaskRepository>();
    private final JiraRepositoryPersistence persistence;
    private AtomicBoolean initiailzed = new AtomicBoolean(false);
    private FileObject baseDir = null;

    public JiraTaskRepositoryProvider() {
        try {
            baseDir = FileUtil.createFolder(Repository.getDefault().
                    getDefaultFileSystem().getRoot(), BASE_PATH);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        assert baseDir != null;
        persistence = new JiraRepositoryPersistence(this, baseDir);
    }

    public String getId() {
        return "jira";//NOI18N
    }

    public String getName() {
        return NbBundle.getMessage(JiraTaskRepositoryProvider.class, "LBL_Jira_Name");
    }

    public String getDescription() {
        return NbBundle.getMessage(JiraTaskRepositoryProvider.class, "LBL_Jira_Description");
    }

    public Lookup getLookup() {
        return Lookups.fixed(this);
    }

    public Image getImage() {
        return ImageUtilities.loadImage("org/netbeans/cubeon/jira/repository/jira-logo.gif");
    }

    public TaskRepository persistRepository(TaskRepository repository) {

        final JiraTaskRepository jiraTaskRepository =
                repository.getLookup().lookup(JiraTaskRepository.class);
        if (jiraTaskRepository != null) {
            persistence.addRepository(jiraTaskRepository);
            if (!taskRepositorys.contains(jiraTaskRepository)) {
                taskRepositorys.add(jiraTaskRepository);
            }
            JiraRepositoryExtension extension = jiraTaskRepository.getNotifier();
            extension.fireNameChenged();
            extension.fireDescriptionChenged();
            RequestProcessor.getDefault().post(new Runnable() {

                public void run() {
                    try {
                        //reconnect and update repository
                        jiraTaskRepository.reconnect();
                        jiraTaskRepository.updateAttributes();
                        jiraTaskRepository.synchronize();
                    } catch (JiraException ex) {
                        JiraExceptionHandler.notify(ex);
                    }

                }
            });

            return repository;
        }

        return null;
    }

    public boolean removeRepository(TaskRepository repository) {

        JiraTaskRepository jiraTaskRepository =
                repository.getLookup().lookup(JiraTaskRepository.class);
        if (jiraTaskRepository != null) {
            persistence.removeRepository(jiraTaskRepository);
            taskRepositorys.remove(jiraTaskRepository);
            List<String> taskIds = jiraTaskRepository.getTaskIds();
            TaskEditorFactory factory = Lookup.getDefault().lookup(TaskEditorFactory.class);
            for (String id : taskIds) {
                JiraTask task = jiraTaskRepository.getTaskElementById(id);
                if (task != null) {
                    jiraTaskRepository.getNotifier().fireTaskRemoved(task);
                    factory.closeTask(task);
                }

            }
            List<TaskQuery> querys = jiraTaskRepository.getQuerySupport().getTaskQuerys();
            for (TaskQuery query : querys) {
                jiraTaskRepository.getQuerySupport().removeTaskQuery(query);
            }

            try {
                FileObject baseDir1 = jiraTaskRepository.getBaseDir();

                baseDir1.delete();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
            return true;
        }

        return false;

    }

    public List<TaskRepository> getRepositorys() {

        if (!initiailzed.getAndSet(true)) {
            taskRepositorys.addAll(persistence.getJiraTaskRepositorys());

        }
        return new ArrayList<TaskRepository>(taskRepositorys);
    }

    public TaskRepository getRepositoryById(String id) {
        for (TaskRepository taskRepository : taskRepositorys) {
            if (taskRepository.getId().equals(id)) {
                return taskRepository;
            }
        }

        return null;
    }

    public ConfigurationHandler createConfigurationHandler() {
        return new ConfigurationHandlerImpl(this);
    }

    public FileObject getBaseDir() {
        return baseDir;
    }
}


text:
graphviz-aws
============

AWS architecture the easy way

Example Output
--------------

![Example](https://raw.github.com/daniellawrence/graphviz-aws/master/example.png)

Example Code
------------

If we look at the example included in the base of this project (example.sh).
We use the following syntax to create the dot source

```sh
cat <<EOF > example.dot

digraph G {
    web1 [$I_EC2];
    web2 [$I_EC2];
    app [$I_EC2];
    db  [$I_MYSQL];
    db_slave  [$I_MYSQL];
    s3  [$I_S3];
    gl  [$I_GLACIER];

    web1 -> app $OVER_HTTP
    web2 -> app $OVER_HTTP

    app -> db $OVER_MYSQL
    db  -> db_slave $OVER_MYSQL

    app -> s3 $OVER_API
    db  -> s3 $OVER_API

    s3  -> gl $OVER_API
}

EOF

```

Install
-------

```sh
$ ./setup.sh
Downloading AWS Simple Icons    [Skipped]
Unzipping AWS Simple Icons    [Skipped]
Deleting MACOSX files    [Skipped]
Installing librsvg2-bin    [Skipped]
Images convereted: 117
````

How it works
------------

* It will use the Simple AWS icons provided by AWS.
* Convert them all to by PNG (from SVG)
* Use graphviz/dot to generate the images