<commit_before>var customEvent = require('@grid/custom-event');
var debounce = require('@grid/debounce');
var util = require('@grid/util');

module.exports = function (_grid) {
    var viewLayer = {};

    var grid = _grid;
    var container;
    var root;
    var cellContainer;
    var decoratorContainer;
    var borderWidth;

    var GRID_CELL_CONTAINER_BASE_CLASS = 'grid-cells';
    var GRID_VIEW_ROOT_CLASS = 'js-grid-view-root';
    var CELL_CLASS = 'grid-cell';

    var cells; //matrix of rendered cell elements;
    var rows; //array of all rendered rows

    //add the cell classes through the standard way

    grid.cellClasses.add(grid.cellClasses.create(0, 0, CELL_CLASS, Infinity, Infinity));

    viewLayer.build = function (elem) {
        container = elem;

        cleanup();
        cellContainer = document.createElement('div');
        cellContainer.setAttribute('dts', 'grid-cells');
        cellContainer.setAttribute('class', GRID_CELL_CONTAINER_BASE_CLASS);
        util.position(cellContainer, 0, 0, 0, 0);
        cellContainer.style.zIndex = 0;

        decoratorContainer = document.createElement('div');
        decoratorContainer.setAttribute('dts', 'grid-decorators');
        util.position(decoratorContainer, 0, 0, 0, 0);
        decoratorContainer.style.zIndex = 0;
        decoratorContainer.style.pointerEvents = 'none';

        root = document.createElement('div');
        root.setAttribute('class', GRID_VIEW_ROOT_CLASS);

        root.appendChild(cellContainer);
        root.appendChild(decoratorContainer);

        container.appendChild(root);

    };

    function measureBorderWidth() {
        //read the border width, for the rare case of larger than 1px borders, otherwise the draw will default to 1
        if (borderWidth) {
            return;
        }
        var jsGridCell = cells[0] && cells[0][0];
        if (jsGridCell) {
            var oldClass = jsGridCell.className;
            jsGridCell.className = CELL_CLASS;
            var computedStyle = getComputedStyle(jsGridCell);
            var borderWidthProp = computedStyle.getPropertyValue('border-left-width');
            borderWidth = parseInt(borderWidthProp);
            jsGridCell.className = oldClass;
        }
        borderWidth = isNaN(borderWidth) || !borderWidth ? undefined : borderWidth;
        return borderWidth;
    }

    //only draw once per js turn, may need to create a synchronous version
    viewLayer.draw = debounce(function () {
        //return if we haven't built yet
        if (!container) {
            return;
        }
        var viewPortDirty = grid.viewPort.isDirty();
        if (viewPortDirty) {
            viewLayer._buildCells(cellContainer);
        }
        var colModelDirty = grid.colModel.isDirty();
        var cellScrollDirty = grid.cellScrollModel.isDirty();
        var cellsPositionOrSizeChanged = colModelDirty || cellScrollDirty;

        if (viewPortDirty || grid.cellClasses.isDirty() || cellsPositionOrSizeChanged) {
            viewLayer._drawCellClasses();
        }

        if (viewPortDirty || cellsPositionOrSizeChanged) {
            viewLayer._drawCells();
        }

        if (grid.decorators.isDirty() || viewPortDirty || cellsPositionOrSizeChanged) {
            viewLayer._drawDecorators(cellsPositionOrSizeChanged);
        }

        grid.eventLoop.fire('grid-draw');
    }, 1);

    /* CELL LOGIC */
    function getBorderWidth() {
        return borderWidth || 1;
    }

    viewLayer._drawCells = function () {
        measureBorderWidth()
        var bWidth = getBorderWidth();
        grid.viewPort.iterateCells(function drawCell(r, c) {
            var cell = cells[r][c];
            var width = grid.viewPort.getColWidth(c);
            cell.style.width = width + bWidth + 'px';

            var left = grid.viewPort.getColLeft(c);
            cell.style.left = left + 'px';

            while (cell.firstChild) {
                cell.removeChild(cell.firstChild);
            }
            var virtualRow = grid.viewPort.toVirtualRow(r);
            var virtualCol = grid.viewPort.toVirtualCol(c);
            var formattedData = grid.dataModel.getFormatted(virtualRow, virtualCol);
            cell.appendChild(document.createTextNode(formattedData));
        }, function drawRow(r) {
            var height = grid.viewPort.getRowHeight(r); //maybe faster to do this only on row iterations but meh
            var row = rows[r];
            row.style.height = height + bWidth + 'px';
            var top = grid.viewPort.getRowTop(r);
            row.style.top = top + 'px';
        });

        if (grid.cellScrollModel.row % 2) {
            cellContainer.className = GRID_CELL_CONTAINER_BASE_CLASS + ' odds';
        } else {
            cellContainer.className = GRID_CELL_CONTAINER_BASE_CLASS;
        }
    };

    function buildCells(cellContainer) {
        while (cellContainer.firstChild) {
            cellContainer.removeChild(cellContainer.firstChild);
        }

        cells = [];
        rows = [];
        var row;
        grid.viewPort.iterateCells(function (r, c) {
            var cell = buildDivCell();
            cells[r][c] = cell;
            row.appendChild(cell);
        }, function (r) {
            cells[r] = [];
            row = document.createElement('div');
            row.setAttribute('class', 'grid-row');
            row.setAttribute('dts', 'grid-row');
            row.style.position = 'absolute';
            row.style.left = 0;
            row.style.right = 0;
            rows[r] = row;
            cellContainer.appendChild(row);
        });
    }

    viewLayer._buildCells = buildCells;

    function buildDivCell() {
        var cell = document.createElement('div');
        cell.setAttribute('dts', 'grid-cell');
        var style = cell.style;
        style.position = 'absolute';
        style.boxSizing = 'border-box';
        style.top = '0px';
        style.bottom = '0px';
        return cell;
    }

    /* END CELL LOGIC */

    /* DECORATOR LOGIC */
    function setPosition(boundingBox, top, left, height, width) {
        var style = boundingBox.style;
        style.top = top + 'px';
        style.left = left + 'px';
        style.height = height + 'px';
        style.width = width + 'px';
        style.position = 'absolute';
    }

    function positionDecorator(bounding, t, l, h, w) {
        setPosition(bounding, t, l, util.clamp(h, 0, grid.viewPort.height), util.clamp(w, 0, grid.viewPort.width));
    }

    function positionCellDecoratorFromRealCellRange(realCellRange, boundingBox) {
        var realPxRange = grid.viewPort.toPx(realCellRange);
        positionDecorator(boundingBox, realPxRange.top, realPxRange.left, realPxRange.height + getBorderWidth(), realPxRange.width + getBorderWidth());
    }

    viewLayer._drawDecorators = function (cellsPositionOrSizeChanged) {
        var aliveDecorators = grid.decorators.getAlive();
        aliveDecorators.forEach(function (decorator) {

            var boundingBox = decorator.boundingBox;
            if (!boundingBox) {
                boundingBox = document.createElement('div');
                boundingBox.style.pointerEvents = 'none';
                decorator.boundingBox = boundingBox;
                var decElement = decorator.render();
                if (decElement) {
                    boundingBox.appendChild(decElement);
                    decoratorContainer.appendChild(boundingBox);
                }
            }

            if ((decorator.isDirty() || cellsPositionOrSizeChanged) && decorator.space === 'real') {
                switch (decorator.units) {
                    case 'px':
                        positionDecorator(boundingBox, decorator.top, decorator.left, decorator.height, decorator.width);
                        break;
                    case 'cell':
                        positionCellDecoratorFromRealCellRange(decorator, boundingBox);
                        break;
                }
            } else if ((decorator.isDirty() || cellsPositionOrSizeChanged) && decorator.space === 'virtual') {
                switch (decorator.units) {
                    case 'px':
                        break;
                    case 'cell':
                    /* jshint -W086 */
                    default:
                        var realCellRange = grid.viewPort.intersect(decorator);
                        if (realCellRange) {
                            positionCellDecoratorFromRealCellRange(realCellRange, boundingBox);
                        } else {
                            positionDecorator(boundingBox, -1, -1, -1, -1);
                        }
                        break;
                    /* jshint +W086 */
                }

            }
        });

        removeDecorators(grid.decorators.popAllDead());
    }

    function removeDecorators(decorators) {
        decorators.forEach(function (decorator) {
            var boundingBox = decorator.boundingBox;
            if (boundingBox) {
                //if they rendered an element previously we attached it to the bounding box as the only child
                var renderedElement = boundingBox.firstChild;
                if (renderedElement) {
                    //create a destroy dom event that bubbles
                    var destroyEvent = customEvent('decorator-destroy', true);
                    renderedElement.dispatchEvent(destroyEvent);
                }
                decoratorContainer.removeChild(boundingBox);
                decorator.boundingBox = undefined;
            }
        });
    }

    /* END DECORATOR LOGIC */

    /* CELL CLASSES LOGIC */
    viewLayer._drawCellClasses = function () {
        grid.viewPort.iterateCells(function (r, c) {
            cells[r][c].className = '';
        });
        grid.cellClasses.getAll().forEach(function (descriptor) {
            var intersection = grid.viewPort.intersect(descriptor);
            if (intersection) {
                rowloop:
                    for (var r = 0; r < intersection.height; r++) {
                        for (var c = 0; c < intersection.width; c++) {
                            var row = intersection.top + r;
                            var col = intersection.left + c;

                            var cellRow = cells[row];
                            if (!cellRow) {
                                continue rowloop;
                            }
                            var cell = cellRow[col];
                            if (!cell) {
                                continue;
                            }
                            cell.className = (cell.className ? cell.className + ' ' : '') + descriptor.class;
                        }
                    }
            }
        });
    }

    /* END CELL CLASSES LOGIC*/

    viewLayer.destroy = cleanup;

    function cleanup() {
        removeDecorators(grid.decorators.getAlive().concat(grid.decorators.popAllDead()));
        if (!container) {
            return;
        }
        var querySelectorAll = container.querySelectorAll('.' + GRID_VIEW_ROOT_CLASS);
        for (var i = 0; i < querySelectorAll.length; ++i) {
            var root = querySelectorAll[i];
            container.removeChild(root);
        }
    }

    grid.eventLoop.bind('grid-destroy', function () {
        viewLayer.destroy();
        clearTimeout(viewLayer.draw.timeout);
    });

    return viewLayer;
};<commit_msg>jshint<commit_after>var customEvent = require('@grid/custom-event');
var debounce = require('@grid/debounce');
var util = require('@grid/util');

module.exports = function (_grid) {
    var viewLayer = {};

    var grid = _grid;
    var container;
    var root;
    var cellContainer;
    var decoratorContainer;
    var borderWidth;

    var GRID_CELL_CONTAINER_BASE_CLASS = 'grid-cells';
    var GRID_VIEW_ROOT_CLASS = 'js-grid-view-root';
    var CELL_CLASS = 'grid-cell';

    var cells; //matrix of rendered cell elements;
    var rows; //array of all rendered rows

    //add the cell classes through the standard way

    grid.cellClasses.add(grid.cellClasses.create(0, 0, CELL_CLASS, Infinity, Infinity));

    viewLayer.build = function (elem) {
        container = elem;

        cleanup();
        cellContainer = document.createElement('div');
        cellContainer.setAttribute('dts', 'grid-cells');
        cellContainer.setAttribute('class', GRID_CELL_CONTAINER_BASE_CLASS);
        util.position(cellContainer, 0, 0, 0, 0);
        cellContainer.style.zIndex = 0;

        decoratorContainer = document.createElement('div');
        decoratorContainer.setAttribute('dts', 'grid-decorators');
        util.position(decoratorContainer, 0, 0, 0, 0);
        decoratorContainer.style.zIndex = 0;
        decoratorContainer.style.pointerEvents = 'none';

        root = document.createElement('div');
        root.setAttribute('class', GRID_VIEW_ROOT_CLASS);

        root.appendChild(cellContainer);
        root.appendChild(decoratorContainer);

        container.appendChild(root);

    };

    function measureBorderWidth() {
        //read the border width, for the rare case of larger than 1px borders, otherwise the draw will default to 1
        if (borderWidth) {
            return;
        }
        var jsGridCell = cells[0] && cells[0][0];
        if (jsGridCell) {
            var oldClass = jsGridCell.className;
            jsGridCell.className = CELL_CLASS;
            var computedStyle = getComputedStyle(jsGridCell);
            var borderWidthProp = computedStyle.getPropertyValue('border-left-width');
            borderWidth = parseInt(borderWidthProp);
            jsGridCell.className = oldClass;
        }
        borderWidth = isNaN(borderWidth) || !borderWidth ? undefined : borderWidth;
        return borderWidth;
    }

    //only draw once per js turn, may need to create a synchronous version
    viewLayer.draw = debounce(function () {
        //return if we haven't built yet
        if (!container) {
            return;
        }
        var viewPortDirty = grid.viewPort.isDirty();
        if (viewPortDirty) {
            viewLayer._buildCells(cellContainer);
        }
        var colModelDirty = grid.colModel.isDirty();
        var cellScrollDirty = grid.cellScrollModel.isDirty();
        var cellsPositionOrSizeChanged = colModelDirty || cellScrollDirty;

        if (viewPortDirty || grid.cellClasses.isDirty() || cellsPositionOrSizeChanged) {
            viewLayer._drawCellClasses();
        }

        if (viewPortDirty || cellsPositionOrSizeChanged) {
            viewLayer._drawCells();
        }

        if (grid.decorators.isDirty() || viewPortDirty || cellsPositionOrSizeChanged) {
            viewLayer._drawDecorators(cellsPositionOrSizeChanged);
        }

        grid.eventLoop.fire('grid-draw');
    }, 1);

    /* CELL LOGIC */
    function getBorderWidth() {
        return borderWidth || 1;
    }

    viewLayer._drawCells = function () {
        measureBorderWidth();
        var bWidth = getBorderWidth();
        grid.viewPort.iterateCells(function drawCell(r, c) {
            var cell = cells[r][c];
            var width = grid.viewPort.getColWidth(c);
            cell.style.width = width + bWidth + 'px';

            var left = grid.viewPort.getColLeft(c);
            cell.style.left = left + 'px';

            while (cell.firstChild) {
                cell.removeChild(cell.firstChild);
            }
            var virtualRow = grid.viewPort.toVirtualRow(r);
            var virtualCol = grid.viewPort.toVirtualCol(c);
            var formattedData = grid.dataModel.getFormatted(virtualRow, virtualCol);
            cell.appendChild(document.createTextNode(formattedData));
        }, function drawRow(r) {
            var height = grid.viewPort.getRowHeight(r); //maybe faster to do this only on row iterations but meh
            var row = rows[r];
            row.style.height = height + bWidth + 'px';
            var top = grid.viewPort.getRowTop(r);
            row.style.top = top + 'px';
        });

        if (grid.cellScrollModel.row % 2) {
            cellContainer.className = GRID_CELL_CONTAINER_BASE_CLASS + ' odds';
        } else {
            cellContainer.className = GRID_CELL_CONTAINER_BASE_CLASS;
        }
    };

    function buildCells(cellContainer) {
        while (cellContainer.firstChild) {
            cellContainer.removeChild(cellContainer.firstChild);
        }

        cells = [];
        rows = [];
        var row;
        grid.viewPort.iterateCells(function (r, c) {
            var cell = buildDivCell();
            cells[r][c] = cell;
            row.appendChild(cell);
        }, function (r) {
            cells[r] = [];
            row = document.createElement('div');
            row.setAttribute('class', 'grid-row');
            row.setAttribute('dts', 'grid-row');
            row.style.position = 'absolute';
            row.style.left = 0;
            row.style.right = 0;
            rows[r] = row;
            cellContainer.appendChild(row);
        });
    }

    viewLayer._buildCells = buildCells;

    function buildDivCell() {
        var cell = document.createElement('div');
        cell.setAttribute('dts', 'grid-cell');
        var style = cell.style;
        style.position = 'absolute';
        style.boxSizing = 'border-box';
        style.top = '0px';
        style.bottom = '0px';
        return cell;
    }

    /* END CELL LOGIC */

    /* DECORATOR LOGIC */
    function setPosition(boundingBox, top, left, height, width) {
        var style = boundingBox.style;
        style.top = top + 'px';
        style.left = left + 'px';
        style.height = height + 'px';
        style.width = width + 'px';
        style.position = 'absolute';
    }

    function positionDecorator(bounding, t, l, h, w) {
        setPosition(bounding, t, l, util.clamp(h, 0, grid.viewPort.height), util.clamp(w, 0, grid.viewPort.width));
    }

    function positionCellDecoratorFromRealCellRange(realCellRange, boundingBox) {
        var realPxRange = grid.viewPort.toPx(realCellRange);
        positionDecorator(boundingBox, realPxRange.top, realPxRange.left, realPxRange.height + getBorderWidth(), realPxRange.width + getBorderWidth());
    }

    viewLayer._drawDecorators = function (cellsPositionOrSizeChanged) {
        var aliveDecorators = grid.decorators.getAlive();
        aliveDecorators.forEach(function (decorator) {

            var boundingBox = decorator.boundingBox;
            if (!boundingBox) {
                boundingBox = document.createElement('div');
                boundingBox.style.pointerEvents = 'none';
                decorator.boundingBox = boundingBox;
                var decElement = decorator.render();
                if (decElement) {
                    boundingBox.appendChild(decElement);
                    decoratorContainer.appendChild(boundingBox);
                }
            }

            if ((decorator.isDirty() || cellsPositionOrSizeChanged) && decorator.space === 'real') {
                switch (decorator.units) {
                    case 'px':
                        positionDecorator(boundingBox, decorator.top, decorator.left, decorator.height, decorator.width);
                        break;
                    case 'cell':
                        positionCellDecoratorFromRealCellRange(decorator, boundingBox);
                        break;
                }
            } else if ((decorator.isDirty() || cellsPositionOrSizeChanged) && decorator.space === 'virtual') {
                switch (decorator.units) {
                    case 'px':
                        break;
                    case 'cell':
                    /* jshint -W086 */
                    default:
                        var realCellRange = grid.viewPort.intersect(decorator);
                        if (realCellRange) {
                            positionCellDecoratorFromRealCellRange(realCellRange, boundingBox);
                        } else {
                            positionDecorator(boundingBox, -1, -1, -1, -1);
                        }
                        break;
                    /* jshint +W086 */
                }

            }
        });

        removeDecorators(grid.decorators.popAllDead());
    };

    function removeDecorators(decorators) {
        decorators.forEach(function (decorator) {
            var boundingBox = decorator.boundingBox;
            if (boundingBox) {
                //if they rendered an element previously we attached it to the bounding box as the only child
                var renderedElement = boundingBox.firstChild;
                if (renderedElement) {
                    //create a destroy dom event that bubbles
                    var destroyEvent = customEvent('decorator-destroy', true);
                    renderedElement.dispatchEvent(destroyEvent);
                }
                decoratorContainer.removeChild(boundingBox);
                decorator.boundingBox = undefined;
            }
        });
    }

    /* END DECORATOR LOGIC */

    /* CELL CLASSES LOGIC */
    viewLayer._drawCellClasses = function () {
        grid.viewPort.iterateCells(function (r, c) {
            cells[r][c].className = '';
        });
        grid.cellClasses.getAll().forEach(function (descriptor) {
            var intersection = grid.viewPort.intersect(descriptor);
            if (intersection) {
                rowloop:
                    for (var r = 0; r < intersection.height; r++) {
                        for (var c = 0; c < intersection.width; c++) {
                            var row = intersection.top + r;
                            var col = intersection.left + c;

                            var cellRow = cells[row];
                            if (!cellRow) {
                                continue rowloop;
                            }
                            var cell = cellRow[col];
                            if (!cell) {
                                continue;
                            }
                            cell.className = (cell.className ? cell.className + ' ' : '') + descriptor.class;
                        }
                    }
            }
        });
    };

    /* END CELL CLASSES LOGIC*/

    viewLayer.destroy = cleanup;

    function cleanup() {
        removeDecorators(grid.decorators.getAlive().concat(grid.decorators.popAllDead()));
        if (!container) {
            return;
        }
        var querySelectorAll = container.querySelectorAll('.' + GRID_VIEW_ROOT_CLASS);
        for (var i = 0; i < querySelectorAll.length; ++i) {
            var root = querySelectorAll[i];
            container.removeChild(root);
        }
    }

    grid.eventLoop.bind('grid-destroy', function () {
        viewLayer.destroy();
        clearTimeout(viewLayer.draw.timeout);
    });

    return viewLayer;
};<|endoftext|>


<commit_before>module.exports = function sha1(buffer) {
  if (buffer === undefined) return create();
  var shasum = create();
  shasum.update(buffer);
  return shasum.digest();
};

// A streaming interface for when nothing is passed in.
function create() {
  var h0 = 0x67452301;
  var h1 = 0xEFCDAB89;
  var h2 = 0x98BADCFE;
  var h3 = 0x10325476;
  var h4 = 0xC3D2E1F0;
  // The first 64 bytes (16 words) is the data chunk
  var block = new Array(80), offset = 0, shift = 24;
  var totalLength = 0;

  return { update: update, digest: digest };

  // The user gave us more data.  Store it!
  function update(chunk) {
    if (typeof chunk === "string") return updateString(chunk);
    var length = chunk.length;
    totalLength += length * 8;
    for (var i = 0; i < length; i++) {
      write(chunk[i]);
    }
  }

  function updateString(string) {
    var length = string.length;
    totalLength += length * 8;
    for (var i = 0; i < length; i++) {
      write(string.charCodeAt(i));
    }
  }

  function write(byte) {
    block[offset] |= (byte & 0xff) << shift;
    if (shift) {
      shift -= 8;
    }
    else {
      offset++;
      shift = 24;
    }
    if (offset === 16) processBlock();
  }

  // No more data will come, pad the block, process and return the result.
  function digest() {
    // Pad
    write(0x80);
    if (offset > 14 || (offset === 14 && shift < 24)) {
      processBlock();
    }
    offset = 14;
    shift = 24;

    // 64-bit length big-endian
    write(0x00); // numbers this big aren't accurate in javascript anyway
    write(0x00); // ..So just hard-code to zero.
    write(totalLength > 0xffffffffff ? totalLength / 0x10000000000 : 0x00);
    write(totalLength > 0xffffffff ? totalLength / 0x100000000 : 0x00);
    for (var s = 24; s >= 0; s -= 8) {
      write(totalLength >> s);
    }

    // At this point one last processBlock() should trigger and we can pull out the result.
    return toHex(h0)
         + toHex(h1)
         + toHex(h2)
         + toHex(h3)
         + toHex(h4);
  }

  // We have a full block to process.  Let's do it!
  function processBlock() {
    // Extend the sixteen 32-bit words into eighty 32-bit words:
    for (var i = 16; i < 80; i++) {
      var w = block[i - 3] ^ block[i - 8] ^ block[i - 14] ^ block[i - 16];
      block[i] = (w << 1) | (w >>> 31);
    }

    // log(block);

    // Initialize hash value for this chunk:
    var a = h0;
    var b = h1;
    var c = h2;
    var d = h3;
    var e = h4;
    var f, k;

    // Main loop:
    for (i = 0; i < 80; i++) {
      if (i < 20) {
        f = d ^ (b & (c ^ d));
        k = 0x5A827999;
      }
      else if (i < 40) {
        f = b ^ c ^ d;
        k = 0x6ED9EBA1;
      }
      else if (i < 60) {
        f = (b & c) | (d & (b | c));
        k = 0x8F1BBCDC;
      }
      else {
        f = b ^ c ^ d;
        k = 0xCA62C1D6;
      }
      var temp = (a << 5 | a >>> 27) + f + e + k + (block[i]|0);
      e = d;
      d = c;
      c = (b << 30 | b >>> 2);
      b = a;
      a = temp;
    }

    // Add this chunk's hash to result so far:
    h0 = (h0 + a) | 0;
    h1 = (h1 + b) | 0;
    h2 = (h2 + c) | 0;
    h3 = (h3 + d) | 0;
    h4 = (h4 + e) | 0;

    // The block is now reusable.
    offset = 0;
    for (i = 0; i < 16; i++) {
      block[i] = 0;
    }
  }

  function toHex(word) {
    var hex = "";
    for (var i = 28; i >= 0; i -= 4) {
      hex += ((word >> i) & 0xf).toString(16);
    }
    return hex;
  }

}
<commit_msg>Make sha1 code run on old browsers<commit_after>var Array32 = typeof Uint8Array === "function" ? Uint8Array : Array;

module.exports = function sha1(buffer) {
  if (buffer === undefined) return create();
  var shasum = create();
  shasum.update(buffer);
  return shasum.digest();
};

// A streaming interface for when nothing is passed in.
function create() {
  var h0 = 0x67452301;
  var h1 = 0xEFCDAB89;
  var h2 = 0x98BADCFE;
  var h3 = 0x10325476;
  var h4 = 0xC3D2E1F0;
  // The first 64 bytes (16 words) is the data chunk
  var block = new Array32(80), offset = 0, shift = 24;
  var totalLength = 0;

  return { update: update, digest: digest };

  // The user gave us more data.  Store it!
  function update(chunk) {
    if (typeof chunk === "string") return updateString(chunk);
    var length = chunk.length;
    totalLength += length * 8;
    for (var i = 0; i < length; i++) {
      write(chunk[i]);
    }
  }

  function updateString(string) {
    var length = string.length;
    totalLength += length * 8;
    for (var i = 0; i < length; i++) {
      write(string.charCodeAt(i));
    }
  }

  function write(byte) {
    block[offset] |= (byte & 0xff) << shift;
    if (shift) {
      shift -= 8;
    }
    else {
      offset++;
      shift = 24;
    }
    if (offset === 16) processBlock();
  }

  // No more data will come, pad the block, process and return the result.
  function digest() {
    // Pad
    write(0x80);
    if (offset > 14 || (offset === 14 && shift < 24)) {
      processBlock();
    }
    offset = 14;
    shift = 24;

    // 64-bit length big-endian
    write(0x00); // numbers this big aren't accurate in javascript anyway
    write(0x00); // ..So just hard-code to zero.
    write(totalLength > 0xffffffffff ? totalLength / 0x10000000000 : 0x00);
    write(totalLength > 0xffffffff ? totalLength / 0x100000000 : 0x00);
    for (var s = 24; s >= 0; s -= 8) {
      write(totalLength >> s);
    }

    // At this point one last processBlock() should trigger and we can pull out the result.
    return toHex(h0)
         + toHex(h1)
         + toHex(h2)
         + toHex(h3)
         + toHex(h4);
  }

  // We have a full block to process.  Let's do it!
  function processBlock() {
    // Extend the sixteen 32-bit words into eighty 32-bit words:
    for (var i = 16; i < 80; i++) {
      var w = block[i - 3] ^ block[i - 8] ^ block[i - 14] ^ block[i - 16];
      block[i] = (w << 1) | (w >>> 31);
    }

    // log(block);

    // Initialize hash value for this chunk:
    var a = h0;
    var b = h1;
    var c = h2;
    var d = h3;
    var e = h4;
    var f, k;

    // Main loop:
    for (i = 0; i < 80; i++) {
      if (i < 20) {
        f = d ^ (b & (c ^ d));
        k = 0x5A827999;
      }
      else if (i < 40) {
        f = b ^ c ^ d;
        k = 0x6ED9EBA1;
      }
      else if (i < 60) {
        f = (b & c) | (d & (b | c));
        k = 0x8F1BBCDC;
      }
      else {
        f = b ^ c ^ d;
        k = 0xCA62C1D6;
      }
      var temp = (a << 5 | a >>> 27) + f + e + k + (block[i]|0);
      e = d;
      d = c;
      c = (b << 30 | b >>> 2);
      b = a;
      a = temp;
    }

    // Add this chunk's hash to result so far:
    h0 = (h0 + a) | 0;
    h1 = (h1 + b) | 0;
    h2 = (h2 + c) | 0;
    h3 = (h3 + d) | 0;
    h4 = (h4 + e) | 0;

    // The block is now reusable.
    offset = 0;
    for (i = 0; i < 16; i++) {
      block[i] = 0;
    }
  }

  function toHex(word) {
    var hex = "";
    for (var i = 28; i >= 0; i -= 4) {
      hex += ((word >> i) & 0xf).toString(16);
    }
    return hex;
  }

}
<|endoftext|>


<commit_before>var fs = require('fs-extra')
var path = require('path')
var glob = require('glob')
var minimatch = require('minimatch')
var mkdirp = require('mkdirp')
var natural = require('natural')
var inflector = new natural.NounInflector()
var Handlebars = require('handlebars')
var connect = require('connect')
var DeepWatch = require('deep-watch')
var _ = require('lodash-node/modern')

var config = require('./config')
var events = require('./events')
var File = require('./file')
var Post = require('./post')
var Page = require('./page')
var Taxonomy = require('./taxonomy')

module.exports = {

  eachTaxonomy: function(cb) {
    _.each(this._taxonomies, function(taxonomyValues, taxonomyTypePlural) {
      var taxonomyType = inflector.singularize(taxonomyTypePlural)
      _.each(taxonomyValues, function(taxonomyValue) {
        cb(taxonomyValue, taxonomyType, taxonomyTypePlural)
      })
    })
  },

  _createPlaceholders: function() {
    var _this = this

    // files are just regulars files that need to be copied
    this._files = []

    // taxonomies are stored in the `_taxonomies`
    // object keyed by the taxonomy type
    this._taxonomies = {}
    _.each(config.taxonomyTypes, function(taxonomyType) {
      _this._taxonomies[inflector.pluralize(taxonomyType)] = []
    })
  },

  _walkPosts: function() {
    var postTypes = config.postTypes
    var taxonomies = this._taxonomies

    _.each(postTypes, function(postType) {
      var postTypePlural = inflector.pluralize(postType)
      var postTypeFiles = glob.sync('_' + postTypePlural + '/*')
      _.each(postTypeFiles, function(filename) {

        // create post objects for each file with in a post type directory
        var post = new Post(File.getOrCreate(filename), postType)

        // convert the post's taxonomy data into Taxonomy instances
        post.registerTaxonomies()

        // if the post specifies a layout, then create a page out of it too
        // (unless the post is a draft and publishing drafts is turned off)
        if (post.layout && !post.isPrivate()) new Page(post)
      })

    })
  },

  _walkFiles: function() {
    var files = glob.sync('**/*')
    var _this = this

    files = _.filter(files, function(filename) {
      // ignore files matching the exlude config array
      var matchesExclude = _.any(config.excludeFiles, function(pattern) {
        return minimatch(filename, pattern)
      })
      if (matchesExclude) return

      // ignore directories
      if (!fs.statSync(filename).isFile()) return

      // include everything else
      return true
    })

    // add files from the includeFiles config option
    files.push.apply(files, config.includeFiles)

    // add files in the _pages directory
    files.push.apply(files, glob.sync('_pages/*'))

    _.each(files, function(filename) {
      var file = File.getOrCreate(filename)

      // for files with data, add to pages, otherwise add to files
      if (file.data) {
        // files without a permalink should use their filename instead
        // of the default permalink since it's assumed they exist at
        // the same location as their destination
        if (!file.data.permalink) file.data.permalink = filename

        new Page(file)
      }
      else {
        _this._files.push(filename)
      }
    })
  },

  _registerPartials: function() {
    _.each(glob.sync(config.partialsDirectory + '/**/*.*'), function(filename) {
      var partial = path.basename(filename, path.extname(filename))
      Handlebars.registerPartial(partial, fs.readFileSync(filename, 'utf-8'))
    })
  },

  _loadPlugins: function() {
    // get system plugins
    var systemPluginDir = path.resolve(__dirname, '../plugins')
    var systemPlugins = glob.sync('**/*.js', {cwd: systemPluginDir})

    // get local plugins
    var localPlugins = glob.sync('**/*.js', {cwd: config.pluginDirectory})

    // don't load system plugins if there's a local plugin by the same name
    systemPlugins = _.without.apply(_, [systemPlugins].concat(localPlugins))

    // don't load sytem plugins if they've been excluded
    systemPlugins = _.without.apply(_, [systemPlugins].concat(config.excludePlugins))

    // require system plugins
    _.each(systemPlugins, function(filename) {
      require(path.resolve(systemPluginDir, filename))
    })

    // require local plugins
    _.each(localPlugins, function(filename) {
      require(path.resolve(config.pluginDirectory, filename))
    })

  },

  _ensureCleanDestination: function() {
    // remove any previously generated _site files
    fs.removeSync(config.destination)
  },

  _paginate: function() {
    Page.each(function(page) {
      page.paginate()
    })
  },

  _renderPosts: function() {
    Post.each(function(post) {
      post.render()
    })
  },

  _renderPages: function() {
    Page.each(function(page) {
      page.render()
      page.write()
    })
  },

  _copyFiles: function() {
    var _this = this

    _.each(this._files, function(filename) {
      var destination = path.join(config.destination, filename)

      events.emit("beforeCopy", filename)

      // TODO: since we've already read this file, look into way
      // to avoid doing this again. Maybe storing the buffer...
      fs.outputFileSync(destination, fs.readFileSync(filename))

      events.emit("afterCopy", filename)
      console.log("Copying " + filename + " to " + destination)
    })
  },

  _clearCaches: function() {
    Post.reset()
    Page.reset()
    Taxonomy.reset()
  },

  build: function() {

    // scan files for data
    this._createPlaceholders()
    this._walkPosts()
    this._walkFiles()
    this._ensureCleanDestination()
    this._registerPartials()
    this._loadPlugins()

    events.emit('beforeBuild')

    // create the new site
    this._paginate()
    this._renderPosts()
    this._renderPages()
    this._copyFiles()

    events.emit('afterBuild')
  },

  rebuild: function() {
    this._clearCaches()
    this.build()
  },

  serve: function() {

    var _this = this

    this.build()

    var watchOptions = {exclude: config.watchExcludes}
    var dw = new DeepWatch('.', watchOptions, function(event, filename) {
      console.log(event, filename)
      _this.rebuild(options)
    })

    dw.start()

    connect()
      .use(connect.logger('dev'))
      .use(connect.static('_site'))
      .listen(config.port)
  }

}
<commit_msg>Fix a typo.<commit_after>var fs = require('fs-extra')
var path = require('path')
var glob = require('glob')
var minimatch = require('minimatch')
var mkdirp = require('mkdirp')
var natural = require('natural')
var inflector = new natural.NounInflector()
var Handlebars = require('handlebars')
var connect = require('connect')
var DeepWatch = require('deep-watch')
var _ = require('lodash-node/modern')

var config = require('./config')
var events = require('./events')
var File = require('./file')
var Post = require('./post')
var Page = require('./page')
var Taxonomy = require('./taxonomy')

module.exports = {

  eachTaxonomy: function(cb) {
    _.each(this._taxonomies, function(taxonomyValues, taxonomyTypePlural) {
      var taxonomyType = inflector.singularize(taxonomyTypePlural)
      _.each(taxonomyValues, function(taxonomyValue) {
        cb(taxonomyValue, taxonomyType, taxonomyTypePlural)
      })
    })
  },

  _createPlaceholders: function() {
    var _this = this

    // files are just regulars files that need to be copied
    this._files = []

    // taxonomies are stored in the `_taxonomies`
    // object keyed by the taxonomy type
    this._taxonomies = {}
    _.each(config.taxonomyTypes, function(taxonomyType) {
      _this._taxonomies[inflector.pluralize(taxonomyType)] = []
    })
  },

  _walkPosts: function() {
    var postTypes = config.postTypes
    var taxonomies = this._taxonomies

    _.each(postTypes, function(postType) {
      var postTypePlural = inflector.pluralize(postType)
      var postTypeFiles = glob.sync('_' + postTypePlural + '/*')
      _.each(postTypeFiles, function(filename) {

        // create post objects for each file within a post type directory
        var post = new Post(File.getOrCreate(filename), postType)

        // convert the post's taxonomy data into Taxonomy instances
        post.registerTaxonomies()

        // if the post specifies a layout, then create a page out of it too
        // (unless the post is a draft and publishing drafts is turned off)
        if (post.layout && !post.isPrivate()) new Page(post)
      })

    })
  },

  _walkFiles: function() {
    var files = glob.sync('**/*')
    var _this = this

    files = _.filter(files, function(filename) {
      // ignore files matching the exlude config array
      var matchesExclude = _.any(config.excludeFiles, function(pattern) {
        return minimatch(filename, pattern)
      })
      if (matchesExclude) return

      // ignore directories
      if (!fs.statSync(filename).isFile()) return

      // include everything else
      return true
    })

    // add files from the includeFiles config option
    files.push.apply(files, config.includeFiles)

    // add files in the _pages directory
    files.push.apply(files, glob.sync('_pages/*'))

    _.each(files, function(filename) {
      var file = File.getOrCreate(filename)

      // for files with data, add to pages, otherwise add to files
      if (file.data) {
        // files without a permalink should use their filename instead
        // of the default permalink since it's assumed they exist at
        // the same location as their destination
        if (!file.data.permalink) file.data.permalink = filename

        new Page(file)
      }
      else {
        _this._files.push(filename)
      }
    })
  },

  _registerPartials: function() {
    _.each(glob.sync(config.partialsDirectory + '/**/*.*'), function(filename) {
      var partial = path.basename(filename, path.extname(filename))
      Handlebars.registerPartial(partial, fs.readFileSync(filename, 'utf-8'))
    })
  },

  _loadPlugins: function() {
    // get system plugins
    var systemPluginDir = path.resolve(__dirname, '../plugins')
    var systemPlugins = glob.sync('**/*.js', {cwd: systemPluginDir})

    // get local plugins
    var localPlugins = glob.sync('**/*.js', {cwd: config.pluginDirectory})

    // don't load system plugins if there's a local plugin by the same name
    systemPlugins = _.without.apply(_, [systemPlugins].concat(localPlugins))

    // don't load sytem plugins if they've been excluded
    systemPlugins = _.without.apply(_, [systemPlugins].concat(config.excludePlugins))

    // require system plugins
    _.each(systemPlugins, function(filename) {
      require(path.resolve(systemPluginDir, filename))
    })

    // require local plugins
    _.each(localPlugins, function(filename) {
      require(path.resolve(config.pluginDirectory, filename))
    })

  },

  _ensureCleanDestination: function() {
    // remove any previously generated _site files
    fs.removeSync(config.destination)
  },

  _paginate: function() {
    Page.each(function(page) {
      page.paginate()
    })
  },

  _renderPosts: function() {
    Post.each(function(post) {
      post.render()
    })
  },

  _renderPages: function() {
    Page.each(function(page) {
      page.render()
      page.write()
    })
  },

  _copyFiles: function() {
    var _this = this

    _.each(this._files, function(filename) {
      var destination = path.join(config.destination, filename)

      events.emit("beforeCopy", filename)

      // TODO: since we've already read this file, look into way
      // to avoid doing this again. Maybe storing the buffer...
      fs.outputFileSync(destination, fs.readFileSync(filename))

      events.emit("afterCopy", filename)
      console.log("Copying " + filename + " to " + destination)
    })
  },

  _clearCaches: function() {
    Post.reset()
    Page.reset()
    Taxonomy.reset()
  },

  build: function() {

    // scan files for data
    this._createPlaceholders()
    this._walkPosts()
    this._walkFiles()
    this._ensureCleanDestination()
    this._registerPartials()
    this._loadPlugins()

    events.emit('beforeBuild')

    // create the new site
    this._paginate()
    this._renderPosts()
    this._renderPages()
    this._copyFiles()

    events.emit('afterBuild')
  },

  rebuild: function() {
    this._clearCaches()
    this.build()
  },

  serve: function() {

    var _this = this

    this.build()

    var watchOptions = {exclude: config.watchExcludes}
    var dw = new DeepWatch('.', watchOptions, function(event, filename) {
      console.log(event, filename)
      _this.rebuild(options)
    })

    dw.start()

    connect()
      .use(connect.logger('dev'))
      .use(connect.static('_site'))
      .listen(config.port)
  }

}
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Post = require('./post');
var Category = require('./category');
var Tag = require('./tag');
var Media = require('./media');
var Comment = require('./comment');
var Follow = require('./follow');
var request = require('./util/request');
var debug = require('debug')('wpcom:site');

/**
 * Resources array
 * A list of endpoints with the same structure
 */

var resources = [
  'categories',
  'comments',
  'follows',
  'media',
  'posts',
  [ 'stats', 'stats' ],
  [ 'statsVisits', 'stats/visits' ],
  [ 'statsReferrers', 'stats/referrers' ],
  [ 'statsTopPosts', 'stats/top-posts' ],
  [ 'statsCountryViews', 'stats/country-views' ],
  [ 'statsClicks', 'stats/clicks' ],
  [ 'statsSearchTerms', 'stats/search-terms' ],
  'tags',
  'users'
];

/**
 * Create a Site instance
 *
 * @param {WPCOM} wpcom
 * @api public
 */

function Site(id, wpcom) {
  if (!(this instanceof Site)) {
    return new Site(id, wpcom);
  }

  this.wpcom = wpcom;

  debug('set %o site id', id);
  this._id = encodeURIComponent(id);
}

/**
 * Require site information
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Site.prototype.get = function (query, fn) {
  return request.get(this.wpcom, null, '/sites/' + this._id, query, fn);
};

/**
 * List method builder
 *
 * @param {String} subpath
 * @param {Function}
 * @api private
 */

function list (subpath, apiVersion) {

  /**
   * Return the <names>List method
   *
   * @param {Object} [query]
   * @param {Function} fn
   * @api public
   */

  return function (query, fn) {
    var path = '/sites/' + this._id + '/' + subpath;
    return request.get(this.wpcom, { apiVersion: apiVersion }, path, query, fn);
  };
}

// walk for each resource and create related method
var i, res, isarr, name, subpath, apiVersion;
for (i = 0; i < resources.length; i++) {
  res = resources[i];
  isarr = Array.isArray(res);

  name =  isarr ? res[0] : res + 'List';
  subpath = isarr ? res[1] : res;
  apiVersion = isarr && 'string' === typeof res[2] ? res[2] : '1';

  debug('adding %o method in %o sub-path (v%o)', 'site.' + name + '()', subpath, apiVersion);
  Site.prototype[name] = list(subpath, apiVersion);
}

/**
 * :POST:
 * Create a `Post` instance
 *
 * @param {String} id
 * @api public
 */

Site.prototype.post = function (id) {
  return new Post(id, this._id, this.wpcom);
};

/**
 * :POST:
 * Add a new blog post
 *
 * @param {Object} body
 * @param {Function} fn
 * @return {Post} new Post instance
 */

Site.prototype.addPost = function (body, fn) {
  var post = new Post(null, this._id, this.wpcom);
  return post.add(body, fn);
};

/**
 * :POST:
 * Delete a blog post
 *
 * @param {String} id
 * @param {Function} fn
 * @return {Post} remove Post instance
 */

Site.prototype.deletePost = function (id, fn) {
  var post = new Post(id, this._id, this.wpcom);
  return post.delete(fn);
};

/**
 * Create a `Media` instance
 *
 * @param {String} id
 * @api public
 */

Site.prototype.media = function (id) {
  return new Media(id, this._id, this.wpcom);
};

/**
 * Add a media from a file
 *
 * @param {Object} [query]
 * @param {Array|String} files
 * @param {Function} fn
 * @return {Post} new Post instance
 */

Site.prototype.addMediaFiles = function (query, files, fn) {
  var media = new Media(null, this._id, this.wpcom);
  return media.addFiles(query, files, fn);
};

/**
 * Add a new media from url
 *
 * @param {Object} [query]
 * @param {Array|String} files
 * @param {Function} fn
 * @return {Post} new Post instance
 */

Site.prototype.addMediaUrls = function (query, files, fn) {
  var media = new Media(null, this._id, this.wpcom);
  return media.addUrls(query, files, fn);
};

/**
 * Delete a blog media
 *
 * @param {String} id
 * @param {Function} fn
 * @return {Post} removed Media instance
 */

Site.prototype.deleteMedia = function (id, fn) {
  var media = new Media(id, this._id, this.wpcom);
  return media.del(fn);
};

/**
 * Create a `Comment` instance
 *
 * @param {String} id
 * @api public
 */

Site.prototype.comment = function (id) {
  return new Comment(id, null, this._id, this.wpcom);
};

/**
 * Create a `Follow` instance
 *
 * @api public
 */

Site.prototype.follow = function () {
  return new Follow(this._id, this.wpcom);
};

/**
 * Create a `Category` instance
 * Set `cat` alias
 *
 * @param {String} [slug]
 * @api public
 */

Site.prototype.cat = Site.prototype.category = function (slug) {
  return new Category(slug, this._id, this.wpcom);
};

/**
 * Create a `Tag` instance
 *
 * @param {String} [slug]
 * @api public
 */

Site.prototype.tag = function (slug) {
  return new Tag(slug, this._id, this.wpcom);
};

/**
 * Expose `Site` module
 */

module.exports = Site;
<commit_msg>site: add `shortcodes()` function<commit_after>
/**
 * Module dependencies.
 */

var Post = require('./post');
var Category = require('./category');
var Tag = require('./tag');
var Media = require('./media');
var Comment = require('./comment');
var Follow = require('./follow');
var request = require('./util/request');
var debug = require('debug')('wpcom:site');

/**
 * Resources array
 * A list of endpoints with the same structure
 */

var resources = [
  'categories',
  'comments',
  'follows',
  'media',
  'posts',
  [ 'stats', 'stats' ],
  [ 'statsVisits', 'stats/visits' ],
  [ 'statsReferrers', 'stats/referrers' ],
  [ 'statsTopPosts', 'stats/top-posts' ],
  [ 'statsCountryViews', 'stats/country-views' ],
  [ 'statsClicks', 'stats/clicks' ],
  [ 'statsSearchTerms', 'stats/search-terms' ],
  'tags',
  'users'
];

/**
 * Create a Site instance
 *
 * @param {WPCOM} wpcom
 * @api public
 */

function Site(id, wpcom) {
  if (!(this instanceof Site)) {
    return new Site(id, wpcom);
  }

  this.wpcom = wpcom;

  debug('set %o site id', id);
  this._id = encodeURIComponent(id);
}

/**
 * Require site information
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Site.prototype.get = function (query, fn) {
  return request.get(this.wpcom, null, '/sites/' + this._id, query, fn);
};

/**
 * List method builder
 *
 * @param {String} subpath
 * @param {Function}
 * @api private
 */

function list (subpath, apiVersion) {

  /**
   * Return the <names>List method
   *
   * @param {Object} [query]
   * @param {Function} fn
   * @api public
   */

  return function (query, fn) {
    var path = '/sites/' + this._id + '/' + subpath;
    return request.get(this.wpcom, { apiVersion: apiVersion }, path, query, fn);
  };
}

// walk for each resource and create related method
var i, res, isarr, name, subpath, apiVersion;
for (i = 0; i < resources.length; i++) {
  res = resources[i];
  isarr = Array.isArray(res);

  name =  isarr ? res[0] : res + 'List';
  subpath = isarr ? res[1] : res;
  apiVersion = isarr && 'string' === typeof res[2] ? res[2] : '1';

  debug('adding %o method in %o sub-path (v%o)', 'site.' + name + '()', subpath, apiVersion);
  Site.prototype[name] = list(subpath, apiVersion);
}

/**
 * :POST:
 * Create a `Post` instance
 *
 * @param {String} id
 * @api public
 */

Site.prototype.post = function (id) {
  return new Post(id, this._id, this.wpcom);
};

/**
 * :POST:
 * Add a new blog post
 *
 * @param {Object} body
 * @param {Function} fn
 * @return {Post} new Post instance
 */

Site.prototype.addPost = function (body, fn) {
  var post = new Post(null, this._id, this.wpcom);
  return post.add(body, fn);
};

/**
 * :POST:
 * Delete a blog post
 *
 * @param {String} id
 * @param {Function} fn
 * @return {Post} remove Post instance
 */

Site.prototype.deletePost = function (id, fn) {
  var post = new Post(id, this._id, this.wpcom);
  return post.delete(fn);
};

/**
 * Create a `Media` instance
 *
 * @param {String} id
 * @api public
 */

Site.prototype.media = function (id) {
  return new Media(id, this._id, this.wpcom);
};

/**
 * Add a media from a file
 *
 * @param {Object} [query]
 * @param {Array|String} files
 * @param {Function} fn
 * @return {Post} new Post instance
 */

Site.prototype.addMediaFiles = function (query, files, fn) {
  var media = new Media(null, this._id, this.wpcom);
  return media.addFiles(query, files, fn);
};

/**
 * Add a new media from url
 *
 * @param {Object} [query]
 * @param {Array|String} files
 * @param {Function} fn
 * @return {Post} new Post instance
 */

Site.prototype.addMediaUrls = function (query, files, fn) {
  var media = new Media(null, this._id, this.wpcom);
  return media.addUrls(query, files, fn);
};

/**
 * Delete a blog media
 *
 * @param {String} id
 * @param {Function} fn
 * @return {Post} removed Media instance
 */

Site.prototype.deleteMedia = function (id, fn) {
  var media = new Media(id, this._id, this.wpcom);
  return media.del(fn);
};

/**
 * Create a `Comment` instance
 *
 * @param {String} id
 * @api public
 */

Site.prototype.comment = function (id) {
  return new Comment(id, null, this._id, this.wpcom);
};

/**
 * Create a `Follow` instance
 *
 * @api public
 */

Site.prototype.follow = function () {
  return new Follow(this._id, this.wpcom);
};

/**
 * Create a `Category` instance
 * Set `cat` alias
 *
 * @param {String} [slug]
 * @api public
 */

Site.prototype.cat = Site.prototype.category = function (slug) {
  return new Category(slug, this._id, this.wpcom);
};

/**
 * Create a `Tag` instance
 *
 * @param {String} [slug]
 * @api public
 */

Site.prototype.tag = function (slug) {
  return new Tag(slug, this._id, this.wpcom);
};

/**
 * Get a list of shortcodes available on a site.
 *
 * Note: The current user must have publishing access.
 *
 * @api public
 */

Site.prototype.shortcodes = function (query, fn) {
  var path = '/sites/' + this._id + '/shortcodes';
  return request.get(this.wpcom, null, path, query, fn);
};

/**
 * Expose `Site` module
 */

module.exports = Site;
<|endoftext|>


<commit_before>/**
 * @jest-environment node
 */
const fs = require('fs');
const path = require('path');
const utils = require('./utils');
const nock = require('nock');

const readText = async (fileName) => {const buffer = await fs.promises.readFile(path.join(__dirname, '__mocks__', fileName)); return buffer.toString();};

describe('utils', () => {
    let _reporter;
    afterEach(() => {
        nock.cleanAll();
    });
    beforeEach(async () => {
        process.env.GET_CONTENT = true;
        nock.disableNetConnect();

        _reporter = {
            panic: (...args) => {throw args[0];},
            error: jest.fn(),
            activityTimer: () => {
                return {
                    start: jest.fn(),
                    end: jest.fn(),
                };
            }
        };
    });
    it('fix GitHub URL: submodule gets expanded', () => {
        expect(utils.fixGitHubUrl('https://github.com/jenkinsci/blueocean-plugin/blueocean-bitbucket-pipeline', 'master'))
            .toBe('https://github.com/jenkinsci/blueocean-plugin/tree/master/blueocean-bitbucket-pipeline');
    });
    it('fix GitHub URL: expanded stays expanded', () => {
        expect(utils.fixGitHubUrl('https://github.com/jenkinsci/blueocean-plugin/tree/master/blueocean-bitbucket-pipeline', 'master'))
            .toBe('https://github.com/jenkinsci/blueocean-plugin/tree/master/blueocean-bitbucket-pipeline');
    });
    it('fix GitHub URL: no submodule, keep short', () => {
        expect(utils.fixGitHubUrl('https://github.com/jenkinsci/junit-plugin', ''))
            .toBe('https://github.com/jenkinsci/junit-plugin');
    });
    it('get plugin data for a wiki based plugin', async () => {
        nock('https://updates.jenkins.io')
            .get('/update-center.actual.json')
            .reply(200, JSON.parse(await readText('update-center.actual.json')));
        nock('https://updates.jenkins.io')
            .get('/current/plugin-documentation-urls.json')
            .reply(200, '{"ios-device-connector":{"url":"https://wiki.jenkins-ci.org/display/JENKINS/iOS+Device+Connector+Plugin"}}');
        nock('https://www.jenkins.io')
            .get('/doc/pipeline/steps/contents.json')
            .reply(200, []);
        nock('https://www.jenkins.io')
            .get('/doc/developer/extensions/contents.json')
            .reply(200, []);
        nock('https://raw.githubusercontent.com:443')
            .get('/jenkinsci/bom/master/bom-weekly/pom.xml')
            .reply(200, '');
        nock('https://raw.githubusercontent.com:443')
            .get('/jenkinsci/jenkins/master/core/src/main/resources/jenkins/split-plugins.txt')
            .reply(200, await readText('split-plugins.txt'));
        nock('https://raw.githubusercontent.com:443')
            .get('/jenkinsci/jenkins/master/core/src/main/resources/jenkins/canonical-labels.txt')
            .reply(200, '');
        nock('https://plugins.jenkins.io').persist()
            .get(/\/api\/plugin\/.*/)
            .reply(200, '{"wiki":{"content": "
This plugin lists up all the iOS devices connected to the master and all the Jenkins slaves, and provide operations to them.
"}}');

        const createNode = jest.fn().mockResolvedValue();
        const createContentDigest = require('gatsby-core-utils').createContentDigest;
        const createNodeId = jest.fn(key => key);
        const firstReleases = {'ios-device-connector': new Date(0)};
        const labelToCategory = {'ios': 'languagesPlatforms', 'builder': 'buildManagement'};
        const stats = {
            'core': {'installations': [{total: 300000}, {total: 300000}]},
            'ios-device-connector': {
                'currentInstalls': 269, 'installations': [
                    {'timestamp': 1590984000000, 'total': 349},
                    {'timestamp': 1593576000000, 'total': 348},
                    {'timestamp': 1596254400000, 'total': 341},
                    {'timestamp': 1598932800000, 'total': 347},
                    {'timestamp': 1601524800000, 'total': 318},
                    {'timestamp': 1604203200000, 'total': 325},
                    {'timestamp': 1606798800000, 'total': 312},
                    {'timestamp': 1609477200000, 'total': 301},
                    {'timestamp': 1612155600000, 'total': 297},
                    {'timestamp': 1614574800000, 'total': 303},
                    {'timestamp': 1617249600000, 'total': 290},
                    {'timestamp': 1619841600000, 'total': 275},
                    {'timestamp': 1622520000000, 'total': 269}]
            }
        };
        await utils.fetchPluginData({createNode, createNodeId, createContentDigest, reporter: _reporter, firstReleases, labelToCategory, stats});
        expect(createNode.mock.calls.filter(call => call[0].name === 'ios-device-connector').map(args => args[0])).toMatchSnapshot();
    });
});
<commit_msg>17:5  error  beforeEach hooks should be before any afterEach hooks  jest/prefer-hooks-in-order<commit_after>/**
 * @jest-environment node
 */
const fs = require('fs');
const path = require('path');
const utils = require('./utils');
const nock = require('nock');

const readText = async (fileName) => {const buffer = await fs.promises.readFile(path.join(__dirname, '__mocks__', fileName)); return buffer.toString();};

describe('utils', () => {
    let _reporter;
    beforeEach(async () => {
        process.env.GET_CONTENT = true;
        nock.disableNetConnect();

        _reporter = {
            panic: (...args) => {throw args[0];},
            error: jest.fn(),
            activityTimer: () => {
                return {
                    start: jest.fn(),
                    end: jest.fn(),
                };
            }
        };
    });
    afterEach(() => {
        nock.cleanAll();
    });
    it('fix GitHub URL: submodule gets expanded', () => {
        expect(utils.fixGitHubUrl('https://github.com/jenkinsci/blueocean-plugin/blueocean-bitbucket-pipeline', 'master'))
            .toBe('https://github.com/jenkinsci/blueocean-plugin/tree/master/blueocean-bitbucket-pipeline');
    });
    it('fix GitHub URL: expanded stays expanded', () => {
        expect(utils.fixGitHubUrl('https://github.com/jenkinsci/blueocean-plugin/tree/master/blueocean-bitbucket-pipeline', 'master'))
            .toBe('https://github.com/jenkinsci/blueocean-plugin/tree/master/blueocean-bitbucket-pipeline');
    });
    it('fix GitHub URL: no submodule, keep short', () => {
        expect(utils.fixGitHubUrl('https://github.com/jenkinsci/junit-plugin', ''))
            .toBe('https://github.com/jenkinsci/junit-plugin');
    });
    it('get plugin data for a wiki based plugin', async () => {
        nock('https://updates.jenkins.io')
            .get('/update-center.actual.json')
            .reply(200, JSON.parse(await readText('update-center.actual.json')));
        nock('https://updates.jenkins.io')
            .get('/current/plugin-documentation-urls.json')
            .reply(200, '{"ios-device-connector":{"url":"https://wiki.jenkins-ci.org/display/JENKINS/iOS+Device+Connector+Plugin"}}');
        nock('https://www.jenkins.io')
            .get('/doc/pipeline/steps/contents.json')
            .reply(200, []);
        nock('https://www.jenkins.io')
            .get('/doc/developer/extensions/contents.json')
            .reply(200, []);
        nock('https://raw.githubusercontent.com:443')
            .get('/jenkinsci/bom/master/bom-weekly/pom.xml')
            .reply(200, '');
        nock('https://raw.githubusercontent.com:443')
            .get('/jenkinsci/jenkins/master/core/src/main/resources/jenkins/split-plugins.txt')
            .reply(200, await readText('split-plugins.txt'));
        nock('https://raw.githubusercontent.com:443')
            .get('/jenkinsci/jenkins/master/core/src/main/resources/jenkins/canonical-labels.txt')
            .reply(200, '');
        nock('https://plugins.jenkins.io').persist()
            .get(/\/api\/plugin\/.*/)
            .reply(200, '{"wiki":{"content": "
This plugin lists up all the iOS devices connected to the master and all the Jenkins slaves, and provide operations to them.
"}}');

        const createNode = jest.fn().mockResolvedValue();
        const createContentDigest = require('gatsby-core-utils').createContentDigest;
        const createNodeId = jest.fn(key => key);
        const firstReleases = {'ios-device-connector': new Date(0)};
        const labelToCategory = {'ios': 'languagesPlatforms', 'builder': 'buildManagement'};
        const stats = {
            'core': {'installations': [{total: 300000}, {total: 300000}]},
            'ios-device-connector': {
                'currentInstalls': 269, 'installations': [
                    {'timestamp': 1590984000000, 'total': 349},
                    {'timestamp': 1593576000000, 'total': 348},
                    {'timestamp': 1596254400000, 'total': 341},
                    {'timestamp': 1598932800000, 'total': 347},
                    {'timestamp': 1601524800000, 'total': 318},
                    {'timestamp': 1604203200000, 'total': 325},
                    {'timestamp': 1606798800000, 'total': 312},
                    {'timestamp': 1609477200000, 'total': 301},
                    {'timestamp': 1612155600000, 'total': 297},
                    {'timestamp': 1614574800000, 'total': 303},
                    {'timestamp': 1617249600000, 'total': 290},
                    {'timestamp': 1619841600000, 'total': 275},
                    {'timestamp': 1622520000000, 'total': 269}]
            }
        };
        await utils.fetchPluginData({createNode, createNodeId, createContentDigest, reporter: _reporter, firstReleases, labelToCategory, stats});
        expect(createNode.mock.calls.filter(call => call[0].name === 'ios-device-connector').map(args => args[0])).toMatchSnapshot();
    });
});
<|endoftext|>


<commit_before>module.exports = {
	attributes: {}
};
<commit_msg>Make Empty api fixture model schemaless<commit_after>module.exports = {
	schema: false,
	attributes: {}
};
<|endoftext|>


<commit_before>'use strict';

var _Object$assign = require('babel-runtime/core-js/object/assign')['default'];

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports['default'] = MockData;

var _ParsersParser = require('./Parsers/Parser');

var _ParsersParser2 = _interopRequireDefault(_ParsersParser);

var parser = new _ParsersParser2['default']();

function MockData(definition, configMock) {
  var schema = definition.schema;

  if (!schema) return null;

  var mock = {};
  if (configMock.useExamples) {
    if (configMock.useExamples && definition.examples && definition.examples['application/json']) {
      mock = definition.examples['application/json'];
    }

    if (configMock.extendExamples) {
      mock = _Object$assign(parser.parse(schema), mock);
    }
  } else {
    mock = parser.parse(schema);
  }

  return mock;
}

;
module.exports = exports['default'];<commit_msg>grunt dist<commit_after>'use strict';

var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];

var _Object$assign = require('babel-runtime/core-js/object/assign')['default'];

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports['default'] = MockData;

var _stripJsonComments = require('strip-json-comments');

var _stripJsonComments2 = _interopRequireDefault(_stripJsonComments);

var _ParsersParser = require('./Parsers/Parser');

var _ParsersParser2 = _interopRequireDefault(_ParsersParser);

var parser = new _ParsersParser2['default']();

function MockData(definition, configMock) {
  var schema = definition.schema;

  if (!schema) return null;

  var mock = null;

  if (configMock.useExamples) {
    if (configMock.useExamples && definition.examples) {
      var keys = _Object$keys(definition.examples);
      var key = keys.find(function (obj) {
        return obj.includes('json');
      });
      if (key) {
        mock = definition.examples[key];
        if (typeof mock === 'string') {
          mock = (0, _stripJsonComments2['default'])(mock);
          mock = JSON.parse(mock);
        }
      }
      if (configMock.extendExamples) {
        mock = _Object$assign(parser.parse(schema), mock);
      }
    }
  }

  if (!mock) {
    mock = parser.parse(schema);
  }

  return mock;
}

;
module.exports = exports['default'];<|endoftext|>


<commit_before>//===============================================
//					CloudObject

cloudObject = function(){
	this.x = this.y = 0;
	this.alpha = 0;
	this.alpha_max = 0;
	this.t = 0;
	this.lifePeriod = 2;
	this.velocity_x = 0;

	this.img = loadImage("../../game/pictures/mistic_cloud.png");

	this.img.parent = this;
	this.img.onload = function(){
		this.parent.width = this.width;
		this.parent.height = this.height;
		this.parent.respawn();
	}
};

cloudObject.prototype.respawn = function(){
	this.alpha = 0;
	this.alpha_max = 0.3 + Math.random() * 0.5;
	this.t = 0;
	this.lifePeriod = 5 + Math.random() * 20;
	this.velocity_x = 0.2 + Math.random() * 1;

	var x1 = kameraT.x - 600 - this.width;
	var x2 = kameraT.x + this.width/2;

	var y1 = kameraT.y + this.height/2;
	var y2 = kameraT.y -300 - this.height/2;
	var y_min = 0 + this.height;

	this.x1 = x1;
	this.x2 = x2;
	this.y1 = y1;
	this.y2 = y2;

	if(y2 < y_min){
		y2 = y_min;
	}

	this.x = x1+Math.random()*(x2-x1);
	this.y = y2+Math.random()*(y1-y2);
}

cloudObject.prototype.logic = function(){
	this.t ++;
	this.x += this.velocity_x;

	var atlag_a     = this.alpha_max/2;
	var amplitudo_a = this.alpha_max/2
	var fazis_a     = Math.PI
	var periodus_a  = (2*Math.PI)*this.lifePeriod;

	this.alpha = atlag_a + amplitudo_a * Math.cos(fazis_a+this.t/periodus_a);

	if(this.t/periodus_a > 2*Math.PI){
		this.respawn();
	}
};

cloudObject.prototype.draw = function(context, t){
	context.globalAlpha = this.alpha;
	context.drawImage(this.img, t.tX(this.x), t.tY(this.y));
	context.globalAlpha = 1;

	/*	A képernyő kereteihez képest 10px-el "beljebb lévő" téglalap rajzolása
	var x1 = kameraT.x - 600 + 10;
	var x2 = kameraT.x -10;

	var y1 = kameraT.y -10 ;
	var y2 = kameraT.y - 300 +10;
	context.fillStyle = '#00FF00';
	context.fillRect(t.tX(x1), t.tY(y1), x2-x1, y1-y2);
	*/

};

//===============================================
//					Transformation

transformation = function(){
	this.x=0;
	this.y=0;
	this.ay=1;
	this.ax=1;
};

transformation.prototype.tX=function(x){
	return this.ax*x+this.x;
};

transformation.prototype.tY=function(y){
	return this.ay*y+this.y;
};

//===============================================
//					Thing

thing = function(x, y, z, pic){
	this.x = x;
	this.y = y;
	this.z = z;
	//console.log("loading iamge: "+pic);
	this.img = loadImage("../../game/pictures/"+pic+".png");
	this.width = this.img.width;
	this.height = this.img.height;
};

thing.prototype.logic = function(){};

thing.prototype.draw = function(context, t){
	context.drawImage(this.img,
		 t.tX(this.x), t.tY(this.y));
};

//===============================================
//					Spikes

spike = function(x, y, width, height){
	var correcty = 10;
	this.a = 104/236;
	this.x = x;
	this.y = y-correcty;
	this.img = loadImage("rock_spike_3.png");
	this.width = width;//this.img.width;//104
	this.height = height+correcty;//this.img.height;//236
	player.addCollisionCheck(this);

	/*
	var obj = thing.apply(this, x, y, 0, "rock_spike_2");
	obj.width = obj.img.width;
	obj.height = obj.img.height;
	return obj;
	*/
};

//spike.prototype = new thing();

spike.prototype.collide = function(p){
	p.death();
};

spike.prototype.logic = function(){};

spike.prototype.draw = function(context, t){
	var count = Math.round(this.width/(this.a*this.height));

	//console.log(count);
	if(count < 1){
		count=1;
	}
		var width_c = this.width/count;

		for(var i=0; i<count; i++){
			context.drawImage(this.img,
				 t.tX(this.x+i*width_c), t.tY(this.y)-this.height, width_c, this.height);
		}
};

//===============================================
//				Platform

platform = function(x, y, width){
	this.x = x;
	this.y = y;
	this.width = width;
};

platform.prototype.logic = function(){};

platform.prototype.draw = function(context, t){
	context.fillStyle = "black";
	context.fillRect(t.tX(this.x), t.tY(this.y), this.width, 5);
};

//===============================================
//				text

text = function(text, x, y, conext, font){
	this.text = text;
	this.x = x;
	this.y = y;
	this.width = 0;
	this.height = 0;
	this.font = font;
	if(font){
		tmp = context.font;
		context.font = font;
		this.width = context.measureText(text).width;
		this.height = context.measureText(text).height;
		conext.font = tmp;
	}else{
		this.width = context.measureText(text).width;
		this.height = context.measureText(text).height;
	}
};

text.prototype.setText = function(newText){
	this.text = newText;
	/*
	ctx.font="30px Arial";
	var txt="Hello World"
	ctx.fillText("width:" + ctx.measureText(txt).width,10,50)
	*/
}

text.prototype.logic=function(){
};

text.prototype.draw = function(context, t){
	context.fillText(this.text, this.x, this.y);
	//context.fillText("Szig szakkör játéka!", 600/2-40, 20);
};

//=============================================
//       Mushroom

mushroom=function(){
	this.x0=450;
	this.y=0;
	this.x1=750;
	this.x=this.x0;
	this.speed=1;
	this.width=40;
	this.height=40;
	this.img = loadImage("gomba.png");
};
mushroom.prototype.logic=function(){
	if(this.x<=this.x1 && this.x>=this.x0)
	{
		this.x+=this.speed;
	}else
	{
		if(this.x0>this.x)
		{
			this.x=this.x0;
		}else
		{
			this.x=this.x1;
		}
		this.speed*=-1;
	}
};

mushroom.prototype.collide = function(p){
	if(p.prevY>this.y + this.height) {
		this.death();
	}else {
		p.death();
	}
}

mushroom.prototype.death = function(){
	elements.splice(elements.indexOf(this),1);
	player.removeCollisionCheck(this);
}

mushroom.prototype.draw=function(context,t){
	context.drawImage(this.img,
		 t.tX(this.x), t.tY(this.y+2)-this.height+Math.sin(clock/2.0)*2);
};

//=============================================
//       coin

coin=function(x, y){
	this.x_orig = x;
	this.x1 = x;
	this.x2 = x + 40;
	this.y = this.y_orig = y;
	this.width_orig=40;
	this.height=40;
	this.img = loadImage("coin.png");
	this.img_mirror=loadImage("coin_m.png");
	this.t=0;
	this.period= (2*Math.PI)*2;
	//player.addCollisionCheck(this);
};

coin.prototype.logic = function(){
	this.x1 = (this.x_orig+this.width_orig)/2 + (this.width_orig/2) * Math.cos((this.t/this.period)+Math.PI);
	this.x2 = (this.x_orig+this.width_orig)/2 + (this.width_orig/2) * Math.cos(this.t/this.period);
	this.x=Math.min(this.x1,this.x2);
	this.width=Math.abs(this.x1-this.x2);
	this.t++;
	if(this.t/this.period>2*Math.PI){
		this.t=0;
	}
};

coin.prototype.collide = function(p){
	money++;
	moneyText.text = "Money: "+money+"€";
	this.death();
}

coin.prototype.death = function(){
	elements.splice(elements.indexOf(this),1);
	player.removeCollisionCheck(this);
}

coin.prototype.draw = function(context,t){
	if(this.x1>this.x2){
		context.drawImage(this.img_mirror,
		 t.tX(this.x), t.tY(this.y)-this.height, this.width, this.height);
	}else{
		context.drawImage(this.img,
		 t.tX(this.x), t.tY(this.y)-this.height, this.width, this.height);
	}
};

//=============================================
//       potion

potion=function(x, y){
	this.x = x;
	this.y = y;
	this.img = loadImage("potion.png");
	that = this;
	this.img.onload = function(){
		that.width = this.width;
		that.height = this.height;
	}
};

potion.prototype.logic = function(){
};

potion.prototype.collide = function(p){
	life++;
	lifeText.text= "Life: "+life;
	this.death();
}

potion.prototype.death = function(){
	elements.splice(elements.indexOf(this),1);
	player.removeCollisionCheck(this);
}

potion.prototype.draw = function(context,t){
	context.drawImage(this.img,
		 t.tX(this.x), t.tY(this.y));
};
<commit_msg>felho elso megjelenesekor random kezdofazis<commit_after>//===============================================
//					CloudObject

cloudObject = function(){
	this.x = this.y = 0;
	this.alpha = 0;
	this.alpha_max = 0;
	this.t = 0;
	this.lifePeriod = 2;
	this.velocity_x = 0;

	this.img = loadImage("../../game/pictures/mistic_cloud.png");

	this.img.parent = this;
	this.img.onload = function(){
		this.parent.width = this.width;
		this.parent.height = this.height;
		this.parent.respawn(Math.random()*Math.PI*2);//Kezdőfázist adunk neki
	}
};

cloudObject.prototype.respawn = function(startPhase){
	this.alpha = 0;
	this.alpha_max = 0.3 + Math.random() * 0.5;
	this.t = 0;
	this.lifePeriod = 5 + Math.random() * 20;
	this.velocity_x = 0.2 + Math.random() * 1;
	this.fazis_a = startPhase+Math.PI;

	var x1 = kameraT.x - 600 - this.width;
	var x2 = kameraT.x + this.width/2;

	var y1 = kameraT.y + this.height/2;
	var y2 = kameraT.y -300 - this.height/2;
	var y_min = 0 + this.height;

	if(y2 < y_min){
		y2 = y_min;
	}

	this.x = x1+Math.random()*(x2-x1);
	this.y = y2+Math.random()*(y1-y2);
}

cloudObject.prototype.logic = function(){
	this.t ++;
	this.x += this.velocity_x;

	var atlag_a     = this.alpha_max/2;
	var amplitudo_a = this.alpha_max/2;
	var periodus_a  = (2*Math.PI)*this.lifePeriod;

	this.alpha = atlag_a + amplitudo_a * Math.cos(this.fazis_a+this.t/periodus_a);

	if(this.t/periodus_a > 2*Math.PI){
		this.respawn(0);//Kezdőfázisa 0
	}
};

cloudObject.prototype.draw = function(context, t){
	context.globalAlpha = this.alpha;
	context.drawImage(this.img, t.tX(this.x), t.tY(this.y));
	context.globalAlpha = 1;

	/*	A képernyő kereteihez képest 10px-el "beljebb lévő" téglalap rajzolása
	var x1 = kameraT.x - 600 + 10;
	var x2 = kameraT.x -10;

	var y1 = kameraT.y -10 ;
	var y2 = kameraT.y - 300 +10;
	context.fillStyle = '#00FF00';
	context.fillRect(t.tX(x1), t.tY(y1), x2-x1, y1-y2);
	*/

};

//===============================================
//					Transformation

transformation = function(){
	this.x=0;
	this.y=0;
	this.ay=1;
	this.ax=1;
};

transformation.prototype.tX=function(x){
	return this.ax*x+this.x;
};

transformation.prototype.tY=function(y){
	return this.ay*y+this.y;
};

//===============================================
//					Thing

thing = function(x, y, z, pic){
	this.x = x;
	this.y = y;
	this.z = z;
	//console.log("loading iamge: "+pic);
	this.img = loadImage("../../game/pictures/"+pic+".png");
	this.width = this.img.width;
	this.height = this.img.height;
};

thing.prototype.logic = function(){};

thing.prototype.draw = function(context, t){
	context.drawImage(this.img,
		 t.tX(this.x), t.tY(this.y));
};

//===============================================
//					Spikes

spike = function(x, y, width, height){
	var correcty = 10;
	this.a = 104/236;
	this.x = x;
	this.y = y-correcty;
	this.img = loadImage("rock_spike_3.png");
	this.width = width;//this.img.width;//104
	this.height = height+correcty;//this.img.height;//236
	player.addCollisionCheck(this);

	/*
	var obj = thing.apply(this, x, y, 0, "rock_spike_2");
	obj.width = obj.img.width;
	obj.height = obj.img.height;
	return obj;
	*/
};

//spike.prototype = new thing();

spike.prototype.collide = function(p){
	p.death();
};

spike.prototype.logic = function(){};

spike.prototype.draw = function(context, t){
	var count = Math.round(this.width/(this.a*this.height));

	//console.log(count);
	if(count < 1){
		count=1;
	}
		var width_c = this.width/count;

		for(var i=0; i<count; i++){
			context.drawImage(this.img,
				 t.tX(this.x+i*width_c), t.tY(this.y)-this.height, width_c, this.height);
		}
};

//===============================================
//				Platform

platform = function(x, y, width){
	this.x = x;
	this.y = y;
	this.width = width;
};

platform.prototype.logic = function(){};

platform.prototype.draw = function(context, t){
	context.fillStyle = "black";
	context.fillRect(t.tX(this.x), t.tY(this.y), this.width, 5);
};

//===============================================
//				text

text = function(text, x, y, conext, font){
	this.text = text;
	this.x = x;
	this.y = y;
	this.width = 0;
	this.height = 0;
	this.font = font;
	if(font){
		tmp = context.font;
		context.font = font;
		this.width = context.measureText(text).width;
		this.height = context.measureText(text).height;
		conext.font = tmp;
	}else{
		this.width = context.measureText(text).width;
		this.height = context.measureText(text).height;
	}
};

text.prototype.setText = function(newText){
	this.text = newText;
	/*
	ctx.font="30px Arial";
	var txt="Hello World"
	ctx.fillText("width:" + ctx.measureText(txt).width,10,50)
	*/
}

text.prototype.logic=function(){
};

text.prototype.draw = function(context, t){
	context.fillText(this.text, this.x, this.y);
	//context.fillText("Szig szakkör játéka!", 600/2-40, 20);
};

//=============================================
//       Mushroom

mushroom=function(){
	this.x0=450;
	this.y=0;
	this.x1=750;
	this.x=this.x0;
	this.speed=1;
	this.width=40;
	this.height=40;
	this.img = loadImage("gomba.png");
};
mushroom.prototype.logic=function(){
	if(this.x<=this.x1 && this.x>=this.x0)
	{
		this.x+=this.speed;
	}else
	{
		if(this.x0>this.x)
		{
			this.x=this.x0;
		}else
		{
			this.x=this.x1;
		}
		this.speed*=-1;
	}
};

mushroom.prototype.collide = function(p){
	if(p.prevY>this.y + this.height) {
		this.death();
	}else {
		p.death();
	}
}

mushroom.prototype.death = function(){
	elements.splice(elements.indexOf(this),1);
	player.removeCollisionCheck(this);
}

mushroom.prototype.draw=function(context,t){
	context.drawImage(this.img,
		 t.tX(this.x), t.tY(this.y+2)-this.height+Math.sin(clock/2.0)*2);
};

//=============================================
//       coin

coin=function(x, y){
	this.x_orig = x;
	this.x1 = x;
	this.x2 = x + 40;
	this.y = this.y_orig = y;
	this.width_orig=40;
	this.height=40;
	this.img = loadImage("coin.png");
	this.img_mirror=loadImage("coin_m.png");
	this.t=0;
	this.period= (2*Math.PI)*2;
	//player.addCollisionCheck(this);
};

coin.prototype.logic = function(){
	this.x1 = (this.x_orig+this.width_orig)/2 + (this.width_orig/2) * Math.cos((this.t/this.period)+Math.PI);
	this.x2 = (this.x_orig+this.width_orig)/2 + (this.width_orig/2) * Math.cos(this.t/this.period);
	this.x=Math.min(this.x1,this.x2);
	this.width=Math.abs(this.x1-this.x2);
	this.t++;
	if(this.t/this.period>2*Math.PI){
		this.t=0;
	}
};

coin.prototype.collide = function(p){
	money++;
	moneyText.text = "Money: "+money+"€";
	this.death();
}

coin.prototype.death = function(){
	elements.splice(elements.indexOf(this),1);
	player.removeCollisionCheck(this);
}

coin.prototype.draw = function(context,t){
	if(this.x1>this.x2){
		context.drawImage(this.img_mirror,
		 t.tX(this.x), t.tY(this.y)-this.height, this.width, this.height);
	}else{
		context.drawImage(this.img,
		 t.tX(this.x), t.tY(this.y)-this.height, this.width, this.height);
	}
};

//=============================================
//       potion

potion=function(x, y){
	this.x = x;
	this.y = y;
	this.img = loadImage("potion.png");
	that = this;
	this.img.onload = function(){
		that.width = this.width;
		that.height = this.height;
	}
};

potion.prototype.logic = function(){
};

potion.prototype.collide = function(p){
	life++;
	lifeText.text= "Life: "+life;
	this.death();
}

potion.prototype.death = function(){
	elements.splice(elements.indexOf(this),1);
	player.removeCollisionCheck(this);
}

potion.prototype.draw = function(context,t){
	context.drawImage(this.img,
		 t.tX(this.x), t.tY(this.y));
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var marked = require('marked');
var utils = require('./utils');

var validFileRegex = /\.[\w]+$/;
var firstLineRegex = /^[\n\r]?([^\n\r]+)/;
var trailingNewline = /[\n\r]+$/;

var forwardReferenceSections = {};

var tags = {

  /**
   * Add a new section to the style guide.
   *
   * The @section tag can define the section name, otherwise the first line of the
   * description will be used as the section name.
   *
   * @example
      /**
       * My Section
       *
       * A description of the section and how to use it.
       *
       * @section
       *\/

       /**
       * A description of the section and how to use it.
       *
       * @section My Section
       *\/
   */
  section: function () {
    var name, description;

    if (!this.tag.description && !this.comment.description) {
      throw new SyntaxError('unnamed section (' + this.file + ':' +
        (this.tag.line+1) + ')');
    }

    // @section did not define the name so use the first line of the comment
    // description as the section name and use the rest as the section description
    if (!this.tag.description) {
      name = this.comment.description.match(firstLineRegex)[1];
      description = this.comment.description.substr(name.length + 1);
    }

    // @section defined the name so use the comment description as the section
    // description
    else {
      name = this.tag.description;
      description = this.comment.description;
    }

    this.block.name = name;
    this.block.description = marked(description).replace(trailingNewline, '');
    this.block.id = utils.getId(name);
    this.block.depth = 1;  // start sections as H1 until sectionof is encountered
    this.block.isSection = true;

    // we're going to cheat and make an array have object like indices so we
    // have quick access to sections by their name and still have an ordered list
    // that we can use in the template
    this.sections.push(this.block);

    // add any children from forward referenced sectionof
    if (forwardReferenceSections[name]) {
      this.block.children = [];

      forwardReferenceSections[name].forEach(function(section) {
        this.block.children.push(section.block);
      }.bind(this));

      delete forwardReferenceSections[name];
    }

    // look to see if this section defines a sectionof so we can create a named
    // hierarchy. Can define multiple sectionof tags on one block. Unfortunately
    // this means we have to loop over the tags twice
    var sectionofTag, sectionofName;
    this.comment.tags.forEach(function(tag) {
      if (tag.tag === 'sectionof') {
        sectionofTag = tag;
        sectionofName = tag.description + '.' + name;

        if (this.sections[sectionofName]) {
          throw new SyntaxError('section \'' + this.block.name +
            '\' has already been declared within the section \'' +
            sectionofTag.description + '\' (' + this.file + ':' +
            (sectionofTag.line+1) + ')');
        }

        this.sections[sectionofName] = this.block;

        // also add the normalized name for case insensitivity
        this.sections[ utils.normalizeName(sectionofName) ] = this.block;
      }
    }.bind(this));

    if (!sectionofTag) {
      this.sections[name] = this.block;

      // also add the normalized name for case insensitivity
      this.sections[ utils.normalizeName(name) ] = this.block;
    }
  },

  /**
   * Add a section as a child of another section.
   *
   * @example
      /**
       * A description of the parent section.
       *
       * @section Parent Section
       *\/

      /**
       * A description of the child section.
       *
       * @section Child Section
       * @sectionof Parent Section
       *\/
   */
  sectionof: function() {
    if (!this.tag.description) {
      throw new SyntaxError('@sectionof must reference a section (' +
        this.file + ':' + (this.tag.line+1) + ')');
    }

    var section = this.sections[this.tag.description];
    this.block.depth = this.tag.description.split('.').length + 1;

    // cap heading levels at 6
    if (this.block.depth > 6) {
      this.block.depth = 6;
    }

    var id = utils.getId(this.tag.description.replace('.', ' '));
    this.block.id = id + '-' + this.block.id;
    this.block.parent = this.tag.description;

    if (section) {
      section.children = section.children || [];
      section.children.push(this.block);
    }

    // forward referenced section
    else {
      forwardReferenceSections[this.tag.description] = forwardReferenceSections[this.tag.description] || [];
      forwardReferenceSections[this.tag.description].push({
        block: this.block,

        // save error so we have line number, file, and correct location
        error: new ReferenceError('section \'' + this.tag.description +
          '\' is not defined (' + this.file + ':' + (this.tag.line+1) + ')')
      });
    }
  },

  /**
   * Assign the section to a page. Each page will be written to a file. Only the
   * root section needs to specify the page as all children will inherit from it.
   * @example
      /**
       * Section belonging to a page.
       *
       * @section Section Name
       * @page Page Name
       *\/
   */
   page: function() {
    this.block.page = this.tag.description;

    if (this.pages[this.tag.description]) {
      this.pages[this.tag.description].sections.push(this.block);
    }
    else {
      var page = {
        name: this.block.page,
        id: utils.getId(this.block.page),
        sections: [this.block]
      };

      this.pages[this.block.page] = page;

      // also add the normalized name for case insensitivity
      this.pages[ utils.normalizeName(this.block.page) ] = page;

      this.pages.push(page);
    }
   },

  /**
   * Provide an example that will be displayed in the style guide. Can provide a
   * type to change the language for code highlighting. Can also provide a
   * filename to be used as the example.
   * @see http://prismjs.com/#languages-list
   *
   * @example
      /**
       * A simple example.
       *
       * @example
       *
foo

       *\/

      /**
       * An example with a language type.
       *
       * @example {javascript}
       * console.log('foo');
       *\/

      /**
       * An example from a file
       *
       * @example
       * path/to/file.html
       *\/
   */
  example: function() {
    var description = this.tag.description.trimRight();

    if (validFileRegex.test(description)) {
      var resolvedPath = path.resolve(path.dirname(this.file), description);

      try {
        description = fs.readFileSync(resolvedPath, 'utf-8');
      } catch (e) {
        throw new ReferenceError('File not found \'' + resolvedPath + '\' (' +
          this.file + ':' + (this.tag.line+1) + ')');
      }
    }

    this.block[this.tag.tag] = {
      description: description,
      type: this.tag.type || 'markup'
    };

    // default code to use the example only if hideCode hasn't been set
    if (this.tag.tag === 'example' && !this.block.code && !this.block.hideCode) {
      this.block.code = this.block.example
    }

    // replace html encoded at symbol with the actual @ symbol
    // this allows the use of the @ symbol in code examples without the parser
    // trying to parse it as a tag
    // @code
    // .example {
    //   @extend %placeholder-selector;
    // }
    if (this.block.code) {
      this.block.code.description = this.block.code.description.replace('@', '@');
    }
  },

  /**
   * Hide the code output of an example.
   *
   * @example
      /**
       * A simple example.
       *
       * @example
       *
foo

       * @hideCode
       *\/
   */
  hideCode: function() {
    this.block.hideCode = true;

    if (this.block.code) {
      delete this.block.code;
    }
  }
};
tags.code = tags.example;  // @code and @example generate the same structure

module.exports = tags;
module.exports.forwardReferenceSections = forwardReferenceSections;<commit_msg>add back semicolon<commit_after>var fs = require('fs');
var path = require('path');
var marked = require('marked');
var utils = require('./utils');

var validFileRegex = /\.[\w]+$/;
var firstLineRegex = /^[\n\r]?([^\n\r]+)/;
var trailingNewline = /[\n\r]+$/;

var forwardReferenceSections = {};

var tags = {

  /**
   * Add a new section to the style guide.
   *
   * The @section tag can define the section name, otherwise the first line of the
   * description will be used as the section name.
   *
   * @example
      /**
       * My Section
       *
       * A description of the section and how to use it.
       *
       * @section
       *\/

       /**
       * A description of the section and how to use it.
       *
       * @section My Section
       *\/
   */
  section: function () {
    var name, description;

    if (!this.tag.description && !this.comment.description) {
      throw new SyntaxError('unnamed section (' + this.file + ':' +
        (this.tag.line+1) + ')');
    }

    // @section did not define the name so use the first line of the comment
    // description as the section name and use the rest as the section description
    if (!this.tag.description) {
      name = this.comment.description.match(firstLineRegex)[1];
      description = this.comment.description.substr(name.length + 1);
    }

    // @section defined the name so use the comment description as the section
    // description
    else {
      name = this.tag.description;
      description = this.comment.description;
    }

    this.block.name = name;
    this.block.description = marked(description).replace(trailingNewline, '');
    this.block.id = utils.getId(name);
    this.block.depth = 1;  // start sections as H1 until sectionof is encountered
    this.block.isSection = true;

    // we're going to cheat and make an array have object like indices so we
    // have quick access to sections by their name and still have an ordered list
    // that we can use in the template
    this.sections.push(this.block);

    // add any children from forward referenced sectionof
    if (forwardReferenceSections[name]) {
      this.block.children = [];

      forwardReferenceSections[name].forEach(function(section) {
        this.block.children.push(section.block);
      }.bind(this));

      delete forwardReferenceSections[name];
    }

    // look to see if this section defines a sectionof so we can create a named
    // hierarchy. Can define multiple sectionof tags on one block. Unfortunately
    // this means we have to loop over the tags twice
    var sectionofTag, sectionofName;
    this.comment.tags.forEach(function(tag) {
      if (tag.tag === 'sectionof') {
        sectionofTag = tag;
        sectionofName = tag.description + '.' + name;

        if (this.sections[sectionofName]) {
          throw new SyntaxError('section \'' + this.block.name +
            '\' has already been declared within the section \'' +
            sectionofTag.description + '\' (' + this.file + ':' +
            (sectionofTag.line+1) + ')');
        }

        this.sections[sectionofName] = this.block;

        // also add the normalized name for case insensitivity
        this.sections[ utils.normalizeName(sectionofName) ] = this.block;
      }
    }.bind(this));

    if (!sectionofTag) {
      this.sections[name] = this.block;

      // also add the normalized name for case insensitivity
      this.sections[ utils.normalizeName(name) ] = this.block;
    }
  },

  /**
   * Add a section as a child of another section.
   *
   * @example
      /**
       * A description of the parent section.
       *
       * @section Parent Section
       *\/

      /**
       * A description of the child section.
       *
       * @section Child Section
       * @sectionof Parent Section
       *\/
   */
  sectionof: function() {
    if (!this.tag.description) {
      throw new SyntaxError('@sectionof must reference a section (' +
        this.file + ':' + (this.tag.line+1) + ')');
    }

    var section = this.sections[this.tag.description];
    this.block.depth = this.tag.description.split('.').length + 1;

    // cap heading levels at 6
    if (this.block.depth > 6) {
      this.block.depth = 6;
    }

    var id = utils.getId(this.tag.description.replace('.', ' '));
    this.block.id = id + '-' + this.block.id;
    this.block.parent = this.tag.description;

    if (section) {
      section.children = section.children || [];
      section.children.push(this.block);
    }

    // forward referenced section
    else {
      forwardReferenceSections[this.tag.description] = forwardReferenceSections[this.tag.description] || [];
      forwardReferenceSections[this.tag.description].push({
        block: this.block,

        // save error so we have line number, file, and correct location
        error: new ReferenceError('section \'' + this.tag.description +
          '\' is not defined (' + this.file + ':' + (this.tag.line+1) + ')')
      });
    }
  },

  /**
   * Assign the section to a page. Each page will be written to a file. Only the
   * root section needs to specify the page as all children will inherit from it.
   * @example
      /**
       * Section belonging to a page.
       *
       * @section Section Name
       * @page Page Name
       *\/
   */
   page: function() {
    this.block.page = this.tag.description;

    if (this.pages[this.tag.description]) {
      this.pages[this.tag.description].sections.push(this.block);
    }
    else {
      var page = {
        name: this.block.page,
        id: utils.getId(this.block.page),
        sections: [this.block]
      };

      this.pages[this.block.page] = page;

      // also add the normalized name for case insensitivity
      this.pages[ utils.normalizeName(this.block.page) ] = page;

      this.pages.push(page);
    }
   },

  /**
   * Provide an example that will be displayed in the style guide. Can provide a
   * type to change the language for code highlighting. Can also provide a
   * filename to be used as the example.
   * @see http://prismjs.com/#languages-list
   *
   * @example
      /**
       * A simple example.
       *
       * @example
       *
foo

       *\/

      /**
       * An example with a language type.
       *
       * @example {javascript}
       * console.log('foo');
       *\/

      /**
       * An example from a file
       *
       * @example
       * path/to/file.html
       *\/
   */
  example: function() {
    var description = this.tag.description.trimRight();

    if (validFileRegex.test(description)) {
      var resolvedPath = path.resolve(path.dirname(this.file), description);

      try {
        description = fs.readFileSync(resolvedPath, 'utf-8');
      } catch (e) {
        throw new ReferenceError('File not found \'' + resolvedPath + '\' (' +
          this.file + ':' + (this.tag.line+1) + ')');
      }
    }

    this.block[this.tag.tag] = {
      description: description,
      type: this.tag.type || 'markup'
    };

    // default code to use the example only if hideCode hasn't been set
    if (this.tag.tag === 'example' && !this.block.code && !this.block.hideCode) {
      this.block.code = this.block.example;
    }

    // replace html encoded at symbol with the actual @ symbol
    // this allows the use of the @ symbol in code examples without the parser
    // trying to parse it as a tag
    // @code
    // .example {
    //   @extend %placeholder-selector;
    // }
    if (this.block.code) {
      this.block.code.description = this.block.code.description.replace('@', '@');
    }
  },

  /**
   * Hide the code output of an example.
   *
   * @example
      /**
       * A simple example.
       *
       * @example
       *
foo

       * @hideCode
       *\/
   */
  hideCode: function() {
    this.block.hideCode = true;

    if (this.block.code) {
      delete this.block.code;
    }
  }
};
tags.code = tags.example;  // @code and @example generate the same structure

module.exports = tags;
module.exports.forwardReferenceSections = forwardReferenceSections;<|endoftext|>