<commit_before>// Word cloud layout by Jason Davies, http://www.jasondavies.com/word-cloud/
// Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf
(function() {
  function cloud() {
    var size = [512, 512],
        text = cloudText,
        font = cloudFont,
        fontSize = cloudFontSize,
        fontStyle = cloudFontNormal,
        fontWeight = cloudFontNormal,
        rotate = cloudRotate,
        padding = cloudPadding,
        spiral = archimedeanSpiral,
        words = [],
        timeInterval = Infinity,
        event = d3.dispatch("word", "end"),
        timer = null,
        cloud = {};

    cloud.start = function() {
      var board = zeroArray((size[0] >> 5) * size[1]),
          bounds = null,
          n = words.length,
          i = -1,
          tags = [],
          data = words.map(function(d, i) {
            d.text = text.call(this, d, i);
            d.font = font.call(this, d, i);
            d.style = fontStyle.call(this, d, i);
            d.weight = fontWeight.call(this, d, i);
            d.rotate = rotate.call(this, d, i);
            d.size = ~~fontSize.call(this, d, i);
            d.padding = padding.call(this, d, i);
            return d;
          }).sort(function(a, b) { return b.size - a.size; });

      if (timer) clearInterval(timer);
      timer = setInterval(step, 0);
      step();

      return cloud;

      function step() {
        var start = +new Date,
            d;
        while (+new Date - start < timeInterval && ++i < n && timer) {
          d = data[i];
          d.x = (size[0] * (Math.random() + .5)) >> 1;
          d.y = (size[1] * (Math.random() + .5)) >> 1;
          cloudSprite(d, data, i);
          if (d.hasText && place(board, d, bounds)) {
            tags.push(d);
            event.word(d);
            if (bounds) cloudBounds(bounds, d);
            else bounds = [{x: d.x + d.x0, y: d.y + d.y0}, {x: d.x + d.x1, y: d.y + d.y1}];
            // Temporary hack
            d.x -= size[0] >> 1;
            d.y -= size[1] >> 1;
          }
        }
        if (i >= n) {
          cloud.stop();
          event.end(tags, bounds);
        }
      }
    }

    cloud.stop = function() {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
      return cloud;
    };

    cloud.timeInterval = function(x) {
      if (!arguments.length) return timeInterval;
      timeInterval = x == null ? Infinity : x;
      return cloud;
    };

    function place(board, tag, bounds) {
      var perimeter = [{x: 0, y: 0}, {x: size[0], y: size[1]}],
          startX = tag.x,
          startY = tag.y,
          maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]),
          s = spiral(size),
          dt = Math.random() < .5 ? 1 : -1,
          t = -dt,
          dxdy,
          dx,
          dy;

      while (dxdy = s(t += dt)) {
        dx = ~~dxdy[0];
        dy = ~~dxdy[1];

        if (Math.min(dx, dy) > maxDelta) break;

        tag.x = startX + dx;
        tag.y = startY + dy;

        if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 ||
            tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
        // TODO only check for collisions within current bounds.
        if (!bounds || !cloudCollide(tag, board, size[0])) {
          if (!bounds || collideRects(tag, bounds)) {
            var sprite = tag.sprite,
                w = tag.width >> 5,
                sw = size[0] >> 5,
                lx = tag.x - (w << 4),
                sx = lx & 0x7f,
                msx = 32 - sx,
                h = tag.y1 - tag.y0,
                x = (tag.y + tag.y0) * sw + (lx >> 5),
                last;
            for (var j = 0; j < h; j++) {
              last = 0;
              for (var i = 0; i <= w; i++) {
                board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
              }
              x += sw;
            }
            delete tag.sprite;
            return true;
          }
        }
      }
      return false;
    }

    cloud.words = function(x) {
      if (!arguments.length) return words;
      words = x;
      return cloud;
    };

    cloud.size = function(x) {
      if (!arguments.length) return size;
      size = [+x[0], +x[1]];
      return cloud;
    };

    cloud.font = function(x) {
      if (!arguments.length) return font;
      font = d3.functor(x);
      return cloud;
    };

    cloud.fontStyle = function(x) {
      if (!arguments.length) return fontStyle;
      fontStyle = d3.functor(x);
      return cloud;
    };

    cloud.fontWeight = function(x) {
      if (!arguments.length) return fontWeight;
      fontWeight = d3.functor(x);
      return cloud;
    };

    cloud.rotate = function(x) {
      if (!arguments.length) return rotate;
      rotate = d3.functor(x);
      return cloud;
    };

    cloud.text = function(x) {
      if (!arguments.length) return text;
      text = d3.functor(x);
      return cloud;
    };

    cloud.spiral = function(x) {
      if (!arguments.length) return spiral;
      spiral = spirals[x + ""] || x;
      return cloud;
    };

    cloud.fontSize = function(x) {
      if (!arguments.length) return fontSize;
      fontSize = d3.functor(x);
      return cloud;
    };

    cloud.padding = function(x) {
      if (!arguments.length) return padding;
      padding = d3.functor(x);
      return cloud;
    };

    return d3.rebind(cloud, event, "on");
  }

  function cloudText(d) {
    return d.text;
  }

  function cloudFont() {
    return "serif";
  }

  function cloudFontNormal() {
    return "normal";
  }

  function cloudFontSize(d) {
    return Math.sqrt(d.value);
  }

  function cloudRotate() {
    return (~~(Math.random() * 6) - 3) * 30;
  }

  function cloudPadding() {
    return 1;
  }

  // Fetches a monochrome sprite bitmap for the specified text.
  // Load in batches for speed.
  function cloudSprite(d, data, di) {
    if (d.sprite) return;
    c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
    var x = 0,
        y = 0,
        maxh = 0,
        n = data.length;
    --di;
    while (++di < n) {
      d = data[di];
      c.save();
      c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font;
      var w = c.measureText(d.text + "m").width * ratio,
          h = d.size << 1;
      if (d.rotate) {
        var sr = Math.sin(d.rotate * cloudRadians),
            cr = Math.cos(d.rotate * cloudRadians),
            wcr = w * cr,
            wsr = w * sr,
            hcr = h * cr,
            hsr = h * sr;
        w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5;
        h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
      } else {
        w = (w + 0x1f) >> 5 << 5;
      }
      if (h > maxh) maxh = h;
      if (x + w >= (cw << 5)) {
        x = 0;
        y += maxh;
        maxh = 0;
      }
      if (y + h >= ch) break;
      c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
      if (d.rotate) c.rotate(d.rotate * cloudRadians);
      c.fillText(d.text, 0, 0);
      if (d.padding) c.lineWidth = 2 * d.padding, c.strokeText(d.text, 0, 0);
      c.restore();
      d.width = w;
      d.height = h;
      d.xoff = x;
      d.yoff = y;
      d.x1 = w >> 1;
      d.y1 = h >> 1;
      d.x0 = -d.x1;
      d.y0 = -d.y1;
      d.hasText = true;
      x += w;
    }
    var pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,
        sprite = [];
    while (--di >= 0) {
      d = data[di];
      if (!d.hasText) continue;
      var w = d.width,
          w32 = w >> 5,
          h = d.y1 - d.y0;
      // Zero the buffer
      for (var i = 0; i < h * w32; i++) sprite[i] = 0;
      x = d.xoff;
      if (x == null) return;
      y = d.yoff;
      var seen = 0,
          seenRow = -1;
      for (var j = 0; j < h; j++) {
        for (var i = 0; i < w; i++) {
          var k = w32 * j + (i >> 5),
              m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
          sprite[k] |= m;
          seen |= m;
        }
        if (seen) seenRow = j;
        else {
          d.y0++;
          h--;
          j--;
          y++;
        }
      }
      d.y1 = d.y0 + seenRow;
      d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
    }
  }

  // Use mask-based collision detection.
  function cloudCollide(tag, board, sw) {
    sw >>= 5;
    var sprite = tag.sprite,
        w = tag.width >> 5,
        lx = tag.x - (w << 4),
        sx = lx & 0x7f,
        msx = 32 - sx,
        h = tag.y1 - tag.y0,
        x = (tag.y + tag.y0) * sw + (lx >> 5),
        last;
    for (var j = 0; j < h; j++) {
      last = 0;
      for (var i = 0; i <= w; i++) {
        if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0))
            & board[x + i]) return true;
      }
      x += sw;
    }
    return false;
  }

  function cloudBounds(bounds, d) {
    var b0 = bounds[0],
        b1 = bounds[1];
    if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
    if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
    if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
    if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
  }

  function collideRects(a, b) {
    return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y;
  }

  function archimedeanSpiral(size) {
    var e = size[0] / size[1];
    return function(t) {
      return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)];
    };
  }

  function rectangularSpiral(size) {
    var dy = 4,
        dx = dy * size[0] / size[1],
        x = 0,
        y = 0;
    return function(t) {
      var sign = t < 0 ? -1 : 1;
      // See triangular numbers: T_n = n * (n + 1) / 2.
      switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
        case 0:  x += dx; break;
        case 1:  y += dy; break;
        case 2:  x -= dx; break;
        default: y -= dy; break;
      }
      return [x, y];
    };
  }

  // TODO reuse arrays?
  function zeroArray(n) {
    var a = [],
        i = -1;
    while (++i < n) a[i] = 0;
    return a;
  }

  var cloudRadians = Math.PI / 180,
      cw = 1 << 11 >> 5,
      ch = 1 << 11,
      canvas,
      ratio = 1;

  if (typeof document !== "undefined") {
    canvas = document.createElement("canvas");
    canvas.width = 1;
    canvas.height = 1;
    ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2);
    canvas.width = (cw << 5) / ratio;
    canvas.height = ch / ratio;
  } else {
    // Attempt to use node-canvas.
    canvas = new Canvas(cw << 5, ch);
  }

  var c = canvas.getContext("2d"),
      spirals = {
        archimedean: archimedeanSpiral,
        rectangular: rectangularSpiral
      };
  c.fillStyle = c.strokeStyle = "red";
  c.textAlign = "center";

  if (typeof module === "object" && module.exports) module.exports = cloud;
  else (d3.layout || (d3.layout = {})).cloud = cloud;
})();
<commit_msg>Create d3.layout.cloud.js<commit_after>// Word cloud layout by Jason Davies, http://www.jasondavies.com/word-cloud/
// Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf
(function() {
  function cloud() {
    var size = [256, 256],
        text = cloudText,
        font = cloudFont,
        fontSize = cloudFontSize,
        fontStyle = cloudFontNormal,
        fontWeight = cloudFontNormal,
        rotate = cloudRotate,
        padding = cloudPadding,
        spiral = archimedeanSpiral,
        words = [],
        timeInterval = Infinity,
        event = d3.dispatch("word", "end"),
        timer = null,
        cloud = {};

    cloud.start = function() {
      var board = zeroArray((size[0] >> 5) * size[1]),
          bounds = null,
          n = words.length,
          i = -1,
          tags = [],
          data = words.map(function(d, i) {
            d.text = text.call(this, d, i);
            d.font = font.call(this, d, i);
            d.style = fontStyle.call(this, d, i);
            d.weight = fontWeight.call(this, d, i);
            d.rotate = rotate.call(this, d, i);
            d.size = ~~fontSize.call(this, d, i);
            d.padding = padding.call(this, d, i);
            return d;
          }).sort(function(a, b) { return b.size - a.size; });

      if (timer) clearInterval(timer);
      timer = setInterval(step, 0);
      step();

      return cloud;

      function step() {
        var start = +new Date,
            d;
        while (+new Date - start < timeInterval && ++i < n && timer) {
          d = data[i];
          d.x = (size[0] * (Math.random() + .5)) >> 1;
          d.y = (size[1] * (Math.random() + .5)) >> 1;
          cloudSprite(d, data, i);
          if (d.hasText && place(board, d, bounds)) {
            tags.push(d);
            event.word(d);
            if (bounds) cloudBounds(bounds, d);
            else bounds = [{x: d.x + d.x0, y: d.y + d.y0}, {x: d.x + d.x1, y: d.y + d.y1}];
            // Temporary hack
            d.x -= size[0] >> 1;
            d.y -= size[1] >> 1;
          }
        }
        if (i >= n) {
          cloud.stop();
          event.end(tags, bounds);
        }
      }
    }

    cloud.stop = function() {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
      return cloud;
    };

    cloud.timeInterval = function(x) {
      if (!arguments.length) return timeInterval;
      timeInterval = x == null ? Infinity : x;
      return cloud;
    };

    function place(board, tag, bounds) {
      var perimeter = [{x: 0, y: 0}, {x: size[0], y: size[1]}],
          startX = tag.x,
          startY = tag.y,
          maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]),
          s = spiral(size),
          dt = Math.random() < .5 ? 1 : -1,
          t = -dt,
          dxdy,
          dx,
          dy;

      while (dxdy = s(t += dt)) {
        dx = ~~dxdy[0];
        dy = ~~dxdy[1];

        if (Math.min(dx, dy) > maxDelta) break;

        tag.x = startX + dx;
        tag.y = startY + dy;

        if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 ||
            tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
        // TODO only check for collisions within current bounds.
        if (!bounds || !cloudCollide(tag, board, size[0])) {
          if (!bounds || collideRects(tag, bounds)) {
            var sprite = tag.sprite,
                w = tag.width >> 5,
                sw = size[0] >> 5,
                lx = tag.x - (w << 4),
                sx = lx & 0x7f,
                msx = 32 - sx,
                h = tag.y1 - tag.y0,
                x = (tag.y + tag.y0) * sw + (lx >> 5),
                last;
            for (var j = 0; j < h; j++) {
              last = 0;
              for (var i = 0; i <= w; i++) {
                board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
              }
              x += sw;
            }
            delete tag.sprite;
            return true;
          }
        }
      }
      return false;
    }

    cloud.words = function(x) {
      if (!arguments.length) return words;
      words = x;
      return cloud;
    };

    cloud.size = function(x) {
      if (!arguments.length) return size;
      size = [+x[0], +x[1]];
      return cloud;
    };

    cloud.font = function(x) {
      if (!arguments.length) return font;
      font = d3.functor(x);
      return cloud;
    };

    cloud.fontStyle = function(x) {
      if (!arguments.length) return fontStyle;
      fontStyle = d3.functor(x);
      return cloud;
    };

    cloud.fontWeight = function(x) {
      if (!arguments.length) return fontWeight;
      fontWeight = d3.functor(x);
      return cloud;
    };

    cloud.rotate = function(x) {
      if (!arguments.length) return rotate;
      rotate = d3.functor(x);
      return cloud;
    };

    cloud.text = function(x) {
      if (!arguments.length) return text;
      text = d3.functor(x);
      return cloud;
    };

    cloud.spiral = function(x) {
      if (!arguments.length) return spiral;
      spiral = spirals[x + ""] || x;
      return cloud;
    };

    cloud.fontSize = function(x) {
      if (!arguments.length) return fontSize;
      fontSize = d3.functor(x);
      return cloud;
    };

    cloud.padding = function(x) {
      if (!arguments.length) return padding;
      padding = d3.functor(x);
      return cloud;
    };

    return d3.rebind(cloud, event, "on");
  }

  function cloudText(d) {
    return d.text;
  }

  function cloudFont() {
    return "serif";
  }

  function cloudFontNormal() {
    return "normal";
  }

  function cloudFontSize(d) {
    return Math.sqrt(d.value);
  }

  function cloudRotate() {
    return (~~(Math.random() * 6) - 3) * 30;
  }

  function cloudPadding() {
    return 1;
  }

  // Fetches a monochrome sprite bitmap for the specified text.
  // Load in batches for speed.
  function cloudSprite(d, data, di) {
    if (d.sprite) return;
    c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
    var x = 0,
        y = 0,
        maxh = 0,
        n = data.length;
    --di;
    while (++di < n) {
      d = data[di];
      c.save();
      c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font;
      var w = c.measureText(d.text + "m").width * ratio,
          h = d.size << 1;
      if (d.rotate) {
        var sr = Math.sin(d.rotate * cloudRadians),
            cr = Math.cos(d.rotate * cloudRadians),
            wcr = w * cr,
            wsr = w * sr,
            hcr = h * cr,
            hsr = h * sr;
        w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5;
        h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
      } else {
        w = (w + 0x1f) >> 5 << 5;
      }
      if (h > maxh) maxh = h;
      if (x + w >= (cw << 5)) {
        x = 0;
        y += maxh;
        maxh = 0;
      }
      if (y + h >= ch) break;
      c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
      if (d.rotate) c.rotate(d.rotate * cloudRadians);
      c.fillText(d.text, 0, 0);
      if (d.padding) c.lineWidth = 2 * d.padding, c.strokeText(d.text, 0, 0);
      c.restore();
      d.width = w;
      d.height = h;
      d.xoff = x;
      d.yoff = y;
      d.x1 = w >> 1;
      d.y1 = h >> 1;
      d.x0 = -d.x1;
      d.y0 = -d.y1;
      d.hasText = true;
      x += w;
    }
    var pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,
        sprite = [];
    while (--di >= 0) {
      d = data[di];
      if (!d.hasText) continue;
      var w = d.width,
          w32 = w >> 5,
          h = d.y1 - d.y0;
      // Zero the buffer
      for (var i = 0; i < h * w32; i++) sprite[i] = 0;
      x = d.xoff;
      if (x == null) return;
      y = d.yoff;
      var seen = 0,
          seenRow = -1;
      for (var j = 0; j < h; j++) {
        for (var i = 0; i < w; i++) {
          var k = w32 * j + (i >> 5),
              m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
          sprite[k] |= m;
          seen |= m;
        }
        if (seen) seenRow = j;
        else {
          d.y0++;
          h--;
          j--;
          y++;
        }
      }
      d.y1 = d.y0 + seenRow;
      d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
    }
  }

  // Use mask-based collision detection.
  function cloudCollide(tag, board, sw) {
    sw >>= 5;
    var sprite = tag.sprite,
        w = tag.width >> 5,
        lx = tag.x - (w << 4),
        sx = lx & 0x7f,
        msx = 32 - sx,
        h = tag.y1 - tag.y0,
        x = (tag.y + tag.y0) * sw + (lx >> 5),
        last;
    for (var j = 0; j < h; j++) {
      last = 0;
      for (var i = 0; i <= w; i++) {
        if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0))
            & board[x + i]) return true;
      }
      x += sw;
    }
    return false;
  }

  function cloudBounds(bounds, d) {
    var b0 = bounds[0],
        b1 = bounds[1];
    if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
    if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
    if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
    if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
  }

  function collideRects(a, b) {
    return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y;
  }

  function archimedeanSpiral(size) {
    var e = size[0] / size[1];
    return function(t) {
      return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)];
    };
  }

  function rectangularSpiral(size) {
    var dy = 4,
        dx = dy * size[0] / size[1],
        x = 0,
        y = 0;
    return function(t) {
      var sign = t < 0 ? -1 : 1;
      // See triangular numbers: T_n = n * (n + 1) / 2.
      switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
        case 0:  x += dx; break;
        case 1:  y += dy; break;
        case 2:  x -= dx; break;
        default: y -= dy; break;
      }
      return [x, y];
    };
  }

  // TODO reuse arrays?
  function zeroArray(n) {
    var a = [],
        i = -1;
    while (++i < n) a[i] = 0;
    return a;
  }

  var cloudRadians = Math.PI / 180,
      cw = 1 << 11 >> 5,
      ch = 1 << 11,
      canvas,
      ratio = 1;

  if (typeof document !== "undefined") {
    canvas = document.createElement("canvas");
    canvas.width = 1;
    canvas.height = 1;
    ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2);
    canvas.width = (cw << 5) / ratio;
    canvas.height = ch / ratio;
  } else {
    // Attempt to use node-canvas.
    canvas = new Canvas(cw << 5, ch);
  }

  var c = canvas.getContext("2d"),
      spirals = {
        archimedean: archimedeanSpiral,
        rectangular: rectangularSpiral
      };
  c.fillStyle = c.strokeStyle = "red";
  c.textAlign = "center";

  if (typeof module === "object" && module.exports) module.exports = cloud;
  else (d3.layout || (d3.layout = {})).cloud = cloud;
})();
<|endoftext|>


<commit_before>//= require "_modernizr.custom.27778"
//= require "jquery"
//= require "swiper"
//= require "bootstrap"
//= require "bootstrap-tabcollapse"
//= require "_jquery.sticky-kit"
//= require "_jquery.zoomslider"
//= require "floatlabel.js/floatlabels.js"
//= require "bootstrap-datepicker"
//= require "iCheck"
//= require "_picturefill.min.js"
//= require "responsive-toolkit"

!function(a){a.fn.datepicker.dates.hu={days:["Vasárnap","Hétfő","Kedd","Szerda","Csütörtök","Péntek","Szombat","Vasárnap"],daysShort:["Vas","Hét","Ked","Sze","Csü","Pén","Szo","Vas"],daysMin:["Va","Hé","Ke","Sz","Cs","Pé","Sz","Va"],months:["Január","Február","Március","Április","Május","Június","Július","Augusztus","Szeptember","Október","November","December"],monthsShort:["Jan","Feb","Már","Ápr","Máj","Jún","Júl","Aug","Sze","Okt","Nov","Dec"],today:"Ma",weekStart:1,format:"yyyy.mm.dd"}}(jQuery);

+function ($, viewport) {

		var swiper1 = new Swiper('#gallery-eskuvo .swiper-container', {
			nextButton: '#gallery-eskuvo .swiper-button-next',
			prevButton: '#gallery-eskuvo .swiper-button-prev',
			slidesPerView: 'auto',
			centeredSlides: true,
			paginationClickable: true,
	        spaceBetween: 1,
	        autoplay: 2500,
	        preloadImages: true,
	        autoplayDisableOnInteraction: false,

		});

		var swiper2 = new Swiper('#gallery-beauty .swiper-container', {
			nextButton: '#gallery-beauty .swiper-button-next',
			prevButton: '#gallery-beauty .swiper-button-prev',
			slidesPerView: 'auto',
			centeredSlides: true,
			paginationClickable: true,
	        spaceBetween: 1,
	        autoplay: 2500,
	        preloadImages: true,
	      	autoplayDisableOnInteraction: false,

		});

	$(document).ready(function () {

		$('#home').css({'height':($(window).height())+'px'});
		$('.swiper-slide img').height($(window).height()-150);

		$(window).resize(function(){
			$('#home').css({'height':($(window).height())+'px'});
			$('.swiper-slide img').height($(window).height()-150);

			swiper1.update();
			swiper2.update();

			$(document.body).trigger("sticky_kit:recalc");

			var anchor, href;
			var activeLinks = $('#top-nav-collapse li.active > a')
			if(activeLinks.length) {

				for (var i = 0; i < activeLinks.length; i++) {

					href = $(activeLinks[i]).attr('href')
					if(href != '#') anchor = href;
				}
				  $('html, body').animate({
				  	scrollTop: $(anchor).offset().top -70
				  }, 0)
			} else {
			  // Fragment doesn't exist
			}

		})

	    $('#top-nav .nav > li').eq(Math.floor($('#top-nav .nav > li').length / 2) - 1).addClass('center');

	    $('.navbar-fixed-top a').click(function(event) {
	        var $anchor = $(this);
	        if($($anchor.attr('href')).length){
	        	$('html, body').stop().animate({
	        	    scrollTop: $($anchor.attr('href')).offset().top - 70
	        	}, 400);
	        }

	    });

	    // Highlight the top nav as scrolling occurs
	    $('body').scrollspy({
	        target: '.navbar-fixed-top',
	        offset: $('.navbar-fixed-top').height() + 110
	    })

	    // Closes the Responsive Menu on Menu Item Click
	    $('.navbar-collapse ul li:not(.dropdown) a').click(function() {
	        $('.navbar-toggle:visible').click();
	    });

	    $(document).on("shown.bs.collapse shown.bs.tab", ".panel-collapse, a[data-toggle='tab']", function(el){

	    	var $this = $(this);

	    	$('html, body').stop().animate({
	    	    scrollTop: $($this.attr('href')).offset().top - 145
	    	}, 1);

	    })

	    // $('#info-eskuvo').tabCollapse();
	    // $('#info-beauty').tabCollapse();

	    if( viewport.is('>xs') ) {

        	$("[data-sticky_column]").stick_in_parent({
          		parent: "[data-sticky_parent]",
          		offset_top: 50,
          		recalc_every: 1
    	    })

    	    $(document).on("shown.bs.collapse shown.bs.tab", ".panel-collapse, a[data-toggle='tab']", function(el){

    	    	var $this = $(this);

    	    	$(this).closest('aside').find('img').attr('src', $($(this).attr('href')).find('img').attr('src'));

    	    	$(document.body).trigger("sticky_kit:recalc");

    	    })

	    }

	    $('#info-eskuvo .nav-list a').first().tab('show');
	    $('#info-beauty .nav-list a').first().tab('show');

	    $(document.body).trigger("sticky_kit:recalc");

	    // $('input, textarea').each(function(){
	    // 	var l = $(this).parent().find('label');
	    // 	$(this).attr('placeholder', l.text().replace(':', ''))
	    // 	l.remove();
	    // })

	    $('input, textarea').floatlabel({
			labelEndTop: -20,
			paddingOffset: 0
	    });

	    $('.datepicker').datepicker({
	    	language: "hu"
	    })

	    $('input').iCheck({
	      checkboxClass: 'icheckbox_square-blue',
	      radioClass: 'iradio_square-blue',
	      increaseArea: '20%' // optional
	    });

	});

	$(window).load(function() {

		swiper1.update();
		swiper2.update();

	});

	$(window).scroll(function(){
		if(this.scrollY > $(window).height())
			$('#top-nav').addClass('inverse')
		else
			$('#top-nav').removeClass('inverse')
	})

}(jQuery, ResponsiveBootstrapToolkit);

<commit_msg>image show automatically info<commit_after>//= require "_modernizr.custom.27778"
//= require "jquery"
//= require "swiper"
//= require "bootstrap"
//= require "bootstrap-tabcollapse"
//= require "_jquery.sticky-kit"
//= require "_jquery.zoomslider"
//= require "floatlabel.js/floatlabels.js"
//= require "bootstrap-datepicker"
//= require "iCheck"
//= require "_picturefill.min.js"
//= require "responsive-toolkit"

!function(a){a.fn.datepicker.dates.hu={days:["Vasárnap","Hétfő","Kedd","Szerda","Csütörtök","Péntek","Szombat","Vasárnap"],daysShort:["Vas","Hét","Ked","Sze","Csü","Pén","Szo","Vas"],daysMin:["Va","Hé","Ke","Sz","Cs","Pé","Sz","Va"],months:["Január","Február","Március","Április","Május","Június","Július","Augusztus","Szeptember","Október","November","December"],monthsShort:["Jan","Feb","Már","Ápr","Máj","Jún","Júl","Aug","Sze","Okt","Nov","Dec"],today:"Ma",weekStart:1,format:"yyyy.mm.dd"}}(jQuery);

+function ($, viewport) {

		var swiper1 = new Swiper('#gallery-eskuvo .swiper-container', {
			nextButton: '#gallery-eskuvo .swiper-button-next',
			prevButton: '#gallery-eskuvo .swiper-button-prev',
			slidesPerView: 'auto',
			centeredSlides: true,
			paginationClickable: true,
	        spaceBetween: 1,
	        autoplay: 2500,
	        preloadImages: true,
	        autoplayDisableOnInteraction: false,

		});

		var swiper2 = new Swiper('#gallery-beauty .swiper-container', {
			nextButton: '#gallery-beauty .swiper-button-next',
			prevButton: '#gallery-beauty .swiper-button-prev',
			slidesPerView: 'auto',
			centeredSlides: true,
			paginationClickable: true,
	        spaceBetween: 1,
	        autoplay: 2500,
	        preloadImages: true,
	      	autoplayDisableOnInteraction: false,

		});

	$(document).ready(function () {

		$('#home').css({'height':($(window).height())+'px'});
		$('.swiper-slide img').height($(window).height()-150);

		$(window).resize(function(){
			$('#home').css({'height':($(window).height())+'px'});
			$('.swiper-slide img').height($(window).height()-150);

			swiper1.update();
			swiper2.update();

			$(document.body).trigger("sticky_kit:recalc");

			var anchor, href;
			var activeLinks = $('#top-nav-collapse li.active > a')
			if(activeLinks.length) {

				for (var i = 0; i < activeLinks.length; i++) {

					href = $(activeLinks[i]).attr('href')
					if(href != '#') anchor = href;
				}
				  $('html, body').animate({
				  	scrollTop: $(anchor).offset().top -70
				  }, 0)
			} else {
			  // Fragment doesn't exist
			}

		})

	    $('#top-nav .nav > li').eq(Math.floor($('#top-nav .nav > li').length / 2) - 1).addClass('center');

	    $('.navbar-fixed-top a').click(function(event) {
	        var $anchor = $(this);
	        if($($anchor.attr('href')).length){
	        	$('html, body').stop().animate({
	        	    scrollTop: $($anchor.attr('href')).offset().top - 70
	        	}, 400);
	        }

	    });

	    // Highlight the top nav as scrolling occurs
	    $('body').scrollspy({
	        target: '.navbar-fixed-top',
	        offset: $('.navbar-fixed-top').height() + 110
	    })

	    // Closes the Responsive Menu on Menu Item Click
	    $('.navbar-collapse ul li:not(.dropdown) a').click(function() {
	        $('.navbar-toggle:visible').click();
	    });

	    $(document).on("shown.bs.collapse shown.bs.tab", ".panel-collapse, a[data-toggle='tab']", function(el){

	    	var $this = $(this);

	    	$('html, body').stop().animate({
	    	    scrollTop: $($this.attr('href')).offset().top - 145
	    	}, 1);

	    })

	    // $('#info-eskuvo').tabCollapse();
	    // $('#info-beauty').tabCollapse();

	    if( viewport.is('>xs') ) {

        	$("[data-sticky_column]").stick_in_parent({
          		parent: "[data-sticky_parent]",
          		offset_top: 50,
          		recalc_every: 1
    	    })

    	    $(document).on("shown.bs.collapse shown.bs.tab", ".panel-collapse, a[data-toggle='tab']", function(el){

    	    	var $this = $(this);

    	    	$(this).closest('aside').find('img').attr('src', $($(this).attr('href')).find('img').attr('src'));

    	    	$(document.body).trigger("sticky_kit:recalc");

    	    })

	    }

	    $('#info-eskuvo .nav-list a').first().tab('show');
	    $('#info-beauty .nav-list a').first().tab('show');

	    $(document.body).trigger("sticky_kit:recalc");

	    // $('input, textarea').each(function(){
	    // 	var l = $(this).parent().find('label');
	    // 	$(this).attr('placeholder', l.text().replace(':', ''))
	    // 	l.remove();
	    // })

	    $('input, textarea').floatlabel({
			labelEndTop: -20,
			paddingOffset: 0
	    });

	    $('.datepicker').datepicker({
	    	language: "hu"
	    })

	    $('input').iCheck({
	      checkboxClass: 'icheckbox_square-blue',
	      radioClass: 'iradio_square-blue',
	      increaseArea: '20%' // optional
	    });

	});

	$(window).load(function() {

		swiper1.update();
		swiper2.update();

	});

	$(window).scroll(function(){
		if(this.scrollY > $(window).height())
			$('#top-nav').addClass('inverse')
		else
			$('#top-nav').removeClass('inverse')
	})

}(jQuery, ResponsiveBootstrapToolkit);

<|endoftext|>


<commit_before>/* Aurelia Protractor Plugin */
function addValueBindLocator() {
  by.addLocator('valueBind', function (bindingModel, opt_parentElement) {
    var using = opt_parentElement || document;
    var matches = using.querySelectorAll('*[value\\.bind="' + bindingModel +'"]');
    var result;

    if (matches.length === 0) {
      result = null;
    } else if (matches.length === 1) {
      result = matches[0];
    } else {
      result = matches;
    }

    return result;
  });
}

function loadAndWaitForAureliaPage(pageUrl) {
  browser.get(pageUrl);
  return browser.executeAsyncScript(
    'var cb = arguments[arguments.length - 1];' +
    'if (document.querySelector("[aurelia-app]")) { cb("Aurelia composed") }' +
    'document.addEventListener("aurelia-composed", function (e) {' +
    '  cb("Aurelia App composed")' +
    '}, false);'
  ).then(function(result){
    return result;
  });
}

function waitForRouterComplete() {
  return browser.executeAsyncScript(
    'var cb = arguments[arguments.length - 1];' +
    'document.querySelector("[aurelia-app]")' +
    '.aurelia.subscribeOnce("router:navigation:complete", function() {' +
    '  cb(true)' +
    '});'
  ).then(function(result){
    return result;
  });
}

/* Plugin hooks */
exports.setup = function(config) {
  // Ignore the default Angular synchronization helpers
  browser.ignoreSynchronization = true;

  // add the aurelia specific valueBind locator
  addValueBindLocator();

  // attach a new way to browser.get a page and wait for Aurelia to complete loading
  browser.loadAndWaitForAureliaPage = loadAndWaitForAureliaPage;

  // wait for router navigations to complete
  browser.waitForRouterComplete = waitForRouterComplete;
};

exports.teardown = function(config) {};
exports.postResults = function(config) {};
<commit_msg>fix(protractor): make universal for Webpack and JSPM<commit_after>/* Aurelia Protractor Plugin */
function addValueBindLocator() {
  by.addLocator('valueBind', function (bindingModel, opt_parentElement) {
    var using = opt_parentElement || document;
    var matches = using.querySelectorAll('*[value\\.bind="' + bindingModel +'"]');
    var result;

    if (matches.length === 0) {
      result = null;
    } else if (matches.length === 1) {
      result = matches[0];
    } else {
      result = matches;
    }

    return result;
  });
}

function loadAndWaitForAureliaPage(pageUrl) {
  browser.get(pageUrl);
  return browser.executeAsyncScript(
    'var cb = arguments[arguments.length - 1];' +
    'if (window.webpackJsonp && document.querySelector("[aurelia-app]")) { cb("Aurelia composed") }' +
    'document.addEventListener("aurelia-composed", function (e) {' +
    '  cb("Aurelia App composed")' +
    '}, false);'
  ).then(function(result){
    return result;
  });
}

function waitForRouterComplete() {
  return browser.executeAsyncScript(
    'var cb = arguments[arguments.length - 1];' +
    'document.querySelector("[aurelia-app]")' +
    '.aurelia.subscribeOnce("router:navigation:complete", function() {' +
    '  cb(true)' +
    '});'
  ).then(function(result){
    return result;
  });
}

/* Plugin hooks */
exports.setup = function(config) {
  // Ignore the default Angular synchronization helpers
  browser.ignoreSynchronization = true;

  // add the aurelia specific valueBind locator
  addValueBindLocator();

  // attach a new way to browser.get a page and wait for Aurelia to complete loading
  browser.loadAndWaitForAureliaPage = loadAndWaitForAureliaPage;

  // wait for router navigations to complete
  browser.waitForRouterComplete = waitForRouterComplete;
};

exports.teardown = function(config) {};
exports.postResults = function(config) {};
<|endoftext|>


<commit_before><commit_msg>Revert "feature(main) add Content-Length"<commit_after><|endoftext|>


<commit_before><commit_msg>feat: support PATCH calls<commit_after><|endoftext|>


<commit_before><commit_msg>build lib<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const {execSync} = require('child_process');
const {existsSync, readFileSync, renameSync, unlinkSync, writeFileSync} = require('fs');
const {resolve} = require('path');

/**
 * Use Yarn if available, it's much faster than the npm client.
 * Return the version of yarn installed on the system, null if yarn is not available.
 */
function getYarnVersionIfAvailable() {
    let yarnVersion;
    try {
        // execSync returns a Buffer -> convert to string
        yarnVersion = (execSync('yarn --version', {
            stdio: [0, 'pipe', 'ignore'],
        }).toString() || '').trim();
    } catch (error) {
        return null;
    }
    return yarnVersion;
}

function installDevDependencies() {
    console.log('Adding dev dependencies for the project...');

    const devDependenciesJsonPath = resolve('devDependencies.json');
    const devDependencies = JSON.parse(readFileSync(devDependenciesJsonPath));
    let depsToInstall = [];

    for (const depName in devDependencies) {
        const depVersion = devDependencies[depName];
        const depToInstall = `${depName}@${depVersion}`;
        depsToInstall.push(depToInstall);
    }

    depsToInstall = depsToInstall.join(' ');
    console.log(`Adding ${depsToInstall}...`);
    if (getYarnVersionIfAvailable()) {
        execSync(`yarn add ${depsToInstall} -D`, {stdio: 'inherit'});
    } else {
        execSync(`npm install ${depsToInstall} --save`);
    }

    console.log("Deleting devDependencies.json...");
    unlinkSync(devDependenciesJsonPath);
}

function enableWindows() {
    console.log('Enable Windows support to the project...');
    execSync(`react-native windows`);

    unlinkSync(resolve('App.windows.js'))
}

function moveAppJs() {
  const src  = resolve('App.js')
  const dest = resolve('src', 'App.js')

  if(existsSync(dest))
    unlinkSync(src)
  else
    renameSync(src, dest);
}

function updatePackageJson() {
    const fileName = "package.json";
    const file = require(resolve(fileName));

    //these are the scripts that will be added to package.json
    console.log(`Adding scripts for web to package.json`);
    Object.assign(file.scripts,
    {
      "android": "react-native run-android",
      "android:clean": "cd android && ./gradlew clean",
      "android:dev_menu": "adb shell input keyevent KEYCODE_MENU",
      "android:emulator": "scripts/android:emulator.sh",
      "android:kill_server": "fuser -k 8081/tcp || true",
      "android:log": "react-native log-android",
      "android:release": "cd android && ./gradlew assembleRelease",
      "eject": "react-scripts eject",
      "electron": "electron .",
      "ios": "react-native run-ios",
      "preandroid": "scripts/preandroid.sh",
      "preelectron": "PUBLIC_URL=. npm run web:release",
      "release": "npm run android:release && npm run web:release",
      "test:web": "react-scripts test --env=jsdom",
      "web": "react-scripts start",
      "web:release": "react-scripts build",
      "windows": "react-native run-windows"
    })

    // Electron entry point
    file.main = 'index.electron.js'

    writeFileSync(fileName, JSON.stringify(file, null, 2));
}

installDevDependencies();
enableWindows();
moveAppJs();
updatePackageJson();

// We have already installed the aditional dependencies, delete ourselves
unlinkSync(__filename);
<commit_msg>Generate release bundle for iOS (not tested)<commit_after>#!/usr/bin/env node

'use strict';

const {execSync} = require('child_process');
const {existsSync, readFileSync, renameSync, unlinkSync, writeFileSync} = require('fs');
const {resolve} = require('path');

/**
 * Use Yarn if available, it's much faster than the npm client.
 * Return the version of yarn installed on the system, null if yarn is not available.
 */
function getYarnVersionIfAvailable() {
    let yarnVersion;
    try {
        // execSync returns a Buffer -> convert to string
        yarnVersion = (execSync('yarn --version', {
            stdio: [0, 'pipe', 'ignore'],
        }).toString() || '').trim();
    } catch (error) {
        return null;
    }
    return yarnVersion;
}

function installDevDependencies() {
    console.log('Adding dev dependencies for the project...');

    const devDependenciesJsonPath = resolve('devDependencies.json');
    const devDependencies = JSON.parse(readFileSync(devDependenciesJsonPath));
    let depsToInstall = [];

    for (const depName in devDependencies) {
        const depVersion = devDependencies[depName];
        const depToInstall = `${depName}@${depVersion}`;
        depsToInstall.push(depToInstall);
    }

    depsToInstall = depsToInstall.join(' ');
    console.log(`Adding ${depsToInstall}...`);
    if (getYarnVersionIfAvailable()) {
        execSync(`yarn add ${depsToInstall} -D`, {stdio: 'inherit'});
    } else {
        execSync(`npm install ${depsToInstall} --save`);
    }

    console.log("Deleting devDependencies.json...");
    unlinkSync(devDependenciesJsonPath);
}

function enableWindows() {
    console.log('Enable Windows support to the project...');
    execSync(`react-native windows`);

    unlinkSync(resolve('App.windows.js'))
}

function moveAppJs() {
  const src  = resolve('App.js')
  const dest = resolve('src', 'App.js')

  if(existsSync(dest))
    unlinkSync(src)
  else
    renameSync(src, dest);
}

function updatePackageJson() {
    const fileName = "package.json";
    const file = require(resolve(fileName));

    //these are the scripts that will be added to package.json
    console.log(`Adding scripts for web to package.json`);
    Object.assign(file.scripts,
    {
      "android": "react-native run-android",
      "android:clean": "cd android && ./gradlew clean",
      "android:dev_menu": "adb shell input keyevent KEYCODE_MENU",
      "android:emulator": "scripts/android:emulator.sh",
      "android:kill_server": "fuser -k 8081/tcp || true",
      "android:log": "react-native log-android",
      "android:release": "cd android && ./gradlew assembleRelease",
      "eject": "react-scripts eject",
      "electron": "electron .",
      "ios": "react-native run-ios",
      "ios:release": "react-native bundle --platform=ios",
      "preandroid": "scripts/preandroid.sh",
      "preelectron": "PUBLIC_URL=. npm run web:release",
      "release": "npm run android:release && npm run web:release",
      "test:web": "react-scripts test --env=jsdom",
      "web": "react-scripts start",
      "web:release": "react-scripts build",
      "windows": "react-native run-windows"
    })

    // Electron entry point
    file.main = 'index.electron.js'

    writeFileSync(fileName, JSON.stringify(file, null, 2));
}

installDevDependencies();
enableWindows();
moveAppJs();
updatePackageJson();

// We have already installed the aditional dependencies, delete ourselves
unlinkSync(__filename);
<|endoftext|>


<commit_before>const fs = require('fs-extra'),
    request = require('request'),
    path = require('path'),
    git = require('concierge/git');

class FirstRun {
    _getJsonFile (file) {
        try {
            return this._getJson(fs.readFileSync(file, 'utf8'));
        }
        catch (e) {
            return null;
        }
    }

    _getJson (data) {
        try {
            return JSON.parse(data.replace(/^\uFEFF/, ''));
        }
        catch (e) {
            return null;
        }
    }

    _getRemoteDefaults (globalConfig) {
        return new Promise(resolve => {
            const potentialDefaultUrls = [
                globalConfig.url || null,
                this.config.url || null,
                this._getJson(process.env.CONCIERGE_DEFAULTS_URL),
                'https://raw.githubusercontent.com/wiki/concierge/Concierge/Defaults.md'
            ];
            const url = potentialDefaultUrls.find(p => !!p);
            request(url, (err, response, body) => {
                if (err) {
                    resolve(null);
                }
                else {
                    const tableArea = body.substring(body.indexOf('***') + 3, body.lastIndexOf('***')),
                        relevantArea = tableArea.substring(tableArea.indexOf('--|\n') + 4),
                        defaults = relevantArea.split(/\r?\n/)
                            .map(r => r.split('|').map(s => s.trim()).filter(s => !!s)
                            .slice(0, 2).reverse()).filter(r => r.length === 2);
                    resolve(defaults);
                }
            });
        });
    }

    _installModule (def) {
        return new Promise(resolve => {
            console.warn($$`Attempting to install module from "${def[0]}"`);
            const installPath = path.join(global.__modulesPath, def[1]);
            git.clone(def[0], installPath, err => {
                if (err) {
                    console.critical(err);
                    console.error($$`Failed to install module from "${def[0]}"`);
                }
                else {
                    console.warn($$`"${def[1]}" (${this._getJsonFile(path.join(installPath, 'kassy.json')).version}) is now installed.`);
                }
                resolve(true);
            });
        });
    }

    load (platform) {
        const globalConfig = platform.config.getSystemConfig('defaults');
        this._getRemoteDefaults(globalConfig).then(remoteDefaults => {
            const potentialDefaults = [
                this._getJsonFile(global.rootPathJoin('defaults.json')),
                globalConfig.list || null,
                this.config.list || null,
                this._getJson(process.env.CONCIERGE_DEFAULTS),
                remoteDefaults
            ];
            const defaultModules = potentialDefaults.find(p => !!p);
            if (!defaultModules) {
                LOG.error('No defaults list is available to install.');
                return;
            }
            const installPromises = [];
            for (let def of defaultModules) {
                installPromises.push(this._installModule(def));
            }
            Promise.all(installPromises).then(() => {
                platform.modulesLoader.unloadModule(this);
            });
        });
    }

    unload (platform) {
        const dir = this.__descriptor.folderPath;
        fs.remove(dir, () => {
            process.nextTick(() => platform.modulesLoader.loadAllModules());
        });
    }
}

module.exports = new FirstRun();
<commit_msg>Start integration<commit_after>const fs = require('fs-extra'),
    request = require('request'),
    path = require('path'),
    git = require('concierge/git');

class FirstRun {
    _getJsonFile (file) {
        try {
            return this._getJson(fs.readFileSync(file, 'utf8'));
        }
        catch (e) {
            return null;
        }
    }

    _getJson (data) {
        try {
            return JSON.parse(data.replace(/^\uFEFF/, ''));
        }
        catch (e) {
            return null;
        }
    }

    _getRemoteDefaults (globalConfig) {
        return new Promise(resolve => {
            const potentialDefaultUrls = [
                globalConfig.url || null,
                this.config.url || null,
                this._getJson(process.env.CONCIERGE_DEFAULTS_URL),
                'https://raw.githubusercontent.com/wiki/concierge/Concierge/Defaults.md'
            ];
            const url = potentialDefaultUrls.find(p => !!p);
            request(url, (err, response, body) => {
                if (err) {
                    resolve(null);
                }
                else {
                    const tableArea = body.substring(body.indexOf('***') + 3, body.lastIndexOf('***')),
                        relevantArea = tableArea.substring(tableArea.indexOf('--|\n') + 4),
                        defaults = relevantArea.split(/\r?\n/)
                            .map(r => r.split('|').map(s => s.trim()).filter(s => !!s)
                            .slice(0, 2).reverse()).filter(r => r.length === 2);
                    resolve(defaults);
                }
            });
        });
    }

    _installModule (def) {
        return new Promise(resolve => {
            console.warn($$`Attempting to install module from "${def[0]}"`);
            const installPath = path.join(global.__modulesPath, def[1]);
            git.clone(def[0], installPath, err => {
                if (err) {
                    console.critical(err);
                    console.error($$`Failed to install module from "${def[0]}"`);
                }
                else {
                    console.warn($$`"${def[1]}" (${this._getJsonFile(path.join(installPath, 'kassy.json')).version}) is now installed.`);
                }
                resolve(true);
            });
        });
    }

    load (platform) {
        const globalConfig = platform.config.getSystemConfig('defaults');
        this._getRemoteDefaults(globalConfig).then(remoteDefaults => {
            const potentialDefaults = [
                this._getJsonFile(global.rootPathJoin('defaults.json')),
                globalConfig.list || null,
                this.config.list || null,
                this._getJson(process.env.CONCIERGE_DEFAULTS),
                remoteDefaults
            ];
            const defaultModules = potentialDefaults.find(p => !!p);
            if (!defaultModules) {
                LOG.error('No defaults list is available to install.');
                return;
            }
            const installPromises = [];
            for (let def of defaultModules) {
                installPromises.push(this._installModule(def));
            }
            Promise.all(installPromises).then(() => {
                platform.modulesLoader.unloadModule(this);
            });
        });
    }

    unload (platform) {
        const dir = this.__descriptor.folderPath;
        fs.remove(dir, () => {
            process.nextTick(() => {
                platform.modulesLoader.loadAllModules();
                platform.modulesLoader.startIntegration(platform.onMessage, 'test');
            });
        });
    }
}

module.exports = new FirstRun();
<|endoftext|>


<commit_before>(function() {
	var root = (typeof window !== 'undefined' && window !== null) ? window : GLOBAL;

	root.$IMA = root.$IMA || {};

	root.$IMA.Loader = {
		modules: {},
		register: function(moduleName, dependencies, makeModule) {
			var self = this;
			this.modules[moduleName] = {};

			var module = makeModule(function(key, value) {
				self.modules[moduleName][key] = value;
			});

			module.setters.map(function(setter, index) {
				if (!self.modules[dependencies[index]]) {
					throw new Error('$IMA.Loader.register: Dependency ' + dependencies[index] +
							' is not registered. Update your build.js');
				}

				setter(self.modules[dependencies[index]]);
			});

			module.execute();
		},
		import: function(moduleName) {
			if (!this.modules[moduleName]) {
				throw new Error('$IMA.Loader.import: Module name ' + moduleName +
						' is not registered. Update your build.js.');
			}

			return Promise.resolve(this.modules[moduleName]);
		}
	};
})();<commit_msg>asynchronous module loader<commit_after>(function() {
	var root;
	if ((typeof window !== 'undefined') && (window !== null)) {
		root = window;
	} else {
		root = GLOBAL;
	}

	root.$IMA = root.$IMA || {};
	var modules = {};

	root.$IMA.Loader = {
		modules: modules,
		register: function (moduleName, dependencies, moduleFactory) {
			this.modules[moduleName] = {
				dependencies: dependencies,
				factory: moduleFactory,
				instance: null
			};
		},
		import: function (moduleName) {
			if (!this.modules[moduleName]) {
				throw new Error('$IMA.Loader.import: Module name ' +
						moduleName + ' is not registered. Update your ' +
						'build.js.');
			}

			return Promise.resolve(resolveModule(moduleName));
		},
		initAllModules: function () {
			Object.keys(modules).forEach(function (moduleName) {
				resolveModule(moduleName);
			});
		}
	};

	function resolveModule(moduleName, dependencyOf) {
		if (!modules[moduleName]) {
			throw new Error('$IMA.Loader.import: Module name ' +
				moduleName + (
					dependencyOf ?
						(' (dependency of ' + dependencyOf + ')') :
						''
				) + ' is not registered. Update your build.js.');
		}

		var module = modules[moduleName];
		if (module.instance) {
			return module.instance;
		}

		var moduleInstance = {};
		var moduleInitializer = module.factory(function _export(key, value) {
			moduleInstance[key] = value;
		});
		module.instance = moduleInstance; // allow lazy circular dependencies

		var dependencies = module.dependencies.map(function (dependencyName) {
			return resolveModule(dependencyName, moduleName);
		});
		dependencies.forEach(function (dependency, index) {
			moduleInitializer.setters[index](dependency);
		});

		moduleInitializer.execute();

		return moduleInstance;
	}
})();
<|endoftext|>


<commit_before>define(
    [
        'polygonjs/math/Matrix4',
        'polygonjs/math/Vector3'
    ],
    function (Matrix4, Vector3) {

        "use strict";

        var Renderer = function (opts) {
            opts = opts || {};
            this.surface = opts.surface;
            this.scene = opts.scene;
        };

        Renderer.create = function (opts) {
            return new Renderer(opts);
        };

        Renderer.prototype = {
            render: function (delta) {

                var scene = this.scene;
                var camera = scene.mainCamera;
                var cameraWorldPosition = camera.worldPosition;
                var viewTransform = camera.viewTransform;
                var projectionTransform = camera.projectionTransform;
                var models = scene.models, model;
                var polygons = scene.polygons, polygon;
                var worldVertices, worldVertex;
                var viewVertices, viewVertex;
                var screenVertices, screenVertex;
                var surface = this.surface;
                var surfaceWidth = surface.width;
                var surfaceHeight = surface.height;
                var worldNormal, viewNormal;
                var dp;
                var i, j, len;

                surface.clear();

                // Back-face cull
                i = polygons.length;
                while (--i >= 0) {
                    polygon = polygons[i];
                    dp = polygon.worldNormal.dotProduct(camera.forward);
                    polygon.isCulled = dp < 0;
                    polygon.distanceToCamera = polygon.worldPosition.distanceTo(cameraWorldPosition);
                }

                // Sort (slow!)
                // var count = 0;
                polygons.sort(function (a, b) {
                    // count++;
                    return a.distanceToCamera - b.distanceToCamera;
                });
                // console.log(count);

                // Project (view-space and clip-space)
                i = models.length, j;
                while (--i >= 0) {
                    model = models[i];
                    worldVertices = model.worldVertices;
                    viewVertices = model.viewVertices;
                    screenVertices = model.screenVertices;
                    j = worldVertices.length;
                    while (--j >= 0) {
                        worldVertex = worldVertices[j];
                        viewVertex = viewVertices[j];
                        screenVertex = screenVertices[j];

                        viewVertex.copy(worldVertex).applyProjection(viewTransform);
                        screenVertex.copy(viewVertex).applyProjection(projectionTransform);

                        // TODO: combine above?

                        screenVertex.x *= surfaceWidth;
                        screenVertex.y *= surfaceHeight;
                    }
                }

                // Render
                i = polygons.length;
                while (--i >= 0) {
                    polygon = polygons[i];
                    if (!polygon.isCulled)
                        surface.polygon(polygon.screenVertices, polygon.style);
                }

                surface.render();
            }
        };

        return Renderer;
    }
);<commit_msg>Render the polygon's material diffuse color (temp).<commit_after>define(
    [
        'polygonjs/math/Matrix4',
        'polygonjs/math/Vector3'
    ],
    function (Matrix4, Vector3) {

        "use strict";

        var Renderer = function (opts) {
            opts = opts || {};
            this.surface = opts.surface;
            this.scene = opts.scene;
        };

        Renderer.create = function (opts) {
            return new Renderer(opts);
        };

        Renderer.prototype = {
            render: function (delta) {

                var scene = this.scene;
                var camera = scene.mainCamera;
                var cameraWorldPosition = camera.worldPosition;
                var viewTransform = camera.viewTransform;
                var projectionTransform = camera.projectionTransform;
                var models = scene.models, model;
                var polygons = scene.polygons, polygon;
                var worldVertices, worldVertex;
                var viewVertices, viewVertex;
                var screenVertices, screenVertex;
                var surface = this.surface;
                var surfaceWidth = surface.width;
                var surfaceHeight = surface.height;
                var worldNormal, viewNormal;
                var dp;
                var i, j, len;

                surface.clear();

                // Back-face cull
                i = polygons.length;
                while (--i >= 0) {
                    polygon = polygons[i];
                    dp = polygon.worldNormal.dotProduct(camera.forward);
                    polygon.isCulled = dp < 0;
                    polygon.distanceToCamera = polygon.worldPosition.distanceTo(cameraWorldPosition);
                }

                // Sort (slow!)
                // var count = 0;
                polygons.sort(function (a, b) {
                    // count++;
                    return a.distanceToCamera - b.distanceToCamera;
                });
                // console.log(count);

                // Project (view-space and clip-space)
                i = models.length, j;
                while (--i >= 0) {
                    model = models[i];
                    worldVertices = model.worldVertices;
                    viewVertices = model.viewVertices;
                    screenVertices = model.screenVertices;
                    j = worldVertices.length;
                    while (--j >= 0) {
                        worldVertex = worldVertices[j];
                        viewVertex = viewVertices[j];
                        screenVertex = screenVertices[j];

                        viewVertex.copy(worldVertex).applyProjection(viewTransform);
                        screenVertex.copy(viewVertex).applyProjection(projectionTransform);

                        // TODO: combine above?

                        screenVertex.x *= surfaceWidth;
                        screenVertex.y *= surfaceHeight;
                    }
                }

                // Render
                i = polygons.length;
                while (--i >= 0) {
                    polygon = polygons[i];
                    if (!polygon.isCulled) {
                        surface.polygon(polygon.screenVertices, polygon.material.diffuse.getHex());
                    }
                }

                surface.render();
            }
        };

        return Renderer;
    }
);<|endoftext|>


<commit_before>define(function (require, exports, module) {
  'use strict';

  var Repository = app.getModule('core/Repository');
  var ProjectManager = app.getModule('engine/ProjectManager');
  var Engine = app.getModule('engine/Engine');
  var FileSystem = app.getModule('filesystem/FileSystem');
  var FileUtils = app.getModule('file/FileUtils');
  var Async = app.getModule('utils/Async');
  var UML = app.getModule('uml/UML');

  var CodeGenUtils = require('code-generator-utils');

  function RubyCodeGenerator(baseModel, basePath) {
    this.baseModel = baseModel;
    this.basePath = basePath;
  }

  RubyCodeGenerator.prototype.getIndentString = function (options) {
    if (options.useTab) {
      return '\t';
    } else {
      var indent = [];
      var length = options.indentSpaces;
      for (var i = 0; i < length; i++) {
        indent.push(' ');
      }

      return indent.join('');
    }
  };

  RubyCodeGenerator.prototype.generate = function (element, path, options) {
    var result = new $.Deferred();
    var _this = this;
    var fullPath;
    var directory;
    var codeWriter;
    var file;

    if (element instanceof type.UMLPackage) {
      fullPath = path + '/' + element.name;
      directory = FileSystem.getDirectoryForPath(fullPath);
      directory.create(function (error, stat) {
        if (!error) {
          Async.doSequentially(element.ownedElements, function (child) {
            return _this.generate(child, fullPath, options);
          }, false).then(result.resolve, result.reject);
        } else {
          result.reject(error);
        }
      });
    } else if (element instanceof type.UMLClass) {
      if (element.stereotype !== 'annotationType') {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        var moduleName = this.writePackage(codeWriter, element);
        if (moduleName) {
          this.writeDocumentation(codeWriter, element._parent.documentation, options);
          codeWriter.writeLine('module ' + moduleName);
          codeWriter.indent();
        }

        this.writeClass(codeWriter, element, options);
        if (moduleName) {
          codeWriter.outdent();
          codeWriter.writeLine('end');
        }

        fullPath = path + '/' + codeWriter.fileName(element.name) + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      }
    } else {
      result.resolve();
    }

    return result.promise();
  };

  RubyCodeGenerator.prototype.getVisibility = function (element) {
    switch (element.visibility) {
      case UML.VK_PUBLIC:
        return 'public';
      case UML.VK_PROTECTED:
        return 'protected';
      case UML.VK_PRIVATE:
        return 'private';
    }

    return null;
  };

  RubyCodeGenerator.prototype.writePackage = function (codeWriter, element) {
    var path = null;

    if (element._parent) {
      path = _.map(element._parent.getPath(this.baseModel), function (e) {
        return e.name
      }).join('.');
    }

    return path;
  };

  RubyCodeGenerator.prototype.getSuperClasses = function (element) {
    var inheritances = Repository.getRelationshipsOf(element, function (relationship) {
      return (relationship instanceof type.UMLGeneralization && relationship.source === element);
    });

    return _.map(inheritances, function (inherit) {
      return inherit.target;
    });
  };

  RubyCodeGenerator.prototype.writeDocumentation = function (codeWriter, text, options) {
    var lines;

    if (options.documentation && text.trim().length) {
      lines = text.trim().split('\n');
      if (lines > 1) {
        codeWriter.writeLine('#');
        for (var i = 0; i < lines.length; i++) {
          codeWriter.writeLine(' ' + lines[i]);
        }
      } else {
        codeWriter.writeLine('# ' + lines[0]);
      }
    }
  };

  RubyCodeGenerator.prototype.writeConstructor = function (codeWriter, element) {
    if (element.name.length) {
      var terms = [];
      var len = element.attributes.length;

      terms.push('def initialize(');
      for (var i = 0; i < len; i++) {
        if (!element.attributes[i].isStatic) {
          terms.push(element.attributes[i].name);
          if (i !== len - 1) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join('') + ')');
      codeWriter.indent();
      for (var j = 0; j < len; j++) {
        if (!element.attributes[j].isStatic) {
          codeWriter.writeLine('@' + element.attributes[j].name + ' = ' + element.attributes[j].name);
        }
      }

      codeWriter.outdent();
      codeWriter.writeLine('end');
    }
  };

  RubyCodeGenerator.prototype.writeAttributeAccessor = function (type, visibility, codeWriter, element, options) {
    var terms = [];
    var len = element.attributes.length;
    var attributeVisibility;
    var publicAttributeLastIndex;
    var protectedAttributeLastIndex;
    var privateAttributeLastIndex;

    for (var i = 0; i < len; i++) {
      attributeVisibility = this.getVisibility(element.attributes[i]);

      if (attributeVisibility === 'public') {
        publicAttributeLastIndex = i;
      } else if (attributeVisibility === 'protected') {
        protectedAttributeLastIndex = i;
      } else if (attributeVisibility === 'private') {
        privateAttributeLastIndex = i;
      }
    }

    if (type === 'short' && visibility === 'public') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public' && !element.attributes[i].isStatic) {
          this.writeDocumentation(codeWriter, element.attributes[i].documentation, options);
          terms.push(':' + element.attributes[i].name);
          if (i !== publicAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'protected') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          this.writeDocumentation(codeWriter, element.attributes[i].documentation, options);
          terms.push(':' + element.attributes[i].name);
          if (i !== protectedAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'private') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private' && !element.attributes[i].isStatic) {
          this.writeDocumentation(codeWriter, element.attributes[i].documentation, options);
          terms.push(':' + element.attributes[i].name);
          if (i !== privateAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'long' && visibility === 'public') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public' && !element.attributes[i].isStatic) {
          this.writeSetterGetterMethod(codeWriter, element.attributes[i].name);

          if (i !== publicAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'protected') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          this.writeSetterGetterMethod(codeWriter, element.attributes[i].name);

          if (i !== protectedAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'private') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private' && !element.attributes[i].isStatic) {
          this.writeSetterGetterMethod(codeWriter, element.attributes[i].name);

          if (i !== privateAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    }
  };

  RubyCodeGenerator.prototype.writeSetterGetterMethod = function (codeWriter, elementName) {
    codeWriter.writeLine('def ' + elementName);
    codeWriter.indent();
    codeWriter.writeLine('@' + elementName);
    codeWriter.outdent();
    codeWriter.writeLine('end');
    codeWriter.writeLine();
    codeWriter.writeLine('def ' + elementName + '=(value)');
    codeWriter.indent();
    codeWriter.writeLine('@' + elementName + ' = value');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  RubyCodeGenerator.prototype.writeConstant = function (codeWriter, element) {
    var len = element.attributes.length;

    for (var i = 0; i < len; i++) {
      if (element.attributes[i].isStatic) {
        codeWriter.writeLine(element.attributes[i].name + ' = ' + element.attributes[i].defaultValue);
        if (this.getVisibility(element.attributes[i]) === 'private') {
          codeWriter.writeLine('private_constant :' + element.attributes[i].name);
        }
      }
    }
  };

  RubyCodeGenerator.prototype.writeMethod = function (visibility, codeWriter, element, options) {
    var len = element.operations.length;
    var terms = [];

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var parameters = element.operations[i].getNonReturnParameters();
      var parametersLength = parameters.length;

      if (methodVisibility === visibility) {
        this.writeDocumentation(codeWriter, element.operations[i].documentation, options);
        terms.push('def ' + element.operations[i].name);
        if (parametersLength !== 0) {
          terms.push('(');
          for (var j = 0; j < parametersLength; j++) {
            terms.push(parameters[j].name);
            if (j !== parametersLength - 1) {
              terms.push(', ');
            } else {
              terms.push(')');
            }
          }
        }

        codeWriter.writeLine(terms.join(''));
        terms.length = 0;

        codeWriter.indent();
        codeWriter.writeLine('# TODO(person name): Implement this method here.');
        codeWriter.outdent();
        codeWriter.writeLine('end');
        codeWriter.writeLine();
      }
    }
  };

  RubyCodeGenerator.prototype.writeMethodByVisibility = function (codeWriter, element, options) {
    var attributeCount = this.countAttributeByVisibility(element);
    var methodCount = this.countMethodByVisibility(element);
    var protectedAttributeLength = attributeCount[1];
    var privateAttributeLength = attributeCount[2];
    var publicMethodLength = methodCount[0];
    var protectedMethodLength = methodCount[1];
    var privateMethodLength = methodCount[2];

    if (publicMethodLength) {
      codeWriter.indent();
      this.writeMethod('public', codeWriter, element, options);
      codeWriter.outdent();
    }

    if (protectedAttributeLength || protectedMethodLength) {
      codeWriter.indent();
      codeWriter.writeLine('protected');
      codeWriter.indent();
      if (protectedAttributeLength) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'protected', codeWriter, element, options);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'protected', codeWriter, element, options);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (protectedMethodLength) {
        codeWriter.indent();
        this.writeMethod('protected', codeWriter, element, options);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }

    if (privateAttributeLength || privateMethodLength) {
      codeWriter.indent();
      codeWriter.writeLine('private');
      codeWriter.indent();
      if (privateAttributeLength) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'private', codeWriter, element, options);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'private', codeWriter, element, options);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (privateMethodLength) {
        codeWriter.indent();
        this.writeMethod('private', codeWriter, element, options);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }
  };

  RubyCodeGenerator.prototype.countAttributeByVisibility = function (element) {
    var publicElementCount = 0;
    var protectedElementCount = 0;
    var privateElementCount = 0;
    var len = element.attributes.length;
    var elementVisibility;
    var attributeCount = [];

    for (var i = 0; i < len; i++) {
      elementVisibility = this.getVisibility(element.attributes[i]);

      if (elementVisibility === 'public' && !element.attributes[i].isStatic) {
        publicElementCount++;
      } else if (elementVisibility === 'protected') {
        protectedElementCount++;
      } else if (elementVisibility === 'private' && !element.attributes[i].isStatic) {
        privateElementCount++;
      }
    }

    attributeCount[0] = publicElementCount;
    attributeCount[1] = protectedElementCount;
    attributeCount[2] = privateElementCount;

    return attributeCount;
  };

  RubyCodeGenerator.prototype.countStaticAttribute = function (element) {
    var staticAttributeCount = 0;
    var len = element.attributes.length;

    for (var i = 0; i < len; i++) {
      if (element.attributes[i].isStatic) {
        staticAttributeCount++;
      }
    }

    return staticAttributeCount;
  };

  RubyCodeGenerator.prototype.countMethodByVisibility = function (element) {
    var publicMethodCount = 0;
    var protectedMethodCount = 0;
    var privateMethodCount = 0;
    var len = element.operations.length;
    var methodVisibility;
    var methodCount = [];

    for (var i = 0; i < len; i++) {
      methodVisibility = this.getVisibility(element.operations[i]);

      if (methodVisibility === 'public') {
        publicMethodCount++;
      } else if (methodVisibility === 'protected') {
        protectedMethodCount++;
      } else if (methodVisibility === 'private') {
        privateMethodCount++;
      }
    }

    methodCount[0] = publicMethodCount;
    methodCount[1] = protectedMethodCount;
    methodCount[2] = privateMethodCount;

    return methodCount;
  };

  RubyCodeGenerator.prototype.writeToStringMethod = function (codeWriter) {
    codeWriter.indent();
    codeWriter.writeLine('def to_s');
    codeWriter.indent();
    codeWriter.writeLine('\"Your string representation of the object will be written here.\"');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  RubyCodeGenerator.prototype.writeClass = function (codeWriter, element, options) {
    var terms = [];
    var staticAttributeCount = this.countStaticAttribute(element);

    this.writeDocumentation(codeWriter, element.documentation, options);
    terms.push('class');
    terms.push(element.name);

    var _inheritance = this.getSuperClasses(element);
    if (_inheritance.length) {
      terms.push('< ' + _inheritance[0].name);
    }

    codeWriter.writeLine(terms.join(' '));
    codeWriter.indent();

    var attributeCount = this.countAttributeByVisibility(element);
    var publicAttributeLength = attributeCount[0];
    if (options.useAttributeAccessor && publicAttributeLength) {
      this.writeAttributeAccessor('short', 'public', codeWriter, element, options);
      if (!staticAttributeCount) {
        codeWriter.writeLine();
      }
    }

    if (staticAttributeCount) {
      this.writeConstant(codeWriter, element);
      codeWriter.writeLine();
    }

    if (options.initializeMethod) {
      this.writeConstructor(codeWriter, element);
      codeWriter.writeLine();
    }

    if (!options.useAttributeAccessor && publicAttributeLength) {
      this.writeAttributeAccessor('long', 'public', codeWriter, element, options);
      codeWriter.writeLine();
    }

    codeWriter.outdent();
    this.writeMethodByVisibility(codeWriter, element, options);

    if (options.rubyToStringMethod) {
      this.writeToStringMethod(codeWriter);
    }

    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  function generate(baseModel, basePath, options) {
    var result = new $.Deferred();
    var rubyCodeGenerator = new RubyCodeGenerator(baseModel, basePath);

    return rubyCodeGenerator.generate(baseModel, basePath, options);
  }

  exports.generate = generate;
});
<commit_msg>Use Arrays.pop() to pop last element of an array<commit_after>define(function (require, exports, module) {
  'use strict';

  var Repository = app.getModule('core/Repository');
  var ProjectManager = app.getModule('engine/ProjectManager');
  var Engine = app.getModule('engine/Engine');
  var FileSystem = app.getModule('filesystem/FileSystem');
  var FileUtils = app.getModule('file/FileUtils');
  var Async = app.getModule('utils/Async');
  var UML = app.getModule('uml/UML');

  var CodeGenUtils = require('code-generator-utils');

  function RubyCodeGenerator(baseModel, basePath) {
    this.baseModel = baseModel;
    this.basePath = basePath;
  }

  RubyCodeGenerator.prototype.getIndentString = function (options) {
    if (options.useTab) {
      return '\t';
    } else {
      var indent = [];
      var length = options.indentSpaces;
      for (var i = 0; i < length; i++) {
        indent.push(' ');
      }

      return indent.join('');
    }
  };

  RubyCodeGenerator.prototype.generate = function (element, path, options) {
    var result = new $.Deferred();
    var _this = this;
    var fullPath;
    var directory;
    var codeWriter;
    var file;

    if (element instanceof type.UMLPackage) {
      fullPath = path + '/' + element.name;
      directory = FileSystem.getDirectoryForPath(fullPath);
      directory.create(function (error, stat) {
        if (!error) {
          Async.doSequentially(element.ownedElements, function (child) {
            return _this.generate(child, fullPath, options);
          }, false).then(result.resolve, result.reject);
        } else {
          result.reject(error);
        }
      });
    } else if (element instanceof type.UMLClass) {
      if (element.stereotype !== 'annotationType') {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        var moduleName = this.writePackage(codeWriter, element);
        if (moduleName) {
          this.writeDocumentation(codeWriter, element._parent.documentation, options);
          codeWriter.writeLine('module ' + moduleName);
          codeWriter.indent();
        }

        this.writeClass(codeWriter, element, options);
        if (moduleName) {
          codeWriter.outdent();
          codeWriter.writeLine('end');
        }

        fullPath = path + '/' + codeWriter.fileName(element.name) + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      }
    } else {
      result.resolve();
    }

    return result.promise();
  };

  RubyCodeGenerator.prototype.getVisibility = function (element) {
    switch (element.visibility) {
      case UML.VK_PUBLIC:
        return 'public';
      case UML.VK_PROTECTED:
        return 'protected';
      case UML.VK_PRIVATE:
        return 'private';
    }

    return null;
  };

  RubyCodeGenerator.prototype.writePackage = function (codeWriter, element) {
    var path = null;

    if (element._parent) {
      path = _.map(element._parent.getPath(this.baseModel), function (e) {
        return e.name
      }).join('.');
    }

    return path;
  };

  RubyCodeGenerator.prototype.getSuperClasses = function (element) {
    var inheritances = Repository.getRelationshipsOf(element, function (relationship) {
      return (relationship instanceof type.UMLGeneralization && relationship.source === element);
    });

    return _.map(inheritances, function (inherit) {
      return inherit.target;
    });
  };

  RubyCodeGenerator.prototype.writeDocumentation = function (codeWriter, text, options) {
    var lines;

    if (options.documentation && text.trim().length) {
      lines = text.trim().split('\n');
      if (lines > 1) {
        codeWriter.writeLine('#');
        for (var i = 0; i < lines.length; i++) {
          codeWriter.writeLine(' ' + lines[i]);
        }
      } else {
        codeWriter.writeLine('# ' + lines[0]);
      }
    }
  };

  RubyCodeGenerator.prototype.writeConstructor = function (codeWriter, element) {
    if (element.name.length) {
      var terms = [];
      var len = element.attributes.length;

      terms.push('def initialize(');
      for (var i = 0; i < len; i++) {
        if (!element.attributes[i].isStatic) {
          terms.push(element.attributes[i].name);
          terms.push(', ');
        }
      }

      if (terms.length > 1) {
        terms.pop();
      }

      codeWriter.writeLine(terms.join('') + ')');
      codeWriter.indent();
      for (var j = 0; j < len; j++) {
        if (!element.attributes[j].isStatic) {
          codeWriter.writeLine('@' + element.attributes[j].name + ' = ' + element.attributes[j].name);
        }
      }

      codeWriter.outdent();
      codeWriter.writeLine('end');
    }
  };

  RubyCodeGenerator.prototype.writeAttributeAccessor = function (type, visibility, codeWriter, element, options) {
    var terms = [];
    var len = element.attributes.length;
    var attributeVisibility;
    var publicAttributeLastIndex;
    var protectedAttributeLastIndex;
    var privateAttributeLastIndex;

    for (var i = 0; i < len; i++) {
      attributeVisibility = this.getVisibility(element.attributes[i]);

      if (attributeVisibility === 'public') {
        publicAttributeLastIndex = i;
      } else if (attributeVisibility === 'protected') {
        protectedAttributeLastIndex = i;
      } else if (attributeVisibility === 'private') {
        privateAttributeLastIndex = i;
      }
    }

    if (type === 'short' && visibility === 'public') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public' && !element.attributes[i].isStatic) {
          this.writeDocumentation(codeWriter, element.attributes[i].documentation, options);
          terms.push(':' + element.attributes[i].name);
          terms.push(', ');
        }
      }

      if (terms.length > 1) {
        terms.pop();
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'protected') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          this.writeDocumentation(codeWriter, element.attributes[i].documentation, options);
          terms.push(':' + element.attributes[i].name);
          terms.push(', ');
        }
      }

      if (terms.length > 1) {
        terms.pop();
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'private') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private' && !element.attributes[i].isStatic) {
          this.writeDocumentation(codeWriter, element.attributes[i].documentation, options);
          terms.push(':' + element.attributes[i].name);
          terms.push(', ');
        }
      }

      if (terms.length > 1) {
        terms.pop();
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'long' && visibility === 'public') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public' && !element.attributes[i].isStatic) {
          this.writeSetterGetterMethod(codeWriter, element.attributes[i].name);

          if (i !== publicAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'protected') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          this.writeSetterGetterMethod(codeWriter, element.attributes[i].name);

          if (i !== protectedAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'private') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private' && !element.attributes[i].isStatic) {
          this.writeSetterGetterMethod(codeWriter, element.attributes[i].name);

          if (i !== privateAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    }
  };

  RubyCodeGenerator.prototype.writeSetterGetterMethod = function (codeWriter, elementName) {
    codeWriter.writeLine('def ' + elementName);
    codeWriter.indent();
    codeWriter.writeLine('@' + elementName);
    codeWriter.outdent();
    codeWriter.writeLine('end');
    codeWriter.writeLine();
    codeWriter.writeLine('def ' + elementName + '=(value)');
    codeWriter.indent();
    codeWriter.writeLine('@' + elementName + ' = value');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  RubyCodeGenerator.prototype.writeConstant = function (codeWriter, element) {
    var len = element.attributes.length;

    for (var i = 0; i < len; i++) {
      if (element.attributes[i].isStatic) {
        codeWriter.writeLine(element.attributes[i].name + ' = ' + element.attributes[i].defaultValue);
        if (this.getVisibility(element.attributes[i]) === 'private') {
          codeWriter.writeLine('private_constant :' + element.attributes[i].name);
        }
      }
    }
  };

  RubyCodeGenerator.prototype.writeMethod = function (visibility, codeWriter, element, options) {
    var len = element.operations.length;
    var terms = [];

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var parameters = element.operations[i].getNonReturnParameters();
      var parametersLength = parameters.length;

      if (methodVisibility === visibility) {
        this.writeDocumentation(codeWriter, element.operations[i].documentation, options);
        terms.push('def ' + element.operations[i].name);
        if (parametersLength !== 0) {
          terms.push('(');
          for (var j = 0; j < parametersLength; j++) {
            terms.push(parameters[j].name);
            if (j !== parametersLength - 1) {
              terms.push(', ');
            } else {
              terms.push(')');
            }
          }
        }

        codeWriter.writeLine(terms.join(''));
        terms.length = 0;

        codeWriter.indent();
        codeWriter.writeLine('# TODO(person name): Implement this method here.');
        codeWriter.outdent();
        codeWriter.writeLine('end');
        codeWriter.writeLine();
      }
    }
  };

  RubyCodeGenerator.prototype.writeMethodByVisibility = function (codeWriter, element, options) {
    var attributeCount = this.countAttributeByVisibility(element);
    var methodCount = this.countMethodByVisibility(element);
    var protectedAttributeLength = attributeCount[1];
    var privateAttributeLength = attributeCount[2];
    var publicMethodLength = methodCount[0];
    var protectedMethodLength = methodCount[1];
    var privateMethodLength = methodCount[2];

    if (publicMethodLength) {
      codeWriter.indent();
      this.writeMethod('public', codeWriter, element, options);
      codeWriter.outdent();
    }

    if (protectedAttributeLength || protectedMethodLength) {
      codeWriter.indent();
      codeWriter.writeLine('protected');
      codeWriter.indent();
      if (protectedAttributeLength) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'protected', codeWriter, element, options);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'protected', codeWriter, element, options);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (protectedMethodLength) {
        codeWriter.indent();
        this.writeMethod('protected', codeWriter, element, options);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }

    if (privateAttributeLength || privateMethodLength) {
      codeWriter.indent();
      codeWriter.writeLine('private');
      codeWriter.indent();
      if (privateAttributeLength) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'private', codeWriter, element, options);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'private', codeWriter, element, options);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (privateMethodLength) {
        codeWriter.indent();
        this.writeMethod('private', codeWriter, element, options);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }
  };

  RubyCodeGenerator.prototype.countAttributeByVisibility = function (element) {
    var publicElementCount = 0;
    var protectedElementCount = 0;
    var privateElementCount = 0;
    var len = element.attributes.length;
    var elementVisibility;
    var attributeCount = [];

    for (var i = 0; i < len; i++) {
      elementVisibility = this.getVisibility(element.attributes[i]);

      if (elementVisibility === 'public' && !element.attributes[i].isStatic) {
        publicElementCount++;
      } else if (elementVisibility === 'protected') {
        protectedElementCount++;
      } else if (elementVisibility === 'private' && !element.attributes[i].isStatic) {
        privateElementCount++;
      }
    }

    attributeCount[0] = publicElementCount;
    attributeCount[1] = protectedElementCount;
    attributeCount[2] = privateElementCount;

    return attributeCount;
  };

  RubyCodeGenerator.prototype.countStaticAttribute = function (element) {
    var staticAttributeCount = 0;
    var len = element.attributes.length;

    for (var i = 0; i < len; i++) {
      if (element.attributes[i].isStatic) {
        staticAttributeCount++;
      }
    }

    return staticAttributeCount;
  };

  RubyCodeGenerator.prototype.countMethodByVisibility = function (element) {
    var publicMethodCount = 0;
    var protectedMethodCount = 0;
    var privateMethodCount = 0;
    var len = element.operations.length;
    var methodVisibility;
    var methodCount = [];

    for (var i = 0; i < len; i++) {
      methodVisibility = this.getVisibility(element.operations[i]);

      if (methodVisibility === 'public') {
        publicMethodCount++;
      } else if (methodVisibility === 'protected') {
        protectedMethodCount++;
      } else if (methodVisibility === 'private') {
        privateMethodCount++;
      }
    }

    methodCount[0] = publicMethodCount;
    methodCount[1] = protectedMethodCount;
    methodCount[2] = privateMethodCount;

    return methodCount;
  };

  RubyCodeGenerator.prototype.writeToStringMethod = function (codeWriter) {
    codeWriter.indent();
    codeWriter.writeLine('def to_s');
    codeWriter.indent();
    codeWriter.writeLine('\"Your string representation of the object will be written here.\"');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  RubyCodeGenerator.prototype.writeClass = function (codeWriter, element, options) {
    var terms = [];
    var staticAttributeCount = this.countStaticAttribute(element);

    this.writeDocumentation(codeWriter, element.documentation, options);
    terms.push('class');
    terms.push(element.name);

    var _inheritance = this.getSuperClasses(element);
    if (_inheritance.length) {
      terms.push('< ' + _inheritance[0].name);
    }

    codeWriter.writeLine(terms.join(' '));
    codeWriter.indent();

    var attributeCount = this.countAttributeByVisibility(element);
    var publicAttributeLength = attributeCount[0];
    if (options.useAttributeAccessor && publicAttributeLength) {
      this.writeAttributeAccessor('short', 'public', codeWriter, element, options);
      if (!staticAttributeCount) {
        codeWriter.writeLine();
      }
    }

    if (staticAttributeCount) {
      this.writeConstant(codeWriter, element);
      codeWriter.writeLine();
    }

    if (options.initializeMethod) {
      this.writeConstructor(codeWriter, element);
      codeWriter.writeLine();
    }

    if (!options.useAttributeAccessor && publicAttributeLength) {
      this.writeAttributeAccessor('long', 'public', codeWriter, element, options);
      codeWriter.writeLine();
    }

    codeWriter.outdent();
    this.writeMethodByVisibility(codeWriter, element, options);

    if (options.rubyToStringMethod) {
      this.writeToStringMethod(codeWriter);
    }

    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  function generate(baseModel, basePath, options) {
    var result = new $.Deferred();
    var rubyCodeGenerator = new RubyCodeGenerator(baseModel, basePath);

    return rubyCodeGenerator.generate(baseModel, basePath, options);
  }

  exports.generate = generate;
});
<|endoftext|>


<commit_before>// convert mongo db object style to middle style used by plist.js
var when = require('when');

var g_flow;
var plistMapper = {
    "choicesscreen": {name: "Choice", type: "String"},
    "InfoScreen": {name: "Info", type: "String"},
    "type": {name: "ScreenType", type: "String"},
    "choices": {name: "choices", type: "Array"},
    "t": {name: "ChoiceText", type: "String"},
    "wi": {name: "ScreenName", type: "String"},
    "wt": {name: "ChoiceType", type: "String"},
    "screen_name": {name: "ScreenTitle", type: "String"},
    "screen_content": {name: "ContentText", type: "String"}
};

function getNodeWithId(_id) {//get first one , id attribute doesn't duplicate
    return g_flow.Nodes.filter(function (node) {
        return (_id && node.hasOwnProperty('id') && node.id == _id);
    })[0];
}

function mapElement(that) {
    var rObj = {};
    for (var k in that) {
        if (that.hasOwnProperty(k) && plistMapper.hasOwnProperty(k)) {
            if (plistMapper[k].name == 'choices') {
                rObj[plistMapper[k].name] = that.choices.map(mapElement);
                rObj[plistMapper[k].name].forEach(function (choice, index) {
                    choice.ScreenName = that.wires[index][0];
                    choice.ChoiceType = plistMapper[getNodeWithId(choice.ScreenName).type].name;
                });
            } else {
                rObj[plistMapper[k].name] = k == 'type' ? plistMapper[that[k]].name : that[k];
            }
        }
    }
    return rObj;
}

module.exports = {
    extractFlow: function (flow) {
        return when.promise(function (resolve) {
            try {
                //remove unnecessary parts from mongo db object
                var _flow = JSON.parse(JSON.stringify(flow, function (key, value) {
                    return key !== '_id' && key !== '__v' && key !== 'created' && key !== 'deploy' ? value : undefined;
                }));

                var __flow = {};
                g_flow = _flow;
                __flow.key = _flow.key;
                __flow.Version = _flow.version;

                var startId = _flow.Nodes.filter(function (node) {
                    // TODO : if it has no start point through exception
                    return (node.hasOwnProperty('type') && node.type == 'start');
                })[0].wires[0][0];
                var initial = getNodeWithId(startId);
                var rest_of_flow = _flow.Nodes.filter(function (node) {
                    return (node.type != 'start' && node.type != 'tab');
                });
                __flow.Initial = plistMapper[initial.type].name;
                __flow.MainScreen = [initial].map(mapElement)[0];
                rest_of_flow.forEach(function (node) {
                    __flow[node.id] = mapElement(node);
                });
            } catch (ex) {
                resolve([]);
            }
            resolve(__flow);
        });
    }
}<commit_msg>add choice type to Choices<commit_after>// convert mongo db object style to middle style used by plist.js
var when = require('when');

var g_flow;
var plistMapper = {
    "choicesscreen": {name: "Choice", type: "String"},
    "InfoScreen": {name: "Info", type: "String"},
    "type": {name: "ScreenType", type: "String"},
    "choices": {name: "choices", type: "Array"},
    "t": {name: "ChoiceText", type: "String"},
    "wi": {name: "ScreenName", type: "String"},
    "wt": {name: "ChoiceType", type: "String"},
    "screen_name": {name: "ScreenTitle", type: "String"},
    "screen_content": {name: "ContentText", type: "String"}
};

function getNodeWithId(_id) {//get first one , id attribute doesn't duplicate
    return g_flow.Nodes.filter(function (node) {
        return (_id && node.hasOwnProperty('id') && node.id == _id);
    })[0];
}

function mapElement(that) {
    var rObj = {};
    for (var k in that) {
        if (that.hasOwnProperty(k) && plistMapper.hasOwnProperty(k)) {
            if (plistMapper[k].name == 'choices') {
                rObj[plistMapper[k].name] = that.choices.map(mapElement);
                rObj[plistMapper[k].name].forEach(function (choice, index) {
                    choice.ScreenName = that.wires[index][0];
                    choice.ChoiceType = plistMapper[getNodeWithId(that.wires[index][0]).type].name;
                });
            } else {
                rObj[plistMapper[k].name] = k == 'type' ? plistMapper[that[k]].name : that[k];
            }
        }
    }
    return rObj;
}

module.exports = {
    extractFlow: function (flow) {
        return when.promise(function (resolve) {
            try {
                //remove unnecessary parts from mongo db object
                var _flow = JSON.parse(JSON.stringify(flow, function (key, value) {
                    return key !== '_id' && key !== '__v' && key !== 'created' && key !== 'deploy' ? value : undefined;
                }));

                var __flow = {};
                g_flow = _flow;
                __flow.key = _flow.key;
                __flow.Version = _flow.version;

                var startId = _flow.Nodes.filter(function (node) {
                    // TODO : if it has no start point through exception
                    return (node.hasOwnProperty('type') && node.type == 'start');
                })[0].wires[0][0];
                var initial = getNodeWithId(startId);
                var rest_of_flow = _flow.Nodes.filter(function (node) {
                    return (node.type != 'start' && node.type != 'tab');
                });
                __flow.Initial = plistMapper[initial.type].name;
                __flow.MainScreen = [initial].map(mapElement)[0];
                rest_of_flow.forEach(function (node) {
                    __flow[node.id] = mapElement(node);
                });
            } catch (ex) {
                resolve([]);
            }
            resolve(__flow);
        });
    }
}<|endoftext|>