<commit_before>pc.extend(pc, function () {
    var tmpVecA = new pc.Vec3();
    var tmpVecB = new pc.Vec3();
    var tmpVecC = new pc.Vec3();
    var tmpVecD = new pc.Vec3();
    var tmpVecE = new pc.Vec3();
    var tmpVecF = new pc.Vec3();

    /**
     * @name pc.BoundingBox
     * @description Create a new axis-aligned bounding box
     * @class Axis-Aligned Bounding Box
     * @param {pc.Vec3} center - center of box
     * @param {pc.Vec3} halfExtents - half the distance across the box in each axis
     */
    var BoundingBox = function BoundingBox(center, halfExtents) {
        this.center = center || new pc.Vec3(0, 0, 0);
        this.halfExtents = halfExtents || new pc.Vec3(0.5, 0.5, 0.5);
    };

    BoundingBox.prototype = {
        add: function (other) {
            var tc = this.center;
            var th = this.halfExtents;
            var tminx = tc.x - th.x;
            var tmaxx = tc.x + th.x;
            var tminy = tc.y - th.y;
            var tmaxy = tc.y + th.y;
            var tminz = tc.z - th.z;
            var tmaxz = tc.z + th.z;
            var oc = other.center;
            var oh = other.halfExtents;
            var ominx = oc.x - oh.x;
            var omaxx = oc.x + oh.x;
            var ominy = oc.y - oh.y;
            var omaxy = oc.y + oh.y;
            var ominz = oc.z - oh.z;
            var omaxz = oc.z + oh.z;
            if (ominx < tminx) tminx = ominx;
            if (omaxx > tmaxx) tmaxx = omaxx;
            if (ominy < tminy) tminy = ominy;
            if (omaxy > tmaxy) tmaxy = omaxy;
            if (ominz < tminz) tminz = ominz;
            if (omaxz > tmaxz) tmaxz = omaxz;
            tc.set(tminx + tmaxx, tminy + tmaxy, tminz + tmaxz).scale(0.5);
            th.set(tmaxx - tminx, tmaxy - tminy, tmaxz - tminz).scale(0.5);
        },

        copy: function (src) {
            this.center.copy(src.center);
            this.halfExtents.copy(src.halfExtents);
            this.type = src.type;
        },

        /**
         * @function
         * @name pc.BoundingBox#intersects
         * @description Test whether two axis-aligned bounding boxes intersect.
         * @param {pc.BoundingBox} other Bounding box to test against
         * @returns {Boolean} True if there is an intersection
         */
        intersects: function (other) {
            var aMax = this.getMax();
            var aMin = this.getMin();
            var bMax = other.getMax();
            var bMin = other.getMin();

            return (aMin.x <= bMax.x) && (aMax.x >= bMin.x) &&
                   (aMin.y <= bMax.y) && (aMax.y >= bMin.y) &&
                   (aMin.z <= bMax.z) && (aMax.z >= bMin.z);
        },

        intersectsRay: function (ray) {
            var diff = tmpVecA;
            var cross = tmpVecB;
            var prod = tmpVecC;
            var absDiff = tmpVecD;
            var absDir = tmpVecE;
            var rayDir = tmpVecF.copy(ray.direction).normalize();
            var i;

            diff.sub2(ray.origin, aabb.center);
            absDiff.set(Math.abs(diff.x), Math.abs(diff.y), Math.abs(diff.z));

            prod.mul2(diff, rayDir);

            if (absDiff.x > aabb.halfExtents.x && prod.x >= 0)
                return false;

            if (absDiff.y > aabb.halfExtents.y && prod.y >= 0)
                return false;

            if (absDiff.z > aabb.halfExtents.z && prod.z >= 0)
                return false;

            absDir.set(Math.abs(rayDir.x), Math.abs(rayDir.y), Math.abs(rayDir.z));
            cross.cross(rayDir, diff);
            cross.set(Math.abs(cross.x), Math.abs(cross.y), Math.abs(cross.z));

            if (cross.x > aabb.halfExtents.y*absDir.z + aabb.halfExtents.z*absDir.y)
                return false;

            if (cross.y > aabb.halfExtents.x*absDir.z + aabb.halfExtents.z*absDir.x)
                return false;

            if (cross.z > aabb.halfExtents.x*absDir.y + aabb.halfExtents.y*absDir.x)
                return false;

            return true;
        },

        setMinMax: function (min, max) {
            this.center.add2(max, min).scale(0.5);
            this.halfExtents.sub2(max, min).scale(0.5);
        },

        /**
         * @function
         * @name pc.BoundingBox#getMin
         * @description Return the minimum corner of the AABB.
         * @returns {pc.Vec3} minimum corner
         */
        getMin: function () {
            return this.center.clone().sub(this.halfExtents);
        },

        /**
         * @function
         * @name pc.BoundingBox#getMax
         * @description Return the maximum corner of the AABB.
         * @returns {pc.Vec3} maximum corner
         */
        getMax: function () {
            return this.center.clone().add(this.halfExtents);
        },

        /**
         * @function
         * @name pc.BoundingBox#containsPoint
         * @description Test if a point is inside a AABB
         * @param {pc.Vec3} point Point to test
         * @returns {Boolean} true if the point is inside the AABB and false otherwise
         */
        containsPoint: function (point) {
            var min = this.getMin();
            var max = this.getMax();
            var i;

            for (i = 0; i < 3; ++i) {
                if (point.data[i] < min.data[i] || point.data[i] > max.data[i])
                    return false;
            }

            return true;
        },

        /**
         * @function
         * @name pc.BoundingBox#setFromTransformedAabb
         * @description Set an AABB to enclose the specified AABB if it were to be
         * transformed by the specified 4x4 matrix.
         * @param {pc.BoundingBox} aabb Box to transform and enclose
         * @param {pc.Mat4} m Transformation matrix to apply to source AABB.
         */
        setFromTransformedAabb: function (aabb, m) {
            var bc = this.center;
            var br = this.halfExtents;
            var ac = aabb.center.data;
            var ar = aabb.halfExtents.data;

            m = m.data;
            var mx0 = m[0];
            var mx1 = m[4];
            var mx2 = m[8];
            var my0 = m[1];
            var my1 = m[5];
            var my2 = m[9];
            var mz0 = m[2];
            var mz1 = m[6];
            var mz2 = m[10];

            var mx0a = Math.abs(mx0);
            var mx1a = Math.abs(mx1);
            var mx2a = Math.abs(mx2);
            var my0a = Math.abs(my0);
            var my1a = Math.abs(my1);
            var my2a = Math.abs(my2);
            var mz0a = Math.abs(mz0);
            var mz1a = Math.abs(mz1);
            var mz2a = Math.abs(mz2);

            bc.set(
                m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2],
                m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2],
                m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2]
            );

            br.set(
                mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2],
                my0a * ar[0] + my1a * ar[1] + my2a * ar[2],
                mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2]
            );
        },

        compute: function (vertices) {
            var min = tmpVecA.set(vertices[0], vertices[1], vertices[2]);
            var max = tmpVecB.set(vertices[0], vertices[1], vertices[2]);
            var numVerts = vertices.length / 3;

            for (var i = 1; i < numVerts; i++) {
                var x = vertices[i * 3 + 0];
                var y = vertices[i * 3 + 1];
                var z = vertices[i * 3 + 2];
                if (x < min.x) min.x = x;
                if (y < min.y) min.y = y;
                if (z < min.z) min.z = z;
                if (x > max.x) max.x = x;
                if (y > max.y) max.y = y;
                if (z > max.z) max.z = z;
            }

            this.setMinMax(min, max);
        }
    };

    return {
        BoundingBox: BoundingBox
    };
}());
<commit_msg>remove vector cloning in getMin/getMax of bounding box<commit_after>pc.extend(pc, function () {
    var tmpVecA = new pc.Vec3();
    var tmpVecB = new pc.Vec3();
    var tmpVecC = new pc.Vec3();
    var tmpVecD = new pc.Vec3();
    var tmpVecE = new pc.Vec3();
    var tmpVecF = new pc.Vec3();

    /**
     * @name pc.BoundingBox
     * @description Create a new axis-aligned bounding box
     * @class Axis-Aligned Bounding Box
     * @param {pc.Vec3} center - center of box
     * @param {pc.Vec3} halfExtents - half the distance across the box in each axis
     */
    var BoundingBox = function BoundingBox(center, halfExtents) {
        this.center = center || new pc.Vec3(0, 0, 0);
        this.halfExtents = halfExtents || new pc.Vec3(0.5, 0.5, 0.5);
        this._min = new pc.Vec3();
        this._max = new pc.Vec3();
    };

    BoundingBox.prototype = {
        add: function (other) {
            var tc = this.center;
            var th = this.halfExtents;
            var tminx = tc.x - th.x;
            var tmaxx = tc.x + th.x;
            var tminy = tc.y - th.y;
            var tmaxy = tc.y + th.y;
            var tminz = tc.z - th.z;
            var tmaxz = tc.z + th.z;
            var oc = other.center;
            var oh = other.halfExtents;
            var ominx = oc.x - oh.x;
            var omaxx = oc.x + oh.x;
            var ominy = oc.y - oh.y;
            var omaxy = oc.y + oh.y;
            var ominz = oc.z - oh.z;
            var omaxz = oc.z + oh.z;
            if (ominx < tminx) tminx = ominx;
            if (omaxx > tmaxx) tmaxx = omaxx;
            if (ominy < tminy) tminy = ominy;
            if (omaxy > tmaxy) tmaxy = omaxy;
            if (ominz < tminz) tminz = ominz;
            if (omaxz > tmaxz) tmaxz = omaxz;
            tc.set(tminx + tmaxx, tminy + tmaxy, tminz + tmaxz).scale(0.5);
            th.set(tmaxx - tminx, tmaxy - tminy, tmaxz - tminz).scale(0.5);
        },

        copy: function (src) {
            this.center.copy(src.center);
            this.halfExtents.copy(src.halfExtents);
            this.type = src.type;
        },

        /**
         * @function
         * @name pc.BoundingBox#intersects
         * @description Test whether two axis-aligned bounding boxes intersect.
         * @param {pc.BoundingBox} other Bounding box to test against
         * @returns {Boolean} True if there is an intersection
         */
        intersects: function (other) {
            var aMax = this.getMax();
            var aMin = this.getMin();
            var bMax = other.getMax();
            var bMin = other.getMin();

            return (aMin.x <= bMax.x) && (aMax.x >= bMin.x) &&
                   (aMin.y <= bMax.y) && (aMax.y >= bMin.y) &&
                   (aMin.z <= bMax.z) && (aMax.z >= bMin.z);
        },

        intersectsRay: function (ray) {
            var diff = tmpVecA;
            var cross = tmpVecB;
            var prod = tmpVecC;
            var absDiff = tmpVecD;
            var absDir = tmpVecE;
            var rayDir = tmpVecF.copy(ray.direction).normalize();
            var i;

            diff.sub2(ray.origin, aabb.center);
            absDiff.set(Math.abs(diff.x), Math.abs(diff.y), Math.abs(diff.z));

            prod.mul2(diff, rayDir);

            if (absDiff.x > aabb.halfExtents.x && prod.x >= 0)
                return false;

            if (absDiff.y > aabb.halfExtents.y && prod.y >= 0)
                return false;

            if (absDiff.z > aabb.halfExtents.z && prod.z >= 0)
                return false;

            absDir.set(Math.abs(rayDir.x), Math.abs(rayDir.y), Math.abs(rayDir.z));
            cross.cross(rayDir, diff);
            cross.set(Math.abs(cross.x), Math.abs(cross.y), Math.abs(cross.z));

            if (cross.x > aabb.halfExtents.y*absDir.z + aabb.halfExtents.z*absDir.y)
                return false;

            if (cross.y > aabb.halfExtents.x*absDir.z + aabb.halfExtents.z*absDir.x)
                return false;

            if (cross.z > aabb.halfExtents.x*absDir.y + aabb.halfExtents.y*absDir.x)
                return false;

            return true;
        },

        setMinMax: function (min, max) {
            this.center.add2(max, min).scale(0.5);
            this.halfExtents.sub2(max, min).scale(0.5);
        },

        /**
         * @function
         * @name pc.BoundingBox#getMin
         * @description Return the minimum corner of the AABB.
         * @returns {pc.Vec3} minimum corner
         */
        getMin: function () {
            return this._min.copy(this.center).sub(this.halfExtents);
        },

        /**
         * @function
         * @name pc.BoundingBox#getMax
         * @description Return the maximum corner of the AABB.
         * @returns {pc.Vec3} maximum corner
         */
        getMax: function () {
            return this._max.copy(this.center).add(this.halfExtents);
        },

        /**
         * @function
         * @name pc.BoundingBox#containsPoint
         * @description Test if a point is inside a AABB
         * @param {pc.Vec3} point Point to test
         * @returns {Boolean} true if the point is inside the AABB and false otherwise
         */
        containsPoint: function (point) {
            var min = this.getMin();
            var max = this.getMax();
            var i;

            for (i = 0; i < 3; ++i) {
                if (point.data[i] < min.data[i] || point.data[i] > max.data[i])
                    return false;
            }

            return true;
        },

        /**
         * @function
         * @name pc.BoundingBox#setFromTransformedAabb
         * @description Set an AABB to enclose the specified AABB if it were to be
         * transformed by the specified 4x4 matrix.
         * @param {pc.BoundingBox} aabb Box to transform and enclose
         * @param {pc.Mat4} m Transformation matrix to apply to source AABB.
         */
        setFromTransformedAabb: function (aabb, m) {
            var bc = this.center;
            var br = this.halfExtents;
            var ac = aabb.center.data;
            var ar = aabb.halfExtents.data;

            m = m.data;
            var mx0 = m[0];
            var mx1 = m[4];
            var mx2 = m[8];
            var my0 = m[1];
            var my1 = m[5];
            var my2 = m[9];
            var mz0 = m[2];
            var mz1 = m[6];
            var mz2 = m[10];

            var mx0a = Math.abs(mx0);
            var mx1a = Math.abs(mx1);
            var mx2a = Math.abs(mx2);
            var my0a = Math.abs(my0);
            var my1a = Math.abs(my1);
            var my2a = Math.abs(my2);
            var mz0a = Math.abs(mz0);
            var mz1a = Math.abs(mz1);
            var mz2a = Math.abs(mz2);

            bc.set(
                m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2],
                m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2],
                m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2]
            );

            br.set(
                mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2],
                my0a * ar[0] + my1a * ar[1] + my2a * ar[2],
                mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2]
            );
        },

        compute: function (vertices) {
            var min = tmpVecA.set(vertices[0], vertices[1], vertices[2]);
            var max = tmpVecB.set(vertices[0], vertices[1], vertices[2]);
            var numVerts = vertices.length / 3;

            for (var i = 1; i < numVerts; i++) {
                var x = vertices[i * 3 + 0];
                var y = vertices[i * 3 + 1];
                var z = vertices[i * 3 + 2];
                if (x < min.x) min.x = x;
                if (y < min.y) min.y = y;
                if (z < min.z) min.z = z;
                if (x > max.x) max.x = x;
                if (y > max.y) max.y = y;
                if (z > max.z) max.z = z;
            }

            this.setMinMax(min, max);
        }
    };

    return {
        BoundingBox: BoundingBox
    };
}());
<|endoftext|>


<commit_before>import { graphql } from "gatsby";
import Projects from "../components/projects";

export default Projects;

export const query = graphql`
  query($tag: [String]) {
    tags: allMarkdownRemark(
      filter: { fields: { slug: { regex: "//projects//" } } }
    ) {
      group(field: frontmatter___tags) {
        fieldValue
        totalCount
      }
    }
    projects: allMarkdownRemark(
      filter: {
        fields: { slug: { regex: "//projects//" } }
        frontmatter: { tags: { in: $tag } }
      }
      sort: { fields: [frontmatter___date], order: DESC }
    ) {
      nodes {
        id
        frontmatter {
          title
          date
          description
          tags
          source
          demo
          image {
            childImageSharp {
              fluid(maxWidth: 500, quality: 100) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
        fields {
          slug
        }
      }
    }
  }
`;
<commit_msg>fix: Limit project image size<commit_after>import { graphql } from "gatsby";
import Projects from "../components/projects";

export default Projects;

export const query = graphql`
  query($tag: [String]) {
    tags: allMarkdownRemark(
      filter: { fields: { slug: { regex: "//projects//" } } }
    ) {
      group(field: frontmatter___tags) {
        fieldValue
        totalCount
      }
    }
    projects: allMarkdownRemark(
      filter: {
        fields: { slug: { regex: "//projects//" } }
        frontmatter: { tags: { in: $tag } }
      }
      sort: { fields: [frontmatter___date], order: DESC }
    ) {
      nodes {
        id
        frontmatter {
          title
          date
          description
          tags
          source
          demo
          image {
            childImageSharp {
              fluid(maxWidth: 500, maxHeight: 500, quality: 100) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
        fields {
          slug
        }
      }
    }
  }
`;
<|endoftext|>


<commit_before>import BaseDisplay from './BaseDisplay';
import { getColors } from '../utils/display-utils';

const definitions = {
  threshold: {
    type: 'float',
    default: null,
    nullable: true,
    metas: { kind: 'dynamic' },
  },
  thresholdIndex: {
    type: 'integer',
    default: 0,
    metas: { kind: 'dynamic' },
  },
  color: {
    type: 'string',
    default: getColors('marker'),
    nullable: true,
    metas: { kind: 'dynamic' },
  }
};

/**
 * Display a marker according to the input frame.
 *
 * @memberof module:sink
 *
 * @param {String} options.color - Color of the marker.
 * @param {Number} [options.thresholdIndex=0] - Index of the incomming frame
 *  data to compare against the threshold. _Should be used in conjonction with
 *  `threshold`_.
 * @param {Number} [options.threshold=null] - Minimum value the incomming value
 *  must have to trigger the display of a marker. If null each incomming event
 *  triggers a marker. _Should be used in conjonction with `thresholdIndex`_.
 *
 * @example
 * import * as lfo from 'waves-lfo';
 *
 * const eventIn = new lfo.source.EventIn({
 *   frameType: 'scalar',
 * });
 *
 * const marker = new lfo.sink.MarkerDisplay({
 *   canvas: '#marker',
 * });
 *
 * eventIn.connect(marker);
 * eventIn.start();
 *
 * let time = 0;
 * const period = 1;
 *
 * (function generateData() {
 *   eventIn.process(time, Math.random());
 *
 *   time += period;
 *   setTimeout(generateData, period * 1000);
 * }());
 */
class MarkerDisplay extends BaseDisplay {
  constructor(options = {}) {
    super(definitions, options);
  }

  /** @private */
  processVector(frame, frameWidth, pixelsSinceLastFrame) {
    const color = this.params.get('color');
    const threshold = this.params.get('threshold');
    const thresholdIndex = this.params.get('thresholdIndex');
    const ctx = this.ctx;
    const height = ctx.height;
    const value = frame.data[thresholdIndex];

    if (threshold === null || value >= threshold) {
      let yMin = this.getYPosition(this.params.get('min'));
      let yMax = this.getYPosition(this.params.get('max'));

      if (yMin > yMax) {
        const v = yMax;
        yMax = yMin;
        yMin = v;
      }

      ctx.save();
      ctx.fillStyle = color;
      ctx.fillRect(0, yMin, 1, yMax);
      ctx.restore();
    }
  }
}

export default MarkerDisplay;
<commit_msg>updated doc<commit_after>import BaseDisplay from './BaseDisplay';
import { getColors } from '../utils/display-utils';

const definitions = {
  threshold: {
    type: 'float',
    default: null,
    nullable: true,
    metas: { kind: 'dynamic' },
  },
  thresholdIndex: {
    type: 'integer',
    default: 0,
    metas: { kind: 'dynamic' },
  },
  color: {
    type: 'string',
    default: getColors('marker'),
    nullable: true,
    metas: { kind: 'dynamic' },
  }
};

/**
 * Display a marker according to the input frame.
 *
 * @memberof module:sink
 *
 * @param {String} options.color - Color of the marker.
 * @param {Number} [options.thresholdIndex=0] - Index of the incomming frame
 *  data to compare against the threshold. _Should be used in conjonction with
 *  `threshold`_.
 * @param {Number} [options.threshold=null] - Minimum value the incomming value
 *  must have to trigger the display of a marker. If null each incomming event
 *  triggers a marker. _Should be used in conjonction with `thresholdIndex`_.
 * @param {Object} options - Override default parameters.
 * @param {Number} [options.width=300] - Width of the canvas.
 *  _dynamic parameter_
 * @param {Number} [options.height=150] - Height of the canvas.
 *  _dynamic parameter_
 * @param {Element|CSSSelector} [options.container=null] - Container element
 *  in which to insert the canvas. _constant parameter_
 * @param {Element|CSSSelector} [options.canvas=null] - Canvas element
 *  in which to draw. _constant parameter_
 * @param {Number} [options.duration=1] - Duration (in seconds) represented in
 *  the canvas. This parameter only exists for operators that display several
 *  consecutive frames on the canvas. _dynamic parameter_
 * @param {Number} [options.referenceTime=null] - Optionnal reference time the
 *  display should considerer as the origin. Is only usefull when synchronizing
 *  several display using the `DisplaySync` class. This parameter only exists
 *  for operators that display several consecutive frames on the canvas.
 *
 * @example
 * import * as lfo from 'waves-lfo';
 *
 * const eventIn = new lfo.source.EventIn({
 *   frameType: 'scalar',
 * });
 *
 * const marker = new lfo.sink.MarkerDisplay({
 *   canvas: '#marker',
 *   threshold: 0.5,
 * });
 *
 * eventIn.connect(marker);
 * eventIn.start();
 *
 * let time = 0;
 * const period = 1;
 *
 * (function generateData() {
 *   eventIn.process(time, Math.random());
 *
 *   time += period;
 *   setTimeout(generateData, period * 1000);
 * }());
 */
class MarkerDisplay extends BaseDisplay {
  constructor(options = {}) {
    super(definitions, options);
  }

  /** @private */
  processVector(frame, frameWidth, pixelsSinceLastFrame) {
    const color = this.params.get('color');
    const threshold = this.params.get('threshold');
    const thresholdIndex = this.params.get('thresholdIndex');
    const ctx = this.ctx;
    const height = ctx.height;
    const value = frame.data[thresholdIndex];

    if (threshold === null || value >= threshold) {
      let yMin = this.getYPosition(this.params.get('min'));
      let yMax = this.getYPosition(this.params.get('max'));

      if (yMin > yMax) {
        const v = yMax;
        yMax = yMin;
        yMin = v;
      }

      ctx.save();
      ctx.fillStyle = color;
      ctx.fillRect(0, yMin, 1, yMax);
      ctx.restore();
    }
  }
}

export default MarkerDisplay;
<|endoftext|>


<commit_before>import * as system from './support/system';

var playerBank = {
  headText: 'Bank',
  appLink: true,
  depoPos: 2,
  balPos: 1,
  data: {
    cmd: 'bank',
    subcmd: 'transaction'
  },
  initWithdraw: ''
};
var guildBank = {
  headText: 'Guild Bank',
  appLink: false,
  depoPos: 3,
  balPos: 2,
  data: {
    cmd: 'guild',
    subcmd: 'bank',
    subcmd2: 'transaction'
  },
  initWithdraw: '1'
};
var bankSettings;

function transResponse(response) { // jQuery
  var doc = system.createDocument(response);
  var infoBox = $('#pCC #info-msg', doc);
  if (infoBox.length === 0) {return;}
  var target = $('#pCC #info-msg');
  if (target.length === 0) {
    $('#pCC').prepend(infoBox.closest('table'));
  } else {
    target.closest('table').replaceWith(infoBox.closest('table'));
  }
  $('#pH #statbar-gold').text($('#pH #statbar-gold', doc).text());
  $('#pH #statbar-gold-tooltip-general dd').text(function(index) {
    return $('#pH #statbar-gold-tooltip-general dd', doc).eq(index).text();
  });
  var o = bankSettings;
  $('#pCC b').slice(o.balPos).text(function(index) {
    return $('#pCC b', doc).slice(o.balPos).eq(index).text();
  });
  if ($('#pCC b').eq(o.depoPos).text() === '0') {
    $('#pCC input[value="Deposit"]').prop('disabled', true);
  }
  $('#pCC #deposit_amount').val($('#pCC #deposit_amount', doc).val());
  $('#pCC #withdraw_amount').val(o.initWithdraw);
}

function bankDeposit(e) { // jQuery
  e.preventDefault();
  var o = bankSettings;
  var amount = $('#pCC #deposit_amount').val();
  if ($('#pCC b').eq(o.depoPos).text() === '0' || !$.isNumeric(amount) ||
    amount < 1) {return;}
  o.data.mode = 'deposit';
  o.data.deposit_amount = amount;
  $.get('index.php', o.data).done(transResponse);
}

function bankWithdrawal(e) { // jQuery
  e.preventDefault();
  var o = bankSettings;
  var amount = $('#pCC #withdraw_amount').val();
  if (!$.isNumeric(amount) || amount < 1) {return;}
  o.data.mode = 'withdraw';
  o.data.withdraw_amount = amount;
  $.get('index.php', o.data).done(transResponse);
}

function ajaxifyBank() { // jQuery
  var o = bankSettings;
  var bank = $('#pCC b');
  if (bank.length === 0 || bank.eq(0).text() !== o.headText) {return;}
  if (o.appLink) {
    bank.eq(0).closest('tr').after('
' +
      'Go to Guild Bank' +
      '
');
  }
  var depo = $('#pCC input[value="Deposit"]');
  if (depo.length !== 1) {return;}
  var withdraw = $('#pCC input[value="Withdraw"]');
  if (withdraw.length !== 1) {return;}
  if ($('#pCC b').eq(o.depoPos).text() === '0') {
    depo.prop('disabled', true);
  } else {
    depo.click(bankDeposit);
  }
  withdraw.click(bankWithdrawal);
}

export function injectGuildBank() { // Native
  bankSettings = guildBank;
  ajaxifyBank();
}

export function injectBank() { // jQuery
  bankSettings = playerBank;
  ajaxifyBank();
}
<commit_msg>Remember bank depo if 1<commit_after>import * as system from './support/system';

var playerBank = {
  headText: 'Bank',
  appLink: true,
  depoPos: 2,
  balPos: 1,
  data: {
    cmd: 'bank',
    subcmd: 'transaction'
  },
  initWithdraw: ''
};
var guildBank = {
  headText: 'Guild Bank',
  appLink: false,
  depoPos: 3,
  balPos: 2,
  data: {
    cmd: 'guild',
    subcmd: 'bank',
    subcmd2: 'transaction'
  },
  initWithdraw: '1'
};
var bankSettings;

function transResponse(response) { // jQuery
  var doc = system.createDocument(response);
  var infoBox = $('#pCC #info-msg', doc);
  if (infoBox.length === 0) {return;}
  var target = $('#pCC #info-msg');
  if (target.length === 0) {
    $('#pCC').prepend(infoBox.closest('table'));
  } else {
    target.closest('table').replaceWith(infoBox.closest('table'));
  }
  $('#pH #statbar-gold').text($('#pH #statbar-gold', doc).text());
  $('#pH #statbar-gold-tooltip-general dd').text(function(index) {
    return $('#pH #statbar-gold-tooltip-general dd', doc).eq(index).text();
  });
  var o = bankSettings;
  $('#pCC b').slice(o.balPos).text(function(index) {
    return $('#pCC b', doc).slice(o.balPos).eq(index).text();
  });
  if ($('#pCC b').eq(o.depoPos).text() === '0') {
    $('#pCC input[value="Deposit"]').prop('disabled', true);
  }
  if (o.data.deposit_amount !== '1') {
    $('#pCC #deposit_amount').val($('#pCC #deposit_amount', doc).val());
  } else {
    $('#pCC #deposit_amount').val('1');
  }
  $('#pCC #withdraw_amount').val(o.initWithdraw);
}

function bankDeposit(e) { // jQuery
  e.preventDefault();
  var o = bankSettings;
  var amount = $('#pCC #deposit_amount').val();
  if ($('#pCC b').eq(o.depoPos).text() === '0' || !$.isNumeric(amount) ||
    amount < 1) {return;}
  o.data.mode = 'deposit';
  o.data.deposit_amount = amount;
  $.get('index.php', o.data).done(transResponse);
}

function bankWithdrawal(e) { // jQuery
  e.preventDefault();
  var o = bankSettings;
  var amount = $('#pCC #withdraw_amount').val();
  if (!$.isNumeric(amount) || amount < 1) {return;}
  o.data.mode = 'withdraw';
  o.data.withdraw_amount = amount;
  $.get('index.php', o.data).done(transResponse);
}

function ajaxifyBank() { // jQuery
  var o = bankSettings;
  var bank = $('#pCC b');
  if (bank.length === 0 || bank.eq(0).text() !== o.headText) {return;}
  if (o.appLink) {
    bank.eq(0).closest('tr').after('
' +
      'Go to Guild Bank' +
      '
');
  }
  var depo = $('#pCC input[value="Deposit"]');
  if (depo.length !== 1) {return;}
  var withdraw = $('#pCC input[value="Withdraw"]');
  if (withdraw.length !== 1) {return;}
  if ($('#pCC b').eq(o.depoPos).text() === '0') { // Check Deposits Available
    depo.prop('disabled', true);
  } else {
    depo.click(bankDeposit);
  }
  withdraw.click(bankWithdrawal);
}

export function injectGuildBank() { // Native
  bankSettings = guildBank;
  ajaxifyBank();
}

export function injectBank() { // Native
  bankSettings = playerBank;
  ajaxifyBank();
}
<|endoftext|>


<commit_before>const threads = require("../data/threads");
const moment = require("moment");
const utils = require("../utils");
const { getLogUrl, getLogFile, getLogCustomResponse, saveLogToStorage } = require("../data/logs");
const { THREAD_STATUS } = require("../data/constants");
const {getOrFetchChannel} = require("../utils");

const LOG_LINES_PER_PAGE = 10;

module.exports = ({ bot, knex, config, commands, hooks }) => {
  const addOptQueryStringToUrl = (url, args) => {
    const params = [];
    if (args.verbose) params.push("verbose=1");
    if (args.simple) params.push("simple=1");

    if (params.length === 0) {
      return url;
    }

    const hasQueryString = url.indexOf("?") > -1;
    return url + (hasQueryString ? "&" : "?") + params.join("&");
  };

  const logsCmd = async (msg, args, thread) => {
    let userId = args.userId || (thread && thread.user_id);
    if (! userId) return;

    const channel = await getOrFetchChannel(bot, msg.channel.id);
    let userThreads = await threads.getClosedThreadsByUserId(userId);

    // Descending by date
    userThreads.sort((a, b) => {
      if (a.created_at > b.created_at) return -1;
      if (a.created_at < b.created_at) return 1;
      return 0;
    });

    // Pagination
    const totalUserThreads = userThreads.length;
    const maxPage = Math.ceil(totalUserThreads / LOG_LINES_PER_PAGE);
    const inputPage = args.page;
    const page = Math.max(Math.min(inputPage ? parseInt(inputPage, 10) : 1, maxPage), 1); // Clamp page to 1-<max page>
    const isPaginated = totalUserThreads > LOG_LINES_PER_PAGE;
    const start = (page - 1) * LOG_LINES_PER_PAGE;
    const end = page * LOG_LINES_PER_PAGE;
    userThreads = userThreads.slice((page - 1) * LOG_LINES_PER_PAGE, page * LOG_LINES_PER_PAGE);

    const threadLines = await Promise.all(userThreads.map(async userThread => {
      const logUrl = await getLogUrl(userThread);
      const formattedLogUrl = logUrl
        ? `<${addOptQueryStringToUrl(logUrl, args)}>`
        : `View log with \`${config.prefix}log ${userThread.thread_number}\``
      const formattedDate = moment.utc(userThread.created_at).format("MMM Do [at] HH:mm [UTC]");
      return `\`#${userThread.thread_number}\` \`${formattedDate}\`: ${formattedLogUrl}`;
    }));

    let message = isPaginated
      ? `**Log files for <@${userId}>** (page **${page}/${maxPage}**, showing logs **${start + 1}-${end}/${totalUserThreads}**):`
      : `**Log files for <@${userId}>:**`;

    message += `\n${threadLines.join("\n")}`;

    if (isPaginated) {
      message += "\nTo view more, add a page number to the end of the command";
    }

    // Send the list of logs in chunks of 15 lines per message
    const lines = message.split("\n");
    const chunks = utils.chunk(lines, 15);

    let root = Promise.resolve();
    chunks.forEach(chunkLines => {
      root = root.then(() => channel.createMessage(chunkLines.join("\n")));
    });
  };

  const logCmd = async (msg, args, _thread) => {
    const threadId = args.threadId || (_thread && _thread.id);
    if (! threadId) return;

    const thread = (await threads.findById(threadId)) || (await threads.findByThreadNumber(threadId));
    if (! thread) return;

    const channel = await getOrFetchChannel(bot, msg.channel.id);

    const customResponse = await getLogCustomResponse(thread);
    if (customResponse && (customResponse.content || customResponse.file)) {
      channel.createMessage(customResponse.content, customResponse.file);
    }

    const logUrl = await getLogUrl(thread);
    if (logUrl) {
      channel.createMessage(`Open the following link to view the log for thread #${thread.thread_number}:\n<${addOptQueryStringToUrl(logUrl, args)}>`);
      return;
    }

    const logFile = await getLogFile(thread);
    if (logFile) {
      channel.createMessage(`Download the following file to view the log for thread #${thread.thread_number}:`, logFile);
      return;
    }

    if (thread.status === THREAD_STATUS.OPEN) {
      channel.createMessage(`This thread's logs are not currently available, but it's open at <#${thread.channel_id}>`);
      return;
    }

    channel.createMessage("This thread's logs are not currently available");
  };

  const logCmdOptions = [
    { name: "verbose", shortcut: "v", isSwitch: true },
    { name: "simple", shortcut: "s", isSwitch: true },
  ];

  commands.addInboxServerCommand("logs", "<userId:userId> [page:number]", logsCmd, { options: logCmdOptions });
  commands.addInboxServerCommand("logs", "[page:number]", logsCmd, { options: logCmdOptions });

  // Add these two overrides to allow using the command in suspended threads
  commands.addInboxThreadCommand("log", "", logCmd, { options: logCmdOptions, aliases: ["thread"], allowSuspended: true });
  commands.addInboxThreadCommand("loglink", "", logCmd, { options: logCmdOptions, allowSuspended: true });

  commands.addInboxServerCommand("log", "<threadId:string>", logCmd, { options: logCmdOptions, aliases: ["thread"] });
  commands.addInboxServerCommand("loglink", "<threadId:string>", logCmd, { options: logCmdOptions });

  hooks.afterThreadClose(async ({ threadId }) => {
    const thread = await threads.findById(threadId);
    await saveLogToStorage(thread);
  });
};
<commit_msg>Update logsCmd for no logs edge case<commit_after>const threads = require("../data/threads");
const moment = require("moment");
const utils = require("../utils");
const { getLogUrl, getLogFile, getLogCustomResponse, saveLogToStorage } = require("../data/logs");
const { THREAD_STATUS } = require("../data/constants");
const {getOrFetchChannel} = require("../utils");

const LOG_LINES_PER_PAGE = 10;

module.exports = ({ bot, knex, config, commands, hooks }) => {
  const addOptQueryStringToUrl = (url, args) => {
    const params = [];
    if (args.verbose) params.push("verbose=1");
    if (args.simple) params.push("simple=1");

    if (params.length === 0) {
      return url;
    }

    const hasQueryString = url.indexOf("?") > -1;
    return url + (hasQueryString ? "&" : "?") + params.join("&");
  };

  const logsCmd = async (msg, args, thread) => {
    let userId = args.userId || (thread && thread.user_id);
    if (! userId) return;

    const channel = await getOrFetchChannel(bot, msg.channel.id);
    let userThreads = await threads.getClosedThreadsByUserId(userId);

    // Descending by date
    userThreads.sort((a, b) => {
      if (a.created_at > b.created_at) return -1;
      if (a.created_at < b.created_at) return 1;
      return 0;
    });

    // Pagination
    const totalUserThreads = userThreads.length;
    const maxPage = Math.ceil(totalUserThreads / LOG_LINES_PER_PAGE);
    const inputPage = args.page;
    const page = Math.max(Math.min(inputPage ? parseInt(inputPage, 10) : 1, maxPage), 1); // Clamp page to 1-<max page>
    const isPaginated = totalUserThreads > LOG_LINES_PER_PAGE;
    const start = (page - 1) * LOG_LINES_PER_PAGE;
    const end = page * LOG_LINES_PER_PAGE;
    userThreads = userThreads.slice((page - 1) * LOG_LINES_PER_PAGE, page * LOG_LINES_PER_PAGE);

    const threadLines = await Promise.all(userThreads.map(async userThread => {
      const logUrl = await getLogUrl(userThread);
      const formattedLogUrl = logUrl
        ? `<${addOptQueryStringToUrl(logUrl, args)}>`
        : `View log with \`${config.prefix}log ${userThread.thread_number}\``
      const formattedDate = moment.utc(userThread.created_at).format("MMM Do [at] HH:mm [UTC]");
      return `\`#${userThread.thread_number}\` \`${formattedDate}\`: ${formattedLogUrl}`;
    }));

    let message = isPaginated
      ? `**Log files for <@${userId}>** (page **${page}/${maxPage}**, showing logs **${start + 1}-${end}/${totalUserThreads}**):`
      : `**Log files for <@${userId}>:**`;

    message += `\n${threadLines.join("\n")}`;

    if (isPaginated) {
      message += "\nTo view more, add a page number to the end of the command";
    }

    if (threadLines.length === 0) message = `**There are no log files for <@${userId}>**`;

    // Send the list of logs in chunks of 15 lines per message
    const lines = message.split("\n");
    const chunks = utils.chunk(lines, 15);

    let root = Promise.resolve();
    chunks.forEach(chunkLines => {
      root = root.then(() => channel.createMessage(chunkLines.join("\n")));
    });
  };

  const logCmd = async (msg, args, _thread) => {
    const threadId = args.threadId || (_thread && _thread.id);
    if (! threadId) return;

    const thread = (await threads.findById(threadId)) || (await threads.findByThreadNumber(threadId));
    if (! thread) return;

    const channel = await getOrFetchChannel(bot, msg.channel.id);

    const customResponse = await getLogCustomResponse(thread);
    if (customResponse && (customResponse.content || customResponse.file)) {
      channel.createMessage(customResponse.content, customResponse.file);
    }

    const logUrl = await getLogUrl(thread);
    if (logUrl) {
      channel.createMessage(`Open the following link to view the log for thread #${thread.thread_number}:\n<${addOptQueryStringToUrl(logUrl, args)}>`);
      return;
    }

    const logFile = await getLogFile(thread);
    if (logFile) {
      channel.createMessage(`Download the following file to view the log for thread #${thread.thread_number}:`, logFile);
      return;
    }

    if (thread.status === THREAD_STATUS.OPEN) {
      channel.createMessage(`This thread's logs are not currently available, but it's open at <#${thread.channel_id}>`);
      return;
    }

    channel.createMessage("This thread's logs are not currently available");
  };

  const logCmdOptions = [
    { name: "verbose", shortcut: "v", isSwitch: true },
    { name: "simple", shortcut: "s", isSwitch: true },
  ];

  commands.addInboxServerCommand("logs", "<userId:userId> [page:number]", logsCmd, { options: logCmdOptions });
  commands.addInboxServerCommand("logs", "[page:number]", logsCmd, { options: logCmdOptions });

  // Add these two overrides to allow using the command in suspended threads
  commands.addInboxThreadCommand("log", "", logCmd, { options: logCmdOptions, aliases: ["thread"], allowSuspended: true });
  commands.addInboxThreadCommand("loglink", "", logCmd, { options: logCmdOptions, allowSuspended: true });

  commands.addInboxServerCommand("log", "<threadId:string>", logCmd, { options: logCmdOptions, aliases: ["thread"] });
  commands.addInboxServerCommand("loglink", "<threadId:string>", logCmd, { options: logCmdOptions });

  hooks.afterThreadClose(async ({ threadId }) => {
    const thread = await threads.findById(threadId);
    await saveLogToStorage(thread);
  });
};
<|endoftext|>


<commit_before>var util = require('util');
var twitter = require('twitter');

const twit = new twitter({
    consumer_key: process.env.TwitterConsumerKey,
    consumer_secret: process.env.TwitterConsumerSecret,
    access_token_key: process.env.TwitterAccessTokenKey,
    access_token_secret: process.env.TwitterAccessTokenSecret
});

module.exports = function (context, message) {

    return twit.get(`users/show.json?user_id=${message.twitter.id}`)
        .then(log)

    function setOutputBinding(data) {
        context.bindings.out = data;
        return data;
    }

    function log(data) {
        context.log(data);
        return data;
    }
}<commit_msg>include entities<commit_after>var util = require('util');
var twitter = require('twitter');

const twit = new twitter({
    consumer_key: process.env.TwitterConsumerKey,
    consumer_secret: process.env.TwitterConsumerSecret,
    access_token_key: process.env.TwitterAccessTokenKey,
    access_token_secret: process.env.TwitterAccessTokenSecret
});

module.exports = function (context, message) {

    return twit.get(`users/show.json?user_id=${message.twitter.id}`, { include_entities: true })
        .then(log)

    function setOutputBinding(data) {
        context.bindings.out = data;
        return data;
    }

    function log(data) {
        context.log(data);
        return data;
    }
}<|endoftext|>


<commit_before>
/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		// score
		score : 0,
		// hive cap
		hcap : 5,
		// idle bees
		idle : 5,
		// exploring bees
		explore : 0,
		// attacking bees
		attack : 0
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	if (!me.video.init("screen", 800, 480, true, 'auto')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	// Initialize the audio.
	me.audio.init("mp3, ogg, wav");

	// Set a callback to run when loading is complete.
	me.loader.onload = this.loaded.bind(this);

	// Load the resources.
	me.loader.preload(game.resources);

	// Initialize melonJS and display a loading screen.
	me.state.change(me.state.LOADING);
},

	// Run on game resources loaded.
	"loaded" : function () {

		me.pool.register("HiveEntity", game.HiveEntity);
		me.pool.register("BearEntity", game.BearEntity);
		me.pool.register("FlowerEntity", game.FlowerEntity);
		me.sys.gravity = 0;

		me.input.bindKey(me.input.KEY.LEFT, "left");
		me.input.bindKey(me.input.KEY.RIGHT, "right");
		me.input.bindKey(me.input.KEY.UP, "up");
		me.input.bindKey(me.input.KEY.DOWN, "down");
		me.input.bindKey(me.input.KEY.ESC, "esc");

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());
		me.state.set(me.state.CREDITS, new game.CreditScreen());
		me.state.set(me.state.USER, new game.InstructionsScreen());
		// Go to title screen.
		me.audio.playTrack("Beeline_Menu", 0.5);
		me.state.change(me.state.MENU);
	}
};
<commit_msg>Removed extra spaces in alternative formats.<commit_after>
/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		// score
		score : 0,
		// hive cap
		hcap : 5,
		// idle bees
		idle : 5,
		// exploring bees
		explore : 0,
		// attacking bees
		attack : 0
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	if (!me.video.init("screen", 800, 480, true, 'auto')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	// Initialize the audio.
	me.audio.init("mp3,ogg,wav");

	// Set a callback to run when loading is complete.
	me.loader.onload = this.loaded.bind(this);

	// Load the resources.
	me.loader.preload(game.resources);

	// Initialize melonJS and display a loading screen.
	me.state.change(me.state.LOADING);
},

	// Run on game resources loaded.
	"loaded" : function () {

		me.pool.register("HiveEntity", game.HiveEntity);
		me.pool.register("BearEntity", game.BearEntity);
		me.pool.register("FlowerEntity", game.FlowerEntity);
		me.sys.gravity = 0;

		me.input.bindKey(me.input.KEY.LEFT, "left");
		me.input.bindKey(me.input.KEY.RIGHT, "right");
		me.input.bindKey(me.input.KEY.UP, "up");
		me.input.bindKey(me.input.KEY.DOWN, "down");
		me.input.bindKey(me.input.KEY.ESC, "esc");

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());
		me.state.set(me.state.CREDITS, new game.CreditScreen());
		me.state.set(me.state.USER, new game.InstructionsScreen());
		// Go to title screen.
		me.audio.playTrack("Beeline_Menu", 0.5);
		me.state.change(me.state.MENU);
	}
};
<|endoftext|>


<commit_before>/// <reference path="../typings/mocha/mocha.d.ts"/>
"use strict";
var sinon = require('sinon');
var chai = require('chai');
var request = require('supertest');
var express = require('express');
var routes = require('../routes');
var contact = require('../routes/contact');
var sponsors = require('../routes/sponsors');
var path = require('path');

var expect = chai.expect;

var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);

app.get('/', routes.index);
app.get('/Contact', contact.contact);
app.get('/Sponsors', sponsors.list);
app.get('/Code', routes.code);
app.get('/api', routes.api);

describe("Routes", function() {
  describe("GET Index", function() {

    it('responds to /', function testHomepage(done) {
      this.timeout(5000);
        request(app)
          .get('/')
          .expect('Content-Type', /text\/html/)
          .expect(200)
          .end(function(err, res){
            done(err);
          });
    });
  });

  describe('GET Sponsors', function() {
    it('responds to /Sponsors', function testSponsors(done) {
      request(app)
      .get('/Sponsors')
      .expect('Content-Type', /text\/html/)
      .expect(200, done);
    });
  });

  describe('GET Contact Us', function() {
    it('responds to /Contact', function testContactUs(done) {
      request(app)
      .get('/Contact')
      .expect('Content-Type', /text\/html/)
      .expect(200, done);
    });
  });

  describe('GET Code', function() {
    it('responds to /Code', function testCode(done) {
      request(app)
      .get('/Code')
      .expect('Content-Type', /text\/html/)
      .expect(200, done);
    });
  });

  describe('GET Code', function() {
    it('responds to /api', function testApi(done) {
      request(app)
      .get('/api')
      .expect('Content-Type', /application\/json/)
      .expect(200, done);
    });
  });
});<commit_msg>Adding extra long tiomeout for building cache<commit_after>/// <reference path="../typings/mocha/mocha.d.ts"/>
"use strict";
var sinon = require('sinon');
var chai = require('chai');
var request = require('supertest');
var express = require('express');
var routes = require('../routes');
var contact = require('../routes/contact');
var sponsors = require('../routes/sponsors');
var path = require('path');

var expect = chai.expect;

var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);

app.get('/', routes.index);
app.get('/Contact', contact.contact);
app.get('/Sponsors', sponsors.list);
app.get('/Code', routes.code);
app.get('/api', routes.api);

describe("Routes", function() {
  describe("GET Index", function() {

    it('responds to /', function testHomepage(done) {
      this.timeout(10000);
        request(app)
          .get('/')
          .expect('Content-Type', /text\/html/)
          .expect(200)
          .end(function(err, res){
            done(err);
          });
    });
  });

  describe('GET Sponsors', function() {
    it('responds to /Sponsors', function testSponsors(done) {
      request(app)
      .get('/Sponsors')
      .expect('Content-Type', /text\/html/)
      .expect(200, done);
    });
  });

  describe('GET Contact Us', function() {
    it('responds to /Contact', function testContactUs(done) {
      request(app)
      .get('/Contact')
      .expect('Content-Type', /text\/html/)
      .expect(200, done);
    });
  });

  describe('GET Code', function() {
    it('responds to /Code', function testCode(done) {
      request(app)
      .get('/Code')
      .expect('Content-Type', /text\/html/)
      .expect(200, done);
    });
  });

  describe('GET Code', function() {
    it('responds to /api', function testApi(done) {
      request(app)
      .get('/api')
      .expect('Content-Type', /application\/json/)
      .expect(200, done);
    });
  });
});<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Line = function ( geometry, material, mode ) {

	if ( mode === 1 ) {

		console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
		return new THREE.LineSegments( geometry, material );

	}

	THREE.Object3D.call( this );

	this.type = 'Line';

	this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
	this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );

};

THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
THREE.Line.prototype.constructor = THREE.Line;

THREE.Line.prototype.raycast = ( function () {

	var inverseMatrix = new THREE.Matrix4();
	var ray = new THREE.Ray();
	var sphere = new THREE.Sphere();

	return function raycast( raycaster, intersects ) {

		var precision = raycaster.linePrecision;
		var precisionSq = precision * precision;

		var geometry = this.geometry;
		var matrixWorld = this.matrixWorld;

		// Checking boundingSphere distance to ray

		if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

		sphere.copy( geometry.boundingSphere );
		sphere.applyMatrix4( matrixWorld );

		if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;

		//

		inverseMatrix.getInverse( matrixWorld );
		ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

		var vStart = new THREE.Vector3();
		var vEnd = new THREE.Vector3();
		var interSegment = new THREE.Vector3();
		var interRay = new THREE.Vector3();
		var step = this instanceof THREE.LineSegments ? 2 : 1;

		if ( geometry instanceof THREE.BufferGeometry ) {

			var index = geometry.index;
			var attributes = geometry.attributes;

			if ( index !== null ) {

				var indices = index.array;
				var positions = attributes.position.array;

				for ( var i = 0, l = indices.length - 1; i < l; i += step ) {

					var a = indices[ i ];
					var b = indices[ i + 1 ];

					vStart.fromArray( positions, a * 3 );
					vEnd.fromArray( positions, b * 3 );

					var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );

					if ( distSq > precisionSq ) continue;

					interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

					var distance = raycaster.ray.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( this.matrixWorld ),
						index: i,
						face: null,
						faceIndex: null,
						object: this

					} );

				}

			} else {

				var positions = attributes.position.array;

				for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {

					vStart.fromArray( positions, 3 * i );
					vEnd.fromArray( positions, 3 * i + 3 );

					var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );

					if ( distSq > precisionSq ) continue;

					interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

					var distance = raycaster.ray.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( this.matrixWorld ),
						index: i,
						face: null,
						faceIndex: null,
						object: this

					} );

				}

			}

		} else if ( geometry instanceof THREE.Geometry ) {

			var vertices = geometry.vertices;
			var nbVertices = vertices.length;

			for ( var i = 0; i < nbVertices - 1; i += step ) {

				var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );

				if ( distSq > precisionSq ) continue;

				interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

				var distance = raycaster.ray.origin.distanceTo( interRay );

				if ( distance < raycaster.near || distance > raycaster.far ) continue;

				intersects.push( {

					distance: distance,
					// What do we want? intersection point on the ray or on the segment??
					// point: raycaster.ray.at( distance ),
					point: interSegment.clone().applyMatrix4( this.matrixWorld ),
					index: i,
					face: null,
					faceIndex: null,
					object: this

				} );

			}

		}

	};

}() );

THREE.Line.prototype.clone = function () {

	return new this.constructor( this.geometry, this.material ).copy( this );

};

// DEPRECATED

THREE.LineStrip = 0;
THREE.LinePieces = 1;
<commit_msg>Line: raycast clean up.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Line = function ( geometry, material, mode ) {

	if ( mode === 1 ) {

		console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
		return new THREE.LineSegments( geometry, material );

	}

	THREE.Object3D.call( this );

	this.type = 'Line';

	this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
	this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );

};

THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
THREE.Line.prototype.constructor = THREE.Line;

THREE.Line.prototype.raycast = ( function () {

	var inverseMatrix = new THREE.Matrix4();
	var ray = new THREE.Ray();
	var sphere = new THREE.Sphere();

	return function raycast( raycaster, intersects ) {

		var precision = raycaster.linePrecision;
		var precisionSq = precision * precision;

		var geometry = this.geometry;
		var matrixWorld = this.matrixWorld;

		// Checking boundingSphere distance to ray

		if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

		sphere.copy( geometry.boundingSphere );
		sphere.applyMatrix4( matrixWorld );

		if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;

		//

		inverseMatrix.getInverse( matrixWorld );
		ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

		var vStart = new THREE.Vector3();
		var vEnd = new THREE.Vector3();
		var interSegment = new THREE.Vector3();
		var interRay = new THREE.Vector3();
		var step = this instanceof THREE.LineSegments ? 2 : 1;

		if ( geometry instanceof THREE.BufferGeometry ) {

			var index = geometry.index;
			var attributes = geometry.attributes;
			var positions = attributes.position.array;

			if ( index !== null ) {

				var indices = index.array;

				for ( var i = 0, l = indices.length - 1; i < l; i += step ) {

					var a = indices[ i ];
					var b = indices[ i + 1 ];

					vStart.fromArray( positions, a * 3 );
					vEnd.fromArray( positions, b * 3 );

					var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );

					if ( distSq > precisionSq ) continue;

					interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

					var distance = raycaster.ray.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( this.matrixWorld ),
						index: i,
						face: null,
						faceIndex: null,
						object: this

					} );

				}

			} else {

				for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {

					vStart.fromArray( positions, 3 * i );
					vEnd.fromArray( positions, 3 * i + 3 );

					var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );

					if ( distSq > precisionSq ) continue;

					interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

					var distance = raycaster.ray.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( this.matrixWorld ),
						index: i,
						face: null,
						faceIndex: null,
						object: this

					} );

				}

			}

		} else if ( geometry instanceof THREE.Geometry ) {

			var vertices = geometry.vertices;
			var nbVertices = vertices.length;

			for ( var i = 0; i < nbVertices - 1; i += step ) {

				var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );

				if ( distSq > precisionSq ) continue;

				interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

				var distance = raycaster.ray.origin.distanceTo( interRay );

				if ( distance < raycaster.near || distance > raycaster.far ) continue;

				intersects.push( {

					distance: distance,
					// What do we want? intersection point on the ray or on the segment??
					// point: raycaster.ray.at( distance ),
					point: interSegment.clone().applyMatrix4( this.matrixWorld ),
					index: i,
					face: null,
					faceIndex: null,
					object: this

				} );

			}

		}

	};

}() );

THREE.Line.prototype.clone = function () {

	return new this.constructor( this.geometry, this.material ).copy( this );

};

// DEPRECATED

THREE.LineStrip = 0;
THREE.LinePieces = 1;
<|endoftext|>


<commit_before>EZ3.Mesh = function(data) {
  EZ3.Entity.call(this);

  this._buffer = new EZ3.Buffer();
  this.dynamic = data.dynamic || false;
  this.material = data.material || null;
  this.geometry = (data.geometry instanceof EZ3.Geometry) ? data.geometry : null;
};

EZ3.Mesh.prototype = Object.create(EZ3.Entity.prototype);
EZ3.Mesh.prototype.constructor = EZ3.Mesh;

EZ3.Mesh.prototype.init = function(gl) {
  if(this.geometry){
    var hint = (this.dynamic) ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;

    if (this.geometry.verticesNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.VERTEX, this.geometry.vertices.length, this.geometry.vertices, hint);
      this.geometry.verticesNeedUpdate = false;
    }

    if (this.geometry.normalsNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.NORMAL, this.geometry.normals.length, this.geometry.normals, hint);
      this.geometry.normalsNeedUpdate = false;
    }

    if (this.geometry.uvsNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.UV, this.geometry.uvs.length, this.geometry.uvs, hint);
      this.geometry.uvNeedUpdate = false;
    }

    if (this.geometry.tangentsNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.TANGENTS, this.geometry.tangents.length, this.geometry.tangents, hint);
      this.geometry.tangentNeedUpdate = false;
    }

    if (this.geometry.bitangentsNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.BITANGENTS, this.geometry.bitangents.length, this.geometry.bitangents, hint);
      this.geometry.bitangentsNeedUpdate = false;
    }

    if (this.geometry.indicesNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.INDEX, this.geometry.indices.length, this.geometry.indices, hint);
      this.geometry.indicesNeedUpdate = false;
    }
  }
};

EZ3.Mesh.prototype.draw = function(gl) {
  if(this.geometry){
    if (this.geometry.indices.length)
      this._buffer.draw(gl, EZ3.ELEMENTS_DRAW, this.geometry.indices.length);
    else
      this._buffer.draw(gl, EZ3.ARRAYS_DRAW, this.geometry.vertices.length);
  }
};
<commit_msg>Updated Mesh.js<commit_after>EZ3.Mesh = function(geometry, material) {
  EZ3.Entity.call(this);

  this._buffer = new EZ3.Buffer();
  this.dynamic = false;
  this.material = (material instanceof EZ3.Material) ? material : null;
  this.geometry = (geometry instanceof EZ3.Geometry) ? geometry : null;
};

EZ3.Mesh.prototype = Object.create(EZ3.Entity.prototype);
EZ3.Mesh.prototype.constructor = EZ3.Mesh;

EZ3.Mesh.prototype.init = function(gl) {
  if(this.geometry){
    var hint = (this.dynamic) ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;

    if (this.geometry.verticesNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.VERTEX, this.geometry.vertices.length, this.geometry.vertices, hint);
      this.geometry.verticesNeedUpdate = false;
    }

    if (this.geometry.normalsNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.NORMAL, this.geometry.normals.length, this.geometry.normals, hint);
      this.geometry.normalsNeedUpdate = false;
    }

    if (this.geometry.uvsNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.UV, this.geometry.uvs.length, this.geometry.uvs, hint);
      this.geometry.uvNeedUpdate = false;
    }

    if (this.geometry.tangentsNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.TANGENTS, this.geometry.tangents.length, this.geometry.tangents, hint);
      this.geometry.tangentNeedUpdate = false;
    }

    if (this.geometry.bitangentsNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.BITANGENTS, this.geometry.bitangents.length, this.geometry.bitangents, hint);
      this.geometry.bitangentsNeedUpdate = false;
    }

    if (this.geometry.indicesNeedUpdate) {
      this._buffer.init(gl, EZ3.Buffer.INDEX, this.geometry.indices.length, this.geometry.indices, hint);
      this.geometry.indicesNeedUpdate = false;
    }
  }
};

EZ3.Mesh.prototype.render = function(gl) {
  if(this.geometry){
    if (this.geometry.indices.length)
      this._buffer.draw(gl, EZ3.ELEMENTS_DRAW, this.geometry.indices.length);
    else
      this._buffer.draw(gl, EZ3.ARRAYS_DRAW, this.geometry.vertices.length);
  }
};
<|endoftext|>


<commit_before>var util = require('../js/util');
var assert = require('assert');

describe('Hello World function', function() {
    it('should always fail', function() {

        assert.equal(false, false);

    });

    it('should just say hello', function() {
        var answer = util.helloWorld();
        assert.equal('Hello World, wie geht es euch?\n', answer);
    });
});<commit_msg>FIX fix test for new greeting<commit_after>var util = require('../js/util');
var assert = require('assert');

describe('Hello World function', function() {
    it('should always fail', function() {

        assert.equal(false, false);

    });

    it('should just say hello', function() {
        var answer = util.helloWorld();
        assert.equal('Hello World, wie geht es euch?\n ' +
            '
Wir lassen TravisCI für uns arbeiten
', answer);
    });
});<|endoftext|>


<commit_before>/**
 * Lines geometry
 * Use screen space projected lines lineWidth > MAX_LINE_WIDTH
 * https://mattdesl.svbtle.com/drawing-lines-is-hard
 * @module echarts-gl/chart/lines3D/LinesGeometry
 * @author Yi Shen(http://github.com/pissang)
 */

var StaticGeometry = require('qtek/lib/StaticGeometry');
var vec3 = require('qtek/lib/dep/glmatrix').vec3;

// var CURVE_RECURSION_LIMIT = 8;
// var CURVE_COLLINEAR_EPSILON = 40;

/**
 * @constructor
 * @alias module:echarts-gl/chart/lines3D/LinesGeometry
 * @extends qtek.StaticGeometry
 */

var LinesGeometry = StaticGeometry.extend(function () {
    return {

        segmentScale: 1,

        /**
         * Need to use mesh to expand lines if lineWidth > MAX_LINE_WIDTH
         */
        useNativeLine: true,

        attributes: {
            position: new StaticGeometry.Attribute('position', 'float', 3, 'POSITION'),
            positionPrev: new StaticGeometry.Attribute('normal', 'float', 3),
            positionNext: new StaticGeometry.Attribute('normal', 'float', 3),
            offset: new StaticGeometry.Attribute('normal', 'float', 1),
            color: new StaticGeometry.Attribute('color', 'float', 4, 'COLOR')
        }
    };
},
/** @lends module: echarts-gl/chart/lines3D/LinesGeometry.prototype */
{

    /**
     * Reset offset
     */
    resetOffset: function () {
        this._vertexOffset = 0;
        this._faceOffset = 0;
    },

    /**
     * @param {number} nVertex
     */
    setVertexCount: function (nVertex) {
        var attributes = this.attributes;
        if (this.vertexCount !== nVertex) {
            attributes.position.init(nVertex);
            attributes.color.init(nVertex);

            if (!this.useNativeLine) {
                attributes.positionPrev.init(nVertex);
                attributes.positionNext.init(nVertex);
                attributes.offset.init(nVertex);
            }

            this._vertexOffset = 0;

            if (nVertex > 0xffff) {
                if (this.faces instanceof Uint16Array) {
                    this.faces = new Uint32Array(this.faces);
                }
            }
            else {
                if (this.faces instanceof Uint32Array) {
                    this.faces = new Uint16Array(this.faces);
                }
            }
        }
    },

    /**
     * @param {number} nFace
     */
    setFaceCount: function (nFace) {
        if (this.faceCount !== nFace) {
            if (nFace === 0) {
                this.faces = null;
            }
            else {
                this.faces = this.vertexCount > 0xffff ? new Uint32Array(nFace * 3) : new Uint16Array(nFace * 3);
            }
        }
    },

    _getCubicCurveApproxStep: function (p0, p1, p2, p3) {
        var len = vec3.dist(p0, p1) + vec3.dist(p2, p1) + vec3.dist(p3, p2);
        var step = 1 / (len + 1) * this.segmentScale;
        return step;
    },

    /**
     * Get vertex count of cubic curve
     * @param {Array.<number>} p0
     * @param {Array.<number>} p1
     * @param {Array.<number>} p2
     * @param {Array.<number>} p3
     * @return number
     */
    getCubicCurveVertexCount: function (p0, p1, p2, p3) {
        var step = this._getCubicCurveApproxStep(p0, p1, p2, p3);
        var segCount = Math.ceil(1 / step);
        if (!this.useNativeLine) {
            return segCount * 2 + 2;
        }
        else {
            return segCount * 2;
        }
    },

    /**
     * Get face count of cubic curve
     * @param {Array.<number>} p0
     * @param {Array.<number>} p1
     * @param {Array.<number>} p2
     * @param {Array.<number>} p3
     * @return number
     */
    getCubicCurveFaceCount: function (p0, p1, p2, p3) {
        var step = this._getCubicCurveApproxStep(p0, p1, p2, p3);
        var segCount = Math.ceil(1 / step);
        if (!this.useNativeLine) {
            return segCount * 2;
        }
        else {
            return 0;
        }
    },

    /**
     * Get vertex count of line
     * @return {number}
     */
    getLineVertexCount: function () {
        return !this.useNativeLine ? 4 : 2;
    },

    /**
     * Get face count of line
     * @return {number}
     */
    getLineFaceCount: function () {
        return !this.useNativeLine ? 2 : 0;
    },
    /**
     * Add a cubic curve
     * @param {Array.<number>} p0
     * @param {Array.<number>} p1
     * @param {Array.<number>} p2
     * @param {Array.<number>} p3
     * @param {Array.<number>} color
     * @param {number} [lineWidth=1]
     */
    addCubicCurve: function (p0, p1, p2, p3, color, lineWidth) {
        if (lineWidth == null) {
            lineWidth = 1;
        }
        // incremental interpolation
        // http://antigrain.com/research/bezier_interpolation/index.html#PAGE_BEZIER_INTERPOLATION
        var x0 = p0[0], y0 = p0[1], z0 = p0[2];
        var x1 = p1[0], y1 = p1[1], z1 = p1[2];
        var x2 = p2[0], y2 = p2[1], z2 = p2[2];
        var x3 = p3[0], y3 = p3[1], z3 = p3[2];

        var step = this._getCubicCurveApproxStep(p0, p1, p2, p3);

        var step2 = step * step;
        var step3 = step2 * step;

        var pre1 = 3.0 * step;
        var pre2 = 3.0 * step2;
        var pre4 = 6.0 * step2;
        var pre5 = 6.0 * step3;

        var tmp1x = x0 - x1 * 2.0 + x2;
        var tmp1y = y0 - y1 * 2.0 + y2;
        var tmp1z = z0 - z1 * 2.0 + z2;

        var tmp2x = (x1 - x2) * 3.0 - x0 + x3;
        var tmp2y = (y1 - y2) * 3.0 - y0 + y3;
        var tmp2z = (z1 - z2) * 3.0 - z0 + z3;

        var fx = x0;
        var fy = y0;
        var fz = z0;

        var dfx = (x1 - x0) * pre1 + tmp1x * pre2 + tmp2x * step3;
        var dfy = (y1 - y0) * pre1 + tmp1y * pre2 + tmp2y * step3;
        var dfz = (z1 - z0) * pre1 + tmp1z * pre2 + tmp2z * step3;

        var ddfx = tmp1x * pre4 + tmp2x * pre5;
        var ddfy = tmp1y * pre4 + tmp2y * pre5;
        var ddfz = tmp1z * pre4 + tmp2z * pre5;

        var dddfx = tmp2x * pre5;
        var dddfy = tmp2y * pre5;
        var dddfz = tmp2z * pre5;

        var positionAttr = this.attributes.position;
        var positionPrevAttr = this.attributes.positionPrev;
        var positionNextAttr = this.attributes.positionNext;
        var colorAttr = this.attributes.color;
        var offsetAttr = this.attributes.offset;
        var t = 0;
        var posTmp = [];

        var k = 0;
        var segCount = Math.ceil(1 / step);

        var iterCount = !this.useNativeLine ? (segCount + 1) : segCount;
        var vertexOffset = this._vertexOffset;
        for (var k = 0; k < iterCount; k++) {
            posTmp[0] = fx; posTmp[1] = fy; posTmp[2] = fz;
            if (!this.useNativeLine) {
                if (k < iterCount - 1) {
                    positionPrevAttr.set(vertexOffset + 2, posTmp);
                    positionPrevAttr.set(vertexOffset + 3, posTmp);
                }
                if (k > 0) {
                    positionNextAttr.set(vertexOffset - 2, posTmp);
                    positionNextAttr.set(vertexOffset - 1, posTmp);
                }

                positionAttr.set(vertexOffset, posTmp);
                positionAttr.set(vertexOffset + 1, posTmp);

                colorAttr.set(vertexOffset, color);
                colorAttr.set(vertexOffset + 1, color);

                offsetAttr.set(vertexOffset, lineWidth / 2);
                offsetAttr.set(vertexOffset + 1, -lineWidth / 2);

                vertexOffset += 2;
            }
            else {
                if (k > 0) {
                    positionAttr.copy(vertexOffset, vertexOffset - 1);
                    colorAttr.copy(vertexOffset, vertexOffset - 1);
                }
                else {
                    colorAttr.set(vertexOffset, color);
                    positionAttr.set(vertexOffset, posTmp);
                }
                vertexOffset++;
            }

            fx += dfx; fy += dfy; fz += dfz;
            dfx += ddfx; dfy += ddfy; dfz += ddfz;
            ddfx += dddfx; ddfy += dddfy; ddfz += dddfz;
            t += step;

            posTmp[0] = fx; posTmp[1] = fy; posTmp[2] = fz;

            if (!this.useNativeLine) {
                if (k > 0) {
                    var idx3 = this._faceOffset * 3;
                    var faces = this.faces;
                    // 0-----2
                    // 1-----3
                    // 0->1->2, 1->3->2
                    faces[idx3] = vertexOffset - 4;
                    faces[idx3 + 1] = vertexOffset - 3;
                    faces[idx3 + 2] = vertexOffset - 2;

                    faces[idx3 + 3] = vertexOffset - 3;
                    faces[idx3 + 4] = vertexOffset - 1;
                    faces[idx3 + 5] = vertexOffset - 2;

                    this._faceOffset += 2;
                }
            }
            else {
                colorAttr.set(vertexOffset, color);
                positionAttr.set(vertexOffset, posTmp);
                vertexOffset++;
            }
        }
        if (!this.useNativeLine) {

            var start = this._vertexOffset;
            // PENDING
            var end = this._vertexOffset + segCount * 2;
            positionPrevAttr.copy(start, start + 2);
            positionPrevAttr.copy(start + 1, start + 3);
            positionNextAttr.copy(end - 1, end - 3);
            positionNextAttr.copy(end - 2, end - 4);
        }

        this._vertexOffset = vertexOffset;
    },

    /**
     * Add a straight line
     * @param {Array.<number>} p0
     * @param {Array.<number>} p1
     * @param {Array.<number>} color
     */
    addLine: function (p0, p1, color) {

        var positionAttr = this.attributes.position;
        var positionPrevAttr = this.attributes.positionPrev;
        var positionNextAttr = this.attributes.positionNext;
        var colorAttr = this.attributes.color;
        var offsetAttr = this.attributes.offset;

        if (!this.useNativeLine) {
            for (var i = 0; i < 4; i++) {
                positionAttr.set(this._vertexOffset + i, i < 2 ? p0 : p1);
                colorAttr.set(this._vertexOffset + i, color);
            }
        }
        else {

            positionAttr.set(this._vertexOffset, p0);
            positionAttr.set(this._vertexOffset + 1, p1);

            colorAttr.set(this._vertexOffset, color);
            colorAttr.set(this._vertexOffset + 1, color);

            this._vertexOffset += 2;
        }

    },

    addPolyline: function (points) {}
});

module.exports = LinesGeometry;<commit_msg>Line3DGeometry addLine and addPolyline<commit_after>/**
 * Lines geometry
 * Use screen space projected lines lineWidth > MAX_LINE_WIDTH
 * https://mattdesl.svbtle.com/drawing-lines-is-hard
 * @module echarts-gl/chart/lines3D/LinesGeometry
 * @author Yi Shen(http://github.com/pissang)
 */

var StaticGeometry = require('qtek/lib/StaticGeometry');
var vec3 = require('qtek/lib/dep/glmatrix').vec3;

// var CURVE_RECURSION_LIMIT = 8;
// var CURVE_COLLINEAR_EPSILON = 40;

/**
 * @constructor
 * @alias module:echarts-gl/chart/lines3D/LinesGeometry
 * @extends qtek.StaticGeometry
 */

var LinesGeometry = StaticGeometry.extend(function () {
    return {

        segmentScale: 1,

        /**
         * Need to use mesh to expand lines if lineWidth > MAX_LINE_WIDTH
         */
        useNativeLine: true,

        attributes: {
            position: new StaticGeometry.Attribute('position', 'float', 3, 'POSITION'),
            positionPrev: new StaticGeometry.Attribute('normal', 'float', 3),
            positionNext: new StaticGeometry.Attribute('normal', 'float', 3),
            offset: new StaticGeometry.Attribute('normal', 'float', 1),
            color: new StaticGeometry.Attribute('color', 'float', 4, 'COLOR')
        }
    };
},
/** @lends module: echarts-gl/chart/lines3D/LinesGeometry.prototype */
{

    /**
     * Reset offset
     */
    resetOffset: function () {
        this._vertexOffset = 0;
        this._faceOffset = 0;
    },

    /**
     * @param {number} nVertex
     */
    setVertexCount: function (nVertex) {
        var attributes = this.attributes;
        if (this.vertexCount !== nVertex) {
            attributes.position.init(nVertex);
            attributes.color.init(nVertex);

            if (!this.useNativeLine) {
                attributes.positionPrev.init(nVertex);
                attributes.positionNext.init(nVertex);
                attributes.offset.init(nVertex);
            }

            this._vertexOffset = 0;

            if (nVertex > 0xffff) {
                if (this.faces instanceof Uint16Array) {
                    this.faces = new Uint32Array(this.faces);
                }
            }
            else {
                if (this.faces instanceof Uint32Array) {
                    this.faces = new Uint16Array(this.faces);
                }
            }
        }
    },

    /**
     * @param {number} nFace
     */
    setFaceCount: function (nFace) {
        if (this.faceCount !== nFace) {
            if (nFace === 0) {
                this.faces = null;
            }
            else {
                this.faces = this.vertexCount > 0xffff ? new Uint32Array(nFace * 3) : new Uint16Array(nFace * 3);
            }
        }
    },

    _getCubicCurveApproxStep: function (p0, p1, p2, p3) {
        var len = vec3.dist(p0, p1) + vec3.dist(p2, p1) + vec3.dist(p3, p2);
        var step = 1 / (len + 1) * this.segmentScale;
        return step;
    },

    /**
     * Get vertex count of cubic curve
     * @param {Array.<number>} p0
     * @param {Array.<number>} p1
     * @param {Array.<number>} p2
     * @param {Array.<number>} p3
     * @return number
     */
    getCubicCurveVertexCount: function (p0, p1, p2, p3) {
        var step = this._getCubicCurveApproxStep(p0, p1, p2, p3);
        var segCount = Math.ceil(1 / step);
        if (!this.useNativeLine) {
            return segCount * 2 + 2;
        }
        else {
            return segCount * 2;
        }
    },

    /**
     * Get face count of cubic curve
     * @param {Array.<number>} p0
     * @param {Array.<number>} p1
     * @param {Array.<number>} p2
     * @param {Array.<number>} p3
     * @return number
     */
    getCubicCurveFaceCount: function (p0, p1, p2, p3) {
        var step = this._getCubicCurveApproxStep(p0, p1, p2, p3);
        var segCount = Math.ceil(1 / step);
        if (!this.useNativeLine) {
            return segCount * 2;
        }
        else {
            return 0;
        }
    },

    /**
     * Get vertex count of line
     * @return {number}
     */
    getLineVertexCount: function () {
        return this.getPolylineVertexCount(2);
    },

    /**
     * Get face count of line
     * @return {number}
     */
    getLineFaceCount: function () {
        return this.getPolylineFaceCount(2);
    },

    getPolylineVertexCount: function (points) {
        return !this.useNativeLine ? ((points.length - 1) * 2 + 2) : (points.length - 1) * 2;
    },

    getPolylineFaceCount: function (points) {
        return !this.useNativeLine ? (points.length - 1) * 2 : 0;
    },

    /**
     * Add a cubic curve
     * @param {Array.<number>} p0
     * @param {Array.<number>} p1
     * @param {Array.<number>} p2
     * @param {Array.<number>} p3
     * @param {Array.<number>} color
     * @param {number} [lineWidth=1]
     */
    addCubicCurve: function (p0, p1, p2, p3, color, lineWidth) {
        if (lineWidth == null) {
            lineWidth = 1;
        }
        // incremental interpolation
        // http://antigrain.com/research/bezier_interpolation/index.html#PAGE_BEZIER_INTERPOLATION
        var x0 = p0[0], y0 = p0[1], z0 = p0[2];
        var x1 = p1[0], y1 = p1[1], z1 = p1[2];
        var x2 = p2[0], y2 = p2[1], z2 = p2[2];
        var x3 = p3[0], y3 = p3[1], z3 = p3[2];

        var step = this._getCubicCurveApproxStep(p0, p1, p2, p3);

        var step2 = step * step;
        var step3 = step2 * step;

        var pre1 = 3.0 * step;
        var pre2 = 3.0 * step2;
        var pre4 = 6.0 * step2;
        var pre5 = 6.0 * step3;

        var tmp1x = x0 - x1 * 2.0 + x2;
        var tmp1y = y0 - y1 * 2.0 + y2;
        var tmp1z = z0 - z1 * 2.0 + z2;

        var tmp2x = (x1 - x2) * 3.0 - x0 + x3;
        var tmp2y = (y1 - y2) * 3.0 - y0 + y3;
        var tmp2z = (z1 - z2) * 3.0 - z0 + z3;

        var fx = x0;
        var fy = y0;
        var fz = z0;

        var dfx = (x1 - x0) * pre1 + tmp1x * pre2 + tmp2x * step3;
        var dfy = (y1 - y0) * pre1 + tmp1y * pre2 + tmp2y * step3;
        var dfz = (z1 - z0) * pre1 + tmp1z * pre2 + tmp2z * step3;

        var ddfx = tmp1x * pre4 + tmp2x * pre5;
        var ddfy = tmp1y * pre4 + tmp2y * pre5;
        var ddfz = tmp1z * pre4 + tmp2z * pre5;

        var dddfx = tmp2x * pre5;
        var dddfy = tmp2y * pre5;
        var dddfz = tmp2z * pre5;

        var t = 0;

        var k = 0;
        var segCount = Math.ceil(1 / step);

        var points = new Float32Array((segCount + 1) * 3);
        var points = [];
        var offset = 0;
        for (var k = 0; k < segCount + 1; k++) {
            points[offset++] = fx;
            points[offset++] = fy;
            points[offset++] = fz;

            fx += dfx; fy += dfy; fz += dfz;
            dfx += ddfx; dfy += ddfy; dfz += ddfz;
            ddfx += dddfx; ddfy += dddfy; ddfz += dddfz;
            t += step;
        }

        this.addPolyline(points, color, lineWidth);
    },

    /**
     * Add a straight line
     * @param {Array.<number>} p0
     * @param {Array.<number>} p1
     * @param {Array.<number>} color
     * @param {number} [lineWidth=1]
     */
    addLine: function (p0, p1, color, lineWidth) {
        this.addPolyline([p0, p1], color, lineWidth);
    },

    /**
     * Add a straight line
     * @param {Array.<Array> | Array.<number>} points
     * @param {Array.<number>} color
     * @param {number} [lineWidth=1]
     */
    addPolyline: function (points, color, lineWidth) {
        if (!points.length) {
            return;
        }

        var is2DArray = typeof points[0] !== 'number';
        var positionAttr = this.attributes.position;
        var positionPrevAttr = this.attributes.positionPrev;
        var positionNextAttr = this.attributes.positionNext;
        var colorAttr = this.attributes.color;
        var offsetAttr = this.attributes.offset;
        var faces = this.faces;

        if (lineWidth == null) {
            lineWidth = 1;
        }

        var vertexOffset = this._vertexOffset;
        var pointCount = is2DArray ? points.length : points.length / 3;
        var iterCount = !this.useNativeLine ? pointCount : (pointCount - 1);
        var point;
        for (var k = 0; k < iterCount; k++) {
            if (is2DArray) {
                point = points[k];
            }
            else {
                point = point || [];
                point[0] = points[k * 3];
                point[1] = points[k * 3 + 1];
                point[2] = points[k * 3 + 2];
            }
            if (!this.useNativeLine) {
                if (k < iterCount) {
                    // Set to next two points
                    positionPrevAttr.set(vertexOffset + 2, point);
                    positionPrevAttr.set(vertexOffset + 3, point);
                }
                if (k > 0) {
                    // Set to previous two points
                    positionNextAttr.set(vertexOffset - 2, point);
                    positionNextAttr.set(vertexOffset - 1, point);
                }

                positionAttr.set(vertexOffset, point);
                positionAttr.set(vertexOffset + 1, point);

                colorAttr.set(vertexOffset, color);
                colorAttr.set(vertexOffset + 1, color);

                offsetAttr.set(vertexOffset, lineWidth / 2);
                offsetAttr.set(vertexOffset + 1, -lineWidth / 2);

                vertexOffset += 2;
            }
            else {
                if (k > 0) {
                    positionAttr.copy(vertexOffset, vertexOffset - 1);
                    colorAttr.copy(vertexOffset, vertexOffset - 1);
                }
                else {
                    colorAttr.set(vertexOffset, color);
                    positionAttr.set(vertexOffset, point);
                }
                vertexOffset++;
            }

            if (!this.useNativeLine) {
                if (k > 0) {
                    var idx3 = this._faceOffset * 3;
                    var faces = this.faces;
                    // 0-----2
                    // 1-----3
                    // 0->1->2, 1->3->2
                    faces[idx3] = vertexOffset - 4;
                    faces[idx3 + 1] = vertexOffset - 3;
                    faces[idx3 + 2] = vertexOffset - 2;

                    faces[idx3 + 3] = vertexOffset - 3;
                    faces[idx3 + 4] = vertexOffset - 1;
                    faces[idx3 + 5] = vertexOffset - 2;

                    this._faceOffset += 2;
                }
            }
            else {
                colorAttr.set(vertexOffset, color);
                positionAttr.set(vertexOffset, point);
                vertexOffset++;
            }
        }
        if (!this.useNativeLine) {
            var start = this._vertexOffset;
            var end = this._vertexOffset + points.length * 2;
            positionPrevAttr.copy(start, start + 2);
            positionPrevAttr.copy(start + 1, start + 3);
            positionNextAttr.copy(end - 1, end - 3);
            positionNextAttr.copy(end - 2, end - 4);
        }

        this._vertexOffset = vertexOffset;
    }
});

module.exports = LinesGeometry;<|endoftext|>


<commit_before>/* eslint-disable */

import {
  convertStringToObj,
  hexToBase64,
  injectToXML,
} from '../src/utils';

import fixtures from './fixtures/utils';

describe('utils', () => {
  describe('#convertStringToObj', () => {
    test('should return object from string', () => {
      const str = 'CN=1, MN=2';
      const result = { CN: '1', MN: '2' };

      const subject = convertStringToObj(str);

      expect(subject).toEqual(result);
    });
  });

  describe('#hexToBase64', () => {
    test('should return base64 from hex', () => {
      const hex = 'a660b03bc56d364fce9c482632b9f864';
      const result = 'ZPi5MiZInM5PNm3FO7Bgpg==';

      const subject = hexToBase64(hex, '', hex.length - 2);

      expect(subject).toEqual(result);
    });
  });

  describe('#injectToXML', () => {
    test('should return transformed xml', () => {
      const signatureValue = '111';
      const x509certificate = '222';

      const subject = injectToXML(
        fixtures.injectToXML.xml,
        signatureValue,
        x509certificate,
      );

      expect(subject).toEqual(fixtures.injectToXML.result);
    });
  });
});
<commit_msg>[UPDATED] test for hexToBase64 function<commit_after>/* eslint-disable */

import {
  convertStringToObj,
  hexToBase64,
  injectToXML,
} from '../src/utils';

import fixtures from './fixtures/utils';

describe('utils', () => {
  describe('#convertStringToObj', () => {
    test('should return object from string', () => {
      const str = 'CN=1, MN=2';
      const result = { CN: '1', MN: '2' };

      const subject = convertStringToObj(str);

      expect(subject).toEqual(result);
    });
  });

  describe('#hexToBase64', () => {
    test('should return base64 from hex', () => {
      const hex = 'a660b03bc56d364fce9c482632b9f864';
      const result = 'ZPi5MiZInM5PNm3FO7Bgpg==';

      const subject = hexToBase64(hex);

      expect(subject).toEqual(result);
    });
  });

  describe('#injectToXML', () => {
    test('should return transformed xml', () => {
      const signatureValue = '111';
      const x509certificate = '222';

      const subject = injectToXML(
        fixtures.injectToXML.xml,
        signatureValue,
        x509certificate,
      );

      expect(subject).toEqual(fixtures.injectToXML.result);
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>Add tests for nested records<commit_after><|endoftext|>


<commit_before>(function () {
    function simpleHtmlParse(html) {
        // This code is to be replaced in a moment with something more intelligent
        var dummy = document.createElement("div");
        dummy.innerHTML = html;
        return ko.utils.makeArray(dummy.childNodes);
    }

    ko.utils.parseHtmlFragment = function(html) {
        return typeof jQuery != 'undefined' ? jQuery['clean']([html]) // As below, benefit from jQuery's optimisations where possible
                                            : simpleHtmlParse(html);  // ... otherwise, this simple logic will do in most common cases.
    };

    ko.utils.setHtml = function(node, html) {
        ko.utils.emptyDomNode(node);

        if ((html !== null) && (html !== undefined)) {
            if (typeof html != 'string')
                html = html.toString();

            // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
            // for example
 elements which are not normally allowed to exist on their own.
            // If you've referenced jQuery we'll use that rather than duplicating its code.
            if (typeof jQuery != 'undefined') {
                jQuery(node)['html'](html);
            } else {
                // ... otherwise, use KO's own parsing logic.
                var parsedNodes = ko.utils.parseHtmlFragment(html);
                for (var i = 0; i < parsedNodes.length; i++)
                    node.appendChild(parsedNodes[i]);
            }
        }
    };
})();<commit_msg>Smarter HTML parsing<commit_after>(function () {
    function simpleHtmlParse(html) {
        // Based on jQuery's "clean" function, but only accounting for table-related elements.
        // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly

        // Trim whitespace, otherwise indexOf won't work as expected
        var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");

        // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
        var wrap = tags.match(/^<(thead|tbody|tfoot)/)              && [1, "
", "
"] ||
                   !tags.indexOf("<tr")                             && [2, "

", "

"] ||
                   (!tags.indexOf("<td") || !tags.indexOf("<th"))   && [3, "

", "

"] ||
                   /* anything else */                                 [0, "", ""];

        // Go to html and back, then peel off extra wrappers
        div.innerHTML = wrap[1] + html + wrap[2];

        // Move to the right depth
        while (wrap[0]--)
            div = div.lastChild;

        return ko.utils.makeArray(div.childNodes);
    }

    ko.utils.parseHtmlFragment = function(html) {
        return typeof jQuery != 'undefined' ? jQuery['clean']([html]) // As below, benefit from jQuery's optimisations where possible
                                            : simpleHtmlParse(html);  // ... otherwise, this simple logic will do in most common cases.
    };

    ko.utils.setHtml = function(node, html) {
        ko.utils.emptyDomNode(node);

        if ((html !== null) && (html !== undefined)) {
            if (typeof html != 'string')
                html = html.toString();

            // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
            // for example
 elements which are not normally allowed to exist on their own.
            // If you've referenced jQuery we'll use that rather than duplicating its code.
            if (typeof jQuery != 'undefined') {
                jQuery(node)['html'](html);
            } else {
                // ... otherwise, use KO's own parsing logic.
                var parsedNodes = ko.utils.parseHtmlFragment(html);
                for (var i = 0; i < parsedNodes.length; i++)
                    node.appendChild(parsedNodes[i]);
            }
        }
    };
})();<|endoftext|>