<commit_before>var _ = require('underscore'),
    urlTools = require('../util/urlTools');

module.exports = function (queryObj) {
    return function registerRequireJsConfig(assetGraph) {
        assetGraph.requireJsConfig = assetGraph.requireJsConfig || {};
        assetGraph.requireJsConfig.paths = assetGraph.requireJsConfig.paths || {};
        assetGraph.requireJsConfig.resolveUrl = function (url) {
            var fragments = url.indexOf('/') !== -1 && url.split('/');
            if (fragments && fragments.length > 1 && fragments[0] in this.paths) {
                return urlTools.resolveUrl(this.paths[fragments[0]], fragments.slice(1).join('/'));
            } else if ('baseUrl' in this) {
                return urlTools.resolveUrl(this.baseUrl, url);
            } else {
                return url;
            }
        };

        assetGraph.requireJsConfig.registerConfigInJavaScript = function (javaScript, htmlAsset) {
            if (!htmlAsset) {
                var incomingRelationsFromHtml = assetGraph.findRelations({to: javaScript, from: {type: 'Html'}});
                if (incomingRelationsFromHtml.length > 0) {
                    htmlAsset = incomingRelationsFromHtml[0].from;
                }
            }
            if (htmlAsset) {
                var htmlUrl = htmlAsset.nonInlineAncestor.url;

                function extractRequireJsConfig(objAst) {
                    objAst[1].forEach(function (keyValueNode) {
                        if (keyValueNode[0] === 'baseUrl' && keyValueNode[1][0] === 'string') {
                            var baseUrl = keyValueNode[1][1].replace(/\/?$/, '/'); // Ensure trailing slash
                            if (/^\//.test(baseUrl) && /^file:/.test(assetGraph.root) && /^file:/.test(htmlUrl)) {
                                baseUrl = urlTools.resolveUrl(assetGraph.root, baseUrl.replace(/^\//, ''));
                            } else {
                                baseUrl = urlTools.resolveUrl(htmlUrl.replace(/[^\/]+([\?#].*)?$/, ''), baseUrl);
                            }

                            assetGraph.requireJsConfig.baseUrl = baseUrl;
                        }
                    });
                    objAst[1].forEach(function (keyValueNode) {
                        if (keyValueNode[0] === 'paths' && keyValueNode[1][0] === 'object') {
                            keyValueNode[1][1].forEach(function (pathNode) {
                                if (pathNode[1][0] === 'string') {
                                    var pathUrl = urlTools.resolveUrl(assetGraph.requireJsConfig.baseUrl || htmlUrl.replace(/[^\/]+([\?#].*)?$/, ''),
                                                                      pathNode[1][1]).replace(/\/?$/, '/');
                                    assetGraph.requireJsConfig.paths[pathNode[0]] = pathUrl;
                                }
                            });
                        }
                    });
                }

                javaScript.parseTree[1].forEach(function (topLevelStatement) {
                   if (topLevelStatement[0] === 'stat' && topLevelStatement[1][0] === 'call' &&
                        topLevelStatement[1][1][0] === 'dot' && topLevelStatement[1][1][1][0] === 'name' &&
                        topLevelStatement[1][1][1][1] === 'require' && topLevelStatement[1][1][2] === 'config' &&
                        topLevelStatement[1][2].length === 1 && topLevelStatement[1][2][0][0] === 'object') {

                        // ["stat",["call",["dot",["name","require"],"config"],[["object",[...]]]]]
                        extractRequireJsConfig(topLevelStatement[1][2][0]);
                    } else if (topLevelStatement[0] === 'var') {
                        topLevelStatement[1].forEach(function (node) {
                            if (node[0] === 'require' && node[1] && node[1][0] === 'object') {
                                // ["var",[["require",["object",[["foo",["num",1]]]]]]]
                                extractRequireJsConfig(node[1]);
                            }
                        });

                    }
                });
            }
        };

        assetGraph.on('addAsset', function (asset, htmlAsset) {
            if (asset.type === 'JavaScript' && asset.isLoaded) {
                assetGraph.requireJsConfig.registerConfigInJavaScript(asset, htmlAsset);
            } else {
                asset.on('load', function () {
                    assetGraph.requireJsConfig.registerConfigInJavaScript(asset);
                });
            }
        });
    };
};
<commit_msg>transforms.registerRequireJsConfig: Don't attempt to extract the config from not yet loaded non-JavaScript assets.<commit_after>var _ = require('underscore'),
    urlTools = require('../util/urlTools');

module.exports = function (queryObj) {
    return function registerRequireJsConfig(assetGraph) {
        assetGraph.requireJsConfig = assetGraph.requireJsConfig || {};
        assetGraph.requireJsConfig.paths = assetGraph.requireJsConfig.paths || {};
        assetGraph.requireJsConfig.resolveUrl = function (url) {
            var fragments = url.indexOf('/') !== -1 && url.split('/');
            if (fragments && fragments.length > 1 && fragments[0] in this.paths) {
                return urlTools.resolveUrl(this.paths[fragments[0]], fragments.slice(1).join('/'));
            } else if ('baseUrl' in this) {
                return urlTools.resolveUrl(this.baseUrl, url);
            } else {
                return url;
            }
        };

        assetGraph.requireJsConfig.registerConfigInJavaScript = function (javaScript, htmlAsset) {
            if (!htmlAsset) {
                var incomingRelationsFromHtml = assetGraph.findRelations({to: javaScript, from: {type: 'Html'}});
                if (incomingRelationsFromHtml.length > 0) {
                    htmlAsset = incomingRelationsFromHtml[0].from;
                }
            }
            if (htmlAsset) {
                var htmlUrl = htmlAsset.nonInlineAncestor.url;

                function extractRequireJsConfig(objAst) {
                    objAst[1].forEach(function (keyValueNode) {
                        if (keyValueNode[0] === 'baseUrl' && keyValueNode[1][0] === 'string') {
                            var baseUrl = keyValueNode[1][1].replace(/\/?$/, '/'); // Ensure trailing slash
                            if (/^\//.test(baseUrl) && /^file:/.test(assetGraph.root) && /^file:/.test(htmlUrl)) {
                                baseUrl = urlTools.resolveUrl(assetGraph.root, baseUrl.replace(/^\//, ''));
                            } else {
                                baseUrl = urlTools.resolveUrl(htmlUrl.replace(/[^\/]+([\?#].*)?$/, ''), baseUrl);
                            }

                            assetGraph.requireJsConfig.baseUrl = baseUrl;
                        }
                    });
                    objAst[1].forEach(function (keyValueNode) {
                        if (keyValueNode[0] === 'paths' && keyValueNode[1][0] === 'object') {
                            keyValueNode[1][1].forEach(function (pathNode) {
                                if (pathNode[1][0] === 'string') {
                                    var pathUrl = urlTools.resolveUrl(assetGraph.requireJsConfig.baseUrl || htmlUrl.replace(/[^\/]+([\?#].*)?$/, ''),
                                                                      pathNode[1][1]).replace(/\/?$/, '/');
                                    assetGraph.requireJsConfig.paths[pathNode[0]] = pathUrl;
                                }
                            });
                        }
                    });
                }

                javaScript.parseTree[1].forEach(function (topLevelStatement) {
                   if (topLevelStatement[0] === 'stat' && topLevelStatement[1][0] === 'call' &&
                        topLevelStatement[1][1][0] === 'dot' && topLevelStatement[1][1][1][0] === 'name' &&
                        topLevelStatement[1][1][1][1] === 'require' && topLevelStatement[1][1][2] === 'config' &&
                        topLevelStatement[1][2].length === 1 && topLevelStatement[1][2][0][0] === 'object') {

                        // ["stat",["call",["dot",["name","require"],"config"],[["object",[...]]]]]
                        extractRequireJsConfig(topLevelStatement[1][2][0]);
                    } else if (topLevelStatement[0] === 'var') {
                        topLevelStatement[1].forEach(function (node) {
                            if (node[0] === 'require' && node[1] && node[1][0] === 'object') {
                                // ["var",[["require",["object",[["foo",["num",1]]]]]]]
                                extractRequireJsConfig(node[1]);
                            }
                        });

                    }
                });
            }
        };

        assetGraph.on('addAsset', function (asset, htmlAsset) {
            if (asset.type === 'JavaScript') {
                if (asset.isLoaded) {
                    assetGraph.requireJsConfig.registerConfigInJavaScript(asset, htmlAsset);
                } else {
                    asset.on('load', function () {
                        assetGraph.requireJsConfig.registerConfigInJavaScript(asset);
                    });
                }
            }
        });
    };
};
<|endoftext|>


<commit_before>// Basic Javascript Elliptic Curve implementation
// Ported loosely from BouncyCastle's Java EC code
// Only Fp curves implemented for now

var assert = require('assert')
var BigInteger = require('bigi')

// constants
var THREE = BigInteger.valueOf(3)

function ECFieldElementFp(q,x) {
  this.x = x
  // TODO if (x.compareTo(q) >= 0) error
  this.q = q
}

function feFpEquals(other) {
  if (other == this) return true
  return (this.q.equals(other.q) && this.x.equals(other.x))
}

function feFpToBigInteger() {
  return this.x
}

function feFpNegate() {
  return new ECFieldElementFp(this.q, this.x.negate().mod(this.q))
}

function feFpAdd(b) {
  return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q))
}

function feFpSubtract(b) {
  return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q))
}

function feFpMultiply(b) {
  return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q))
}

function feFpSquare() {
  return new ECFieldElementFp(this.q, this.x.square().mod(this.q))
}

function feFpDivide(b) {
  return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q))
}

ECFieldElementFp.prototype.equals = feFpEquals
ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger
ECFieldElementFp.prototype.negate = feFpNegate
ECFieldElementFp.prototype.add = feFpAdd
ECFieldElementFp.prototype.subtract = feFpSubtract
ECFieldElementFp.prototype.multiply = feFpMultiply
ECFieldElementFp.prototype.square = feFpSquare
ECFieldElementFp.prototype.divide = feFpDivide

// ----------------
// ECPointFp

// constructor
function ECPointFp(curve,x,y,z) {
  this.curve = curve
  this.x = x
  this.y = y

  // Projective coordinates: either zinv == null or z * zinv == 1
  // z and zinv are just BigIntegers, not fieldElements
  if (z == null) {
    this.z = BigInteger.ONE

  } else {
    this.z = z
  }
  this.zinv = null

  //TODO: compression flag
}

function pointFpGetX() {
  if (this.zinv == null) {
    this.zinv = this.z.modInverse(this.curve.q)
  }

  return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))
}

function pointFpGetY() {
  if (this.zinv == null) {
    this.zinv = this.z.modInverse(this.curve.q)
  }

  return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))
}

function pointFpEquals(other) {
  if (other == this) return true
  if (this.isInfinity()) return other.isInfinity()
  if (other.isInfinity()) return this.isInfinity()

  // u = Y2 * Z1 - Y1 * Z2
  u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q)
  if (u.signum() !== 0) return false

  // v = X2 * Z1 - X1 * Z2
  v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q)
  return v.signum() === 0
}

function pointFpIsInfinity() {
  if ((this.x == null) && (this.y == null)) return true
  return this.z.signum() === 0 && this.y.toBigInteger().signum() !== 0
}

function pointFpNegate() {
  return new ECPointFp(this.curve, this.x, this.y.negate(), this.z)
}

function pointFpAdd(b) {
  if (this.isInfinity()) return b
  if (b.isInfinity()) return this

  var x1 = this.x.toBigInteger()
  var y1 = this.y.toBigInteger()
  var x2 = b.x.toBigInteger()
  var y2 = b.y.toBigInteger()

  // u = Y2 * Z1 - Y1 * Z2
  var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.q)
  // v = X2 * Z1 - X1 * Z2
  var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.q)

  if (v.signum() === 0) {
      if (u.signum() === 0) {
          return this.twice() // this == b, so double
      }

      return this.curve.getInfinity() // this = -b, so infinity
  }

  var v2 = v.square()
  var v3 = v2.multiply(v)
  var x1v2 = x1.multiply(v2)
  var zu2 = u.square().multiply(this.z)

  // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
  var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q)
  // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
  var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q)
  // z3 = v^3 * z1 * z2
  var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q)

  return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3)
}

function pointFpTwice() {
  if (this.isInfinity()) return this
  if (this.y.toBigInteger().signum() === 0) return this.curve.getInfinity()

  var x1 = this.x.toBigInteger()
  var y1 = this.y.toBigInteger()

  var y1z1 = y1.multiply(this.z)
  var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q)
  var a = this.curve.a.toBigInteger()

  // w = 3 * x1^2 + a * z1^2
  var w = x1.square().multiply(THREE)

  if (a.signum() !== 0) {
    w = w.add(this.z.square().multiply(a))
  }

  w = w.mod(this.curve.q)
  // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
  var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q)
  // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
  var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.q)
  // z3 = 8 * (y1 * z1)^3
  var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.q)

  return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3)
}

// Simple NAF (Non-Adjacent Form) multiplication algorithm
// TODO: modularize the multiplication algorithm
function pointFpMultiply(k) {
  if (this.isInfinity()) return this
  if (k.signum() === 0) return this.curve.getInfinity()

  var e = k
  var h = e.multiply(THREE)

  var neg = this.negate()
  var R = this

  for (var i = h.bitLength() - 2; i > 0; --i) {
    R = R.twice()

    var hBit = h.testBit(i)
    var eBit = e.testBit(i)

    if (hBit != eBit) {
        R = R.add(hBit ? this : neg)
    }
  }

  return R
}

// Compute this*j + x*k (simultaneous multiplication)
function pointFpMultiplyTwo(j,x,k) {
  var i

  if (j.bitLength() > k.bitLength())
    i = j.bitLength() - 1
  else
    i = k.bitLength() - 1

  var R = this.curve.getInfinity()
  var both = this.add(x)
  while (i >= 0) {
    R = R.twice()
    if (j.testBit(i)) {
      if (k.testBit(i)) {
        R = R.add(both)
      }
      else {
        R = R.add(this)
      }
    }
    else {
      if (k.testBit(i)) {
        R = R.add(x)
      }
    }
    --i
  }

  return R
}

ECPointFp.prototype.getX = pointFpGetX
ECPointFp.prototype.getY = pointFpGetY
ECPointFp.prototype.equals = pointFpEquals
ECPointFp.prototype.isInfinity = pointFpIsInfinity
ECPointFp.prototype.negate = pointFpNegate
ECPointFp.prototype.add = pointFpAdd
ECPointFp.prototype.twice = pointFpTwice
ECPointFp.prototype.multiply = pointFpMultiply
ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo

// ----------------
// ECCurveFp

// constructor
function ECCurveFp(q,a,b) {
  this.q = q
  this.a = this.fromBigInteger(a)
  this.b = this.fromBigInteger(b)
  this.infinity = new ECPointFp(this, null, null)
}

function curveFpGetQ() {
  return this.q
}

function curveFpGetA() {
  return this.a
}

function curveFpGetB() {
  return this.b
}

function curveFpEquals(other) {
  if (other == this) return true
  return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b))
}

function curveFpGetInfinity() {
  return this.infinity
}

function curveFpFromBigInteger(x) {
  return new ECFieldElementFp(this.q, x)
}

ECCurveFp.prototype.getQ = curveFpGetQ
ECCurveFp.prototype.getA = curveFpGetA
ECCurveFp.prototype.getB = curveFpGetB
ECCurveFp.prototype.equals = curveFpEquals
ECCurveFp.prototype.getInfinity = curveFpGetInfinity
ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger

ECFieldElementFp.prototype.getByteLength = function () {
  return Math.floor((this.toBigInteger().bitLength() + 7) / 8)
}

ECPointFp.prototype.getEncoded = function(compressed) {
  var x = this.getX().toBigInteger()
  var y = this.getY().toBigInteger()
  var buffer

  // 0x02/0x03 | X
  if (compressed) {
    buffer = new Buffer(33)
    buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)

  // 0x04 | X | Y
  } else {
    buffer = new Buffer(65)
    buffer.writeUInt8(0x04, 0)

    y.toBuffer(32).copy(buffer, 33)
  }

  x.toBuffer(32).copy(buffer, 1)

  return buffer
}

ECPointFp.decodeFrom = function (curve, buffer) {
  var type = buffer.readUInt8(0)
  var compressed = type !== 0x04
  var x = BigInteger.fromBuffer(buffer.slice(1, 33))
  var y

  if (compressed) {
    assert.equal(buffer.length, 33, 'Invalid sequence length')
    assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')

    var isYEven = (type === 0x02)
    var a = curve.getA().toBigInteger()
    var b = curve.getB().toBigInteger()
    var p = curve.getQ()

    // We precalculate (p + 1) / 4 where p is the field order
    if (!curve.P_OVER_FOUR) {
      curve.P_OVER_FOUR = p.add(BigInteger.ONE).shiftRight(2)
    }

    // Convert x to point
    var alpha = x.pow(3).add(a.multiply(x)).add(b).mod(p)
    var beta = alpha.modPow(curve.P_OVER_FOUR, p)

    // If beta is even, but y isn't, or vice versa, then convert it,
    // otherwise we're done and y == beta.
    y = (beta.isEven() ^ isYEven) ? p.subtract(beta) : beta

  } else {
    assert.equal(buffer.length, 65, 'Invalid sequence length')

    y = BigInteger.fromBuffer(buffer.slice(33))
  }

  var Q = new ECPointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y))

  return {
    Q: Q,
    compressed: compressed
  }
}

ECPointFp.prototype.isOnCurve = function () {
  var x = this.getX().toBigInteger()
  var y = this.getY().toBigInteger()
  var a = this.curve.getA().toBigInteger()
  var b = this.curve.getB().toBigInteger()
  var p = this.curve.getQ()
  var lhs = y.square().mod(p)
  var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
  return lhs.equals(rhs)
}

ECPointFp.prototype.toString = function () {
  return '('+this.getX().toBigInteger().toString()+','+
    this.getY().toBigInteger().toString()+')'
}

/**
 * Validate an elliptic curve point.
 *
 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
 */
ECPointFp.prototype.validate = function () {
  var n = this.curve.getQ()

  // Check Q != O
  if (this.isInfinity()) {
    throw new Error("Point is at infinity.")
  }

  // Check coordinate bounds
  var x = this.getX().toBigInteger()
  var y = this.getY().toBigInteger()
  if (x.compareTo(BigInteger.ONE) < 0 ||
      x.compareTo(n.subtract(BigInteger.ONE)) > 0) {
    throw new Error('x coordinate out of bounds')
  }
  if (y.compareTo(BigInteger.ONE) < 0 ||
      y.compareTo(n.subtract(BigInteger.ONE)) > 0) {
    throw new Error('y coordinate out of bounds')
  }

  // Check y^2 = x^3 + ax + b (mod n)
  if (!this.isOnCurve()) {
    throw new Error("Point is not on the curve.")
  }

  // Check nQ = 0 (Q is a scalar multiple of G)
  if (this.multiply(n).isInfinity()) {
    // TODO: This check doesn't work - fix.
    throw new Error("Point is not a scalar multiple of G.")
  }

  return true
}

module.exports = ECCurveFp
module.exports.ECPointFp = ECPointFp
<commit_msg>ec: compare strictly against null<commit_after>// Basic Javascript Elliptic Curve implementation
// Ported loosely from BouncyCastle's Java EC code
// Only Fp curves implemented for now

var assert = require('assert')
var BigInteger = require('bigi')

// constants
var THREE = BigInteger.valueOf(3)

function ECFieldElementFp(q,x) {
  this.x = x
  // TODO if (x.compareTo(q) >= 0) error
  this.q = q
}

function feFpEquals(other) {
  if (other == this) return true
  return (this.q.equals(other.q) && this.x.equals(other.x))
}

function feFpToBigInteger() {
  return this.x
}

function feFpNegate() {
  return new ECFieldElementFp(this.q, this.x.negate().mod(this.q))
}

function feFpAdd(b) {
  return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q))
}

function feFpSubtract(b) {
  return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q))
}

function feFpMultiply(b) {
  return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q))
}

function feFpSquare() {
  return new ECFieldElementFp(this.q, this.x.square().mod(this.q))
}

function feFpDivide(b) {
  return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q))
}

ECFieldElementFp.prototype.equals = feFpEquals
ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger
ECFieldElementFp.prototype.negate = feFpNegate
ECFieldElementFp.prototype.add = feFpAdd
ECFieldElementFp.prototype.subtract = feFpSubtract
ECFieldElementFp.prototype.multiply = feFpMultiply
ECFieldElementFp.prototype.square = feFpSquare
ECFieldElementFp.prototype.divide = feFpDivide

// ----------------
// ECPointFp

// constructor
function ECPointFp(curve,x,y,z) {
  this.curve = curve
  this.x = x
  this.y = y

  // Projective coordinates: either zinv == null or z * zinv == 1
  // z and zinv are just BigIntegers, not fieldElements
  this.z = (z == undefined) ? BigInteger.ONE : z
  this.zinv = null

  //TODO: compression flag
}

function pointFpGetX() {
  if (this.zinv === null) {
    this.zinv = this.z.modInverse(this.curve.q)
  }

  return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))
}

function pointFpGetY() {
  if (this.zinv === null) {
    this.zinv = this.z.modInverse(this.curve.q)
  }

  return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))
}

function pointFpEquals(other) {
  if (other == this) return true
  if (this.isInfinity()) return other.isInfinity()
  if (other.isInfinity()) return this.isInfinity()

  // u = Y2 * Z1 - Y1 * Z2
  u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q)
  if (u.signum() !== 0) return false

  // v = X2 * Z1 - X1 * Z2
  v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q)
  return v.signum() === 0
}

function pointFpIsInfinity() {
  if ((this.x === null) && (this.y === null)) return true
  return this.z.signum() === 0 && this.y.toBigInteger().signum() !== 0
}

function pointFpNegate() {
  return new ECPointFp(this.curve, this.x, this.y.negate(), this.z)
}

function pointFpAdd(b) {
  if (this.isInfinity()) return b
  if (b.isInfinity()) return this

  var x1 = this.x.toBigInteger()
  var y1 = this.y.toBigInteger()
  var x2 = b.x.toBigInteger()
  var y2 = b.y.toBigInteger()

  // u = Y2 * Z1 - Y1 * Z2
  var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.q)
  // v = X2 * Z1 - X1 * Z2
  var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.q)

  if (v.signum() === 0) {
      if (u.signum() === 0) {
          return this.twice() // this == b, so double
      }

      return this.curve.getInfinity() // this = -b, so infinity
  }

  var v2 = v.square()
  var v3 = v2.multiply(v)
  var x1v2 = x1.multiply(v2)
  var zu2 = u.square().multiply(this.z)

  // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
  var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q)
  // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
  var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q)
  // z3 = v^3 * z1 * z2
  var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q)

  return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3)
}

function pointFpTwice() {
  if (this.isInfinity()) return this
  if (this.y.toBigInteger().signum() === 0) return this.curve.getInfinity()

  var x1 = this.x.toBigInteger()
  var y1 = this.y.toBigInteger()

  var y1z1 = y1.multiply(this.z)
  var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q)
  var a = this.curve.a.toBigInteger()

  // w = 3 * x1^2 + a * z1^2
  var w = x1.square().multiply(THREE)

  if (a.signum() !== 0) {
    w = w.add(this.z.square().multiply(a))
  }

  w = w.mod(this.curve.q)
  // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
  var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q)
  // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
  var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.q)
  // z3 = 8 * (y1 * z1)^3
  var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.q)

  return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3)
}

// Simple NAF (Non-Adjacent Form) multiplication algorithm
// TODO: modularize the multiplication algorithm
function pointFpMultiply(k) {
  if (this.isInfinity()) return this
  if (k.signum() === 0) return this.curve.getInfinity()

  var e = k
  var h = e.multiply(THREE)

  var neg = this.negate()
  var R = this

  for (var i = h.bitLength() - 2; i > 0; --i) {
    R = R.twice()

    var hBit = h.testBit(i)
    var eBit = e.testBit(i)

    if (hBit != eBit) {
        R = R.add(hBit ? this : neg)
    }
  }

  return R
}

// Compute this*j + x*k (simultaneous multiplication)
function pointFpMultiplyTwo(j,x,k) {
  var i

  if (j.bitLength() > k.bitLength())
    i = j.bitLength() - 1
  else
    i = k.bitLength() - 1

  var R = this.curve.getInfinity()
  var both = this.add(x)
  while (i >= 0) {
    R = R.twice()
    if (j.testBit(i)) {
      if (k.testBit(i)) {
        R = R.add(both)
      }
      else {
        R = R.add(this)
      }
    }
    else {
      if (k.testBit(i)) {
        R = R.add(x)
      }
    }
    --i
  }

  return R
}

ECPointFp.prototype.getX = pointFpGetX
ECPointFp.prototype.getY = pointFpGetY
ECPointFp.prototype.equals = pointFpEquals
ECPointFp.prototype.isInfinity = pointFpIsInfinity
ECPointFp.prototype.negate = pointFpNegate
ECPointFp.prototype.add = pointFpAdd
ECPointFp.prototype.twice = pointFpTwice
ECPointFp.prototype.multiply = pointFpMultiply
ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo

// ----------------
// ECCurveFp

// constructor
function ECCurveFp(q,a,b) {
  this.q = q
  this.a = this.fromBigInteger(a)
  this.b = this.fromBigInteger(b)
  this.infinity = new ECPointFp(this, null, null)
}

function curveFpGetQ() {
  return this.q
}

function curveFpGetA() {
  return this.a
}

function curveFpGetB() {
  return this.b
}

function curveFpEquals(other) {
  if (other == this) return true
  return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b))
}

function curveFpGetInfinity() {
  return this.infinity
}

function curveFpFromBigInteger(x) {
  return new ECFieldElementFp(this.q, x)
}

ECCurveFp.prototype.getQ = curveFpGetQ
ECCurveFp.prototype.getA = curveFpGetA
ECCurveFp.prototype.getB = curveFpGetB
ECCurveFp.prototype.equals = curveFpEquals
ECCurveFp.prototype.getInfinity = curveFpGetInfinity
ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger

ECFieldElementFp.prototype.getByteLength = function () {
  return Math.floor((this.toBigInteger().bitLength() + 7) / 8)
}

ECPointFp.prototype.getEncoded = function(compressed) {
  var x = this.getX().toBigInteger()
  var y = this.getY().toBigInteger()
  var buffer

  // 0x02/0x03 | X
  if (compressed) {
    buffer = new Buffer(33)
    buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)

  // 0x04 | X | Y
  } else {
    buffer = new Buffer(65)
    buffer.writeUInt8(0x04, 0)

    y.toBuffer(32).copy(buffer, 33)
  }

  x.toBuffer(32).copy(buffer, 1)

  return buffer
}

ECPointFp.decodeFrom = function (curve, buffer) {
  var type = buffer.readUInt8(0)
  var compressed = type !== 0x04
  var x = BigInteger.fromBuffer(buffer.slice(1, 33))
  var y

  if (compressed) {
    assert.equal(buffer.length, 33, 'Invalid sequence length')
    assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')

    var isYEven = (type === 0x02)
    var a = curve.getA().toBigInteger()
    var b = curve.getB().toBigInteger()
    var p = curve.getQ()

    // We precalculate (p + 1) / 4 where p is the field order
    if (!curve.P_OVER_FOUR) {
      curve.P_OVER_FOUR = p.add(BigInteger.ONE).shiftRight(2)
    }

    // Convert x to point
    var alpha = x.pow(3).add(a.multiply(x)).add(b).mod(p)
    var beta = alpha.modPow(curve.P_OVER_FOUR, p)

    // If beta is even, but y isn't, or vice versa, then convert it,
    // otherwise we're done and y == beta.
    y = (beta.isEven() ^ isYEven) ? p.subtract(beta) : beta

  } else {
    assert.equal(buffer.length, 65, 'Invalid sequence length')

    y = BigInteger.fromBuffer(buffer.slice(33))
  }

  var Q = new ECPointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y))

  return {
    Q: Q,
    compressed: compressed
  }
}

ECPointFp.prototype.isOnCurve = function () {
  var x = this.getX().toBigInteger()
  var y = this.getY().toBigInteger()
  var a = this.curve.getA().toBigInteger()
  var b = this.curve.getB().toBigInteger()
  var p = this.curve.getQ()
  var lhs = y.square().mod(p)
  var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
  return lhs.equals(rhs)
}

ECPointFp.prototype.toString = function () {
  return '('+this.getX().toBigInteger().toString()+','+
    this.getY().toBigInteger().toString()+')'
}

/**
 * Validate an elliptic curve point.
 *
 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
 */
ECPointFp.prototype.validate = function () {
  var n = this.curve.getQ()

  // Check Q != O
  if (this.isInfinity()) {
    throw new Error("Point is at infinity.")
  }

  // Check coordinate bounds
  var x = this.getX().toBigInteger()
  var y = this.getY().toBigInteger()
  if (x.compareTo(BigInteger.ONE) < 0 ||
      x.compareTo(n.subtract(BigInteger.ONE)) > 0) {
    throw new Error('x coordinate out of bounds')
  }
  if (y.compareTo(BigInteger.ONE) < 0 ||
      y.compareTo(n.subtract(BigInteger.ONE)) > 0) {
    throw new Error('y coordinate out of bounds')
  }

  // Check y^2 = x^3 + ax + b (mod n)
  if (!this.isOnCurve()) {
    throw new Error("Point is not on the curve.")
  }

  // Check nQ = 0 (Q is a scalar multiple of G)
  if (this.multiply(n).isInfinity()) {
    // TODO: This check doesn't work - fix.
    throw new Error("Point is not a scalar multiple of G.")
  }

  return true
}

module.exports = ECCurveFp
module.exports.ECPointFp = ECPointFp
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------------
//- functions
//---------------------------------------------------------------------------------
'use strict;'
var R = require('ramda');
var log = console.log;

getPath = function(url) {
  var path = url.substring(url.indexOf('api'), url.length);
  return exports.trimLeftAndRight(path, '/');
}

exports.atob = function(str) {
  var res = new Buffer(str, 'ascii').toString('base64');
  return res.replace('+', '-').replace('/', '_').replace('=', ',');
}

exports.btoa = function(str) {
  var res = new Buffer(str, 'base64').toString('ascii');
  return res.replace('-', '+').replace('_', '/').replace(',', '=');
}

//- api/apples || api/apples/abc3b4=1
exports.getId = function(url) {
  var path = getPath(url);
  var tokens = path.split('/');
  var id = exports.btoa(tokens[tokens.length - 1]);
  if (isNaN(id)) return 0;
  return id;
}

//- api/apples/123456/create
exports.getIdAndRel = function(url) {
  var path = getPath(url);
  var idAndRel = { id: 0, rel: ''};
  var tokens = path.split('/')
  tokens = exports.btoa(tokens[tokens.length - 1]).split('/');
  if (tokens.length === 2) {
    idAndRel.id = tokens[0];
    idAndRel.rel = tokens[1];
  }
  else {
    idAndRel.rel = tokens[0];
  }
  return idAndRel;
}

exports.trimLeftAndRight = function(str, ch) {
  return str.replace(new RegExp("^[" + ch + "]+"), "").replace(new RegExp("[" + ch + "]+$"), "");
}

exports.getLinks = function(entity) {
  var states = R.filter(function(m) { return m.startsWith('state_') }, Object.keys(entity));
  for (var i = 0; i < states.length; i++) {
    var links = entity[states[i]]();
    if (links !== false) {
      return links;
    }
  }
  throw { statusCode: 500, message: 'Internal Server Error', log: 'Invalid state invariants: ' + JSON.stringify(entity) };
}

//- api/apples/123456/create
exports.getTypeFromPath = function(url) {
  var path = getPath(url);
  var tokens = path.split('/');
  if (tokens.length > 1) {
    return tokens[1].slice(0, -1);
  }
  throw { statusCode: 500, message: 'Internal Server Error', log: 'Not an API call: ' + path };
}

exports.contains = R.contains;
exports.filter = R.filter;
exports.each = R.each;
exports.some = R.some;
exports.diff = R.difference;
exports.map = R.map;
<commit_msg>refactor<commit_after>//---------------------------------------------------------------------------------
//- functions
//---------------------------------------------------------------------------------
'use strict;'
var R = require('ramda');
exports.contains = R.contains;
exports.filter = R.filter;
exports.each = R.each;
exports.some = R.some;
exports.diff = R.difference;
exports.map = R.map;

var log = console.log;

function getTokens(url) {
  var path = url.substring(url.indexOf('api'), url.length);
  return exports.trimLeftAndRight(path, '/').split('/');
}

exports.atob = function(str) {
  var res = new Buffer(str, 'ascii').toString('base64');
  return res.replace('+', '-').replace('/', '_').replace('=', ',');
}

exports.btoa = function(str) {
  var res = new Buffer(str, 'base64').toString('ascii');
  return res.replace('-', '+').replace('_', '/').replace(',', '=');
}

//- api/apples || api/apples/abc3b4=1
exports.getId = function(url) {
  var tokens = getTokens(url);
  var id = exports.btoa(tokens[tokens.length - 1]);
  if (isNaN(id)) return 0;
  return id;
}

//- api/apples/123456/create
exports.getIdAndRel = function(url) {
  var tokens = getTokens(url);
  var idAndRel = { id: 0, rel: ''};
  tokens = exports.btoa(tokens[tokens.length - 1]).split('/');
  if (tokens.length === 2) {
    idAndRel.id = tokens[0];
    idAndRel.rel = tokens[1];
  }
  else {
    idAndRel.rel = tokens[0];
  }
  return idAndRel;
}

exports.trimLeftAndRight = function(str, ch) {
  return str.replace(new RegExp("^[" + ch + "]+"), "").replace(new RegExp("[" + ch + "]+$"), "");
}

exports.getLinks = function(entity) {
  var states = R.filter(function(m) { return m.startsWith('state_') }, Object.keys(entity));
  for (var i = 0; i < states.length; i++) {
    var links = entity[states[i]]();
    if (links !== false) {
      return links;
    }
  }
  throw { statusCode: 500, message: 'Internal Server Error', log: 'Invalid state invariants: ' + JSON.stringify(entity) };
}

//- api/apples/123456/create
exports.getTypeFromPath = function(url) {
  var tokens = getTokens(url);
  if (tokens.length > 1) {
    return tokens[1].slice(0, -1);
  }
  throw { statusCode: 500, message: 'Internal Server Error', log: 'Not an API call: ' + path };
}

<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
"use strict";
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*global _GPF_FS_TYPE_NOT_FOUND*/ // _GPF_FS_TYPE_NOT_FOUND
/*global _GPF_FS_TYPE_FILE*/ // _GPF_FS_TYPE_FILE
/*global _GPF_FS_TYPE_DIRECTORY*/ // _GPF_FS_TYPE_DIRECTORY
/*global _GPF_FS_TYPE_UNKNOWN*/ // _GPF_FS_TYPE_UNKNOWN
/*global _gpfSetReadOnlyProperty*/ // gpf.setReadOnlyProperty
/*#endif*/

gpf.fs = {

    /**
     * Get information on the provided file path
     *
     * @param {*} path
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event gpf.events.EVENT_READY
     * @eventParam {Object} info contains:
     * - type {Number} see _GPF_FS_TYPE_xxx
     * - size {Number}
     * - createdDateTime
     * - modifiedDateTime
     */
    getInfo: function (path, eventsHandler) {
        _gpfIgnore(path);
        _gpfIgnore(eventsHandler);
        throw gpf.Error.Abstract();
    },

    /**
     * Read as a binary stream
     *
     * @param {*} path
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event gpf.events.EVENT_READY
     * @eventParam {gpf.interface.IReadableStream} stream
     */
    readAsBinaryStream: function (path, eventsHandler) {
        _gpfIgnore(path);
        _gpfIgnore(eventsHandler);
        throw gpf.Error.Abstract();
    },

    /**
     * Write as a binary stream (overwrite file if it exists)
     *
     * @param {*} path
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event gpf.events.EVENT_READY
     * @eventParam {gpf.interface.IWritableStream} stream
     */
    writeAsBinaryStream: function (path, eventsHandler) {
        _gpfIgnore(path);
        _gpfIgnore(eventsHandler);
        throw gpf.Error.Abstract();
    },

    /**
     * Close the underlying file: the stream becomes unusable
     *
     * @param {gpf.interfaces.IReadableStream|
     * gpf.interfaces.IWritableStream} stream
     */
    close: function (stream) {
        _gpfIgnore(stream);
        throw gpf.Error.Abstract();
    }

};

// Create file system constants
(function () {
    var gpfFs = gpf.fs,
        mappings = {
            TYPE_NOT_FOUND: _GPF_FS_TYPE_NOT_FOUND,
            TYPE_FILE: _GPF_FS_TYPE_FILE,
            TYPE_DIRECTORY: _GPF_FS_TYPE_DIRECTORY,
            TYPE_UNKNOWN: _GPF_FS_TYPE_UNKNOWN
        },
        key;
    for (key in mappings) {
        if (mappings.hasOwnProperty(key)) {
            _gpfSetReadOnlyProperty(gpfFs, key, mappings[key]);
        }
    }

}());<commit_msg>fs find WIP<commit_after>/*#ifndef(UMD)*/
"use strict";
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*global _GPF_FS_TYPE_NOT_FOUND*/ // _GPF_FS_TYPE_NOT_FOUND
/*global _GPF_FS_TYPE_FILE*/ // _GPF_FS_TYPE_FILE
/*global _GPF_FS_TYPE_DIRECTORY*/ // _GPF_FS_TYPE_DIRECTORY
/*global _GPF_FS_TYPE_UNKNOWN*/ // _GPF_FS_TYPE_UNKNOWN
/*global _gpfSetReadOnlyProperty*/ // gpf.setReadOnlyProperty
/*#endif*/

gpf.fs = {

    /**
     * Get information on the provided file path
     *
     * @param {*} path
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event gpf.events.EVENT_READY
     * @eventParam {Object} info contains:
     * - type {Number} see _GPF_FS_TYPE_xxx
     * - size {Number}
     * - createdDateTime
     * - modifiedDateTime
     */
    getInfo: function (path, eventsHandler) {
        _gpfIgnore(path);
        _gpfIgnore(eventsHandler);
        throw gpf.Error.Abstract();
    },

    /**
     * Read as a binary stream
     *
     * @param {*} path
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event gpf.events.EVENT_READY
     * @eventParam {gpf.interface.IReadableStream} stream
     */
    readAsBinaryStream: function (path, eventsHandler) {
        _gpfIgnore(path);
        _gpfIgnore(eventsHandler);
        throw gpf.Error.Abstract();
    },

    /**
     * Write as a binary stream (overwrite file if it exists)
     *
     * @param {*} path
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event gpf.events.EVENT_READY
     * @eventParam {gpf.interface.IWritableStream} stream
     */
    writeAsBinaryStream: function (path, eventsHandler) {
        _gpfIgnore(path);
        _gpfIgnore(eventsHandler);
        throw gpf.Error.Abstract();
    },

    /**
     * Close the underlying file: the stream becomes unusable
     *
     * @param {gpf.interfaces.IReadableStream|
     * gpf.interfaces.IWritableStream} stream
     */
    close: function (stream) {
        _gpfIgnore(stream);
        throw gpf.Error.Abstract();
    },

    /**
     * Find and identify files matching the pattern, trigger a file event
     * when a file is found
     *
     * @param {String} basePath
     * @param {String[]} filters Patterns (see gpf.path.match) of files to
     * detect
     * @param {gpf.events.Handler} eventsHandler
     *
     * @event gpf.events.EVENT_DATA
     * a matching file has been identified
     * @eventParam {String} path
     *
     * @event gpf.events.EVENT_END_OF_DATA
     */
    find: function (basePath, filters, eventsHandler) {
        var
            pendingCount = 0,
            match = _gpf.path.match;
        filters = _gpf.path.compileMatchPattern(filters);
        function _explore(currentPath) {
            ++pendingCount;
            _fs.stat(currentPath, function (err, stat) {
                if (err) {
                    console.error(err);
                } else if (stat && stat.isDirectory()) {
                    // Folder
                    ++pendingCount;
                    _fs.readdir(currentPath, function (err, list) {
                        var
                            len,
                            idx;
                        if (err) {
                            console.error(err);
                        } else {
                            len = list.length;
                            for (idx = 0; idx < len; ++idx) {
                                _explore(_path.join(currentPath, list[idx]));
                            }
                        }
                        if (0 === --pendingCount) {
                            _gpfEventsFire("done", eventsHandler);
                        }
                    });
                } else {
                    if (match(filters, currentPath)) {
                        _gpfEventsFire("file", {
                            path: currentPath
                        }, eventsHandler);
                    }
                }
                if (0 === --pendingCount) {
                    _gpfEventsFire("done", eventsHandler);
                }
            });
        }
        _explore(basePath);
    }

};

// Create file system constants
(function () {
    var gpfFs = gpf.fs,
        mappings = {
            TYPE_NOT_FOUND: _GPF_FS_TYPE_NOT_FOUND,
            TYPE_FILE: _GPF_FS_TYPE_FILE,
            TYPE_DIRECTORY: _GPF_FS_TYPE_DIRECTORY,
            TYPE_UNKNOWN: _GPF_FS_TYPE_UNKNOWN
        },
        key;
    for (key in mappings) {
        if (mappings.hasOwnProperty(key)) {
            _gpfSetReadOnlyProperty(gpfFs, key, mappings[key]);
        }
    }

}());<|endoftext|>


<commit_before>// Overwrite Django's `dismissRelatedLookupPopup` to trigger a change event
// on the value change, so Salmonella can catch it and update the associated
// label.
function dismissRelatedLookupPopup(win, chosenId) {
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
        elem.value += ',' + chosenId;
    } else {
        elem.value = chosenId;
    }
    django.jQuery(elem).trigger('change');
    win.close();
}

(function($) {
    $(document).ready(function($) {

        function update_salmonella_label(element, multi){
            var name = element.next("a").attr("data-name"),
                app = element.next("a").attr("data-app"),
                model = element.next("a").attr("data-model"),
                value = element.val(),
                MOUNT_URL = window.SALMONELLA_MOUNT_URL || "/admin/salmonella",
                admin_url_parts = window.location.pathname.split("/").slice(1, 4);

            var url = MOUNT_URL;
            if (multi === true) {
                url = url + "/" + app + "/" + model + "/multiple/";
            } else {
                url = url + "/" + app + "/" + model + "/";
            }
            try {
                // only fire the ajax call if we have all the required info
                if ((name !== undefined) &&
                    (url !== undefined) &&
                    (value !== undefined) && (value !== "")) {
                    // Handles elements added via the TabularInline add row functionality
                    if (name.search(/__prefix__/) != -1){
                        name = element.attr("id").replace("id_", "");
                    }

                    $.ajax({
                        url: url,
                        data: {"id": value},
                        success: function(data){
                            $("#" + name + "_salmonella_label").html(" " + data);
                        }
                    });
                }
            } catch (e) {
                console.log("Oups, we have a problem" + e);
            }
        }

        $(".vForeignKeyRawIdAdminField").change(function(e){
            var $this = $(this);
            update_salmonella_label($this, mutli=false);
            e.stopPropagation();
        });

        // Handle ManyToManyRawIdAdminFields.
        $(".vManyToManyRawIdAdminField").change(function(e){
            var $this = $(this);
            update_salmonella_label($this, multi=true);
            e.stopPropagation();
        });

        // Clear both the input field and the labels
        $(".salmonella-clear-field").click(function(e){
            var $this = $(this);
            $this.parent().find('input').val("");
            $this.parent().find(".salmonella_label").empty();
        });

        // Open up the pop up window and set the focus in the input field
        $(".salmonella-related-lookup").click(function(e){
            // Actual Django javascript function
            showRelatedObjectLookupPopup(this);

            // Set the focus into the input field
            $(this).parent().find('input').focus();
            return false;
        });

        // Fire the event to update the solmonella fields on loads
        $(".vManyToManyRawIdAdminField").trigger('change');
        $(".vForeignKeyRawIdAdminField").trigger('change');
    });
})(django.jQuery);
<commit_msg>Comportamento não trabalhava corretamente com inlines no Django<commit_after>// Overwrite Django's `dismissRelatedLookupPopup` to trigger a change event
// on the value change, so Salmonella can catch it and update the associated
// label.
function dismissRelatedLookupPopup(win, chosenId) {
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
        elem.value += ',' + chosenId;
    } else {
        elem.value = chosenId;
    }
    django.jQuery(elem).trigger('change');
    win.close();
}

(function($) {
    $(document).ready(function($) {

        function update_salmonella_label(element, multi){
            var name = element.next("a").attr("data-name"),
                app = element.next("a").attr("data-app"),
                model = element.next("a").attr("data-model"),
                value = element.val(),
                MOUNT_URL = window.SALMONELLA_MOUNT_URL || "/admin/salmonella",
                admin_url_parts = window.location.pathname.split("/").slice(1, 4);

            var url = MOUNT_URL;
            if (multi === true) {
                url = url + "/" + app + "/" + model + "/multiple/";
            } else {
                url = url + "/" + app + "/" + model + "/";
            }
            try {
                // only fire the ajax call if we have all the required info
                if ((name !== undefined) &&
                    (url !== undefined) &&
                    (value !== undefined) && (value !== "")) {
                    // Handles elements added via the TabularInline add row functionality
                    if (name.search(/__prefix__/) != -1){
                        name = element.attr("id").replace("id_", "");
                    }

                    $.ajax({
                        url: url,
                        data: {"id": value},
                        success: function(data){
                            $("#" + name + "_salmonella_label").html(" " + data);
                        }
                    });
                }
            } catch (e) {
                console.log("Oups, we have a problem" + e);
            }
        }

        $(".vForeignKeyRawIdAdminField").change(function(e){
            var $this = $(this);
            update_salmonella_label($this, mutli=false);
            e.stopPropagation();
        });

        // Handle ManyToManyRawIdAdminFields.
        $(".vManyToManyRawIdAdminField").change(function(e){
            var $this = $(this);
            update_salmonella_label($this, multi=true);
            e.stopPropagation();
        });

        // Clear both the input field and the labels
        $(".salmonella-clear-field").click(function(e){
            var $this = $(this);
            $this.parent().find('.vForeignKeyRawIdAdminField, .vManyToManyRawIdAdminField').val("");
            $this.parent().find(".salmonella_label").empty();
        });

        // Open up the pop up window and set the focus in the input field
        $(".salmonella-related-lookup").click(function(e){
            // Actual Django javascript function
            showRelatedObjectLookupPopup(this);

            // Set the focus into the input field
            $(this).parent().find('input').focus();
            return false;
        });

        // Fire the event to update the solmonella fields on loads
        $(".vManyToManyRawIdAdminField").trigger('change');
        $(".vForeignKeyRawIdAdminField").trigger('change');
    });
})(django.jQuery);
<|endoftext|>


<commit_before>/**
 * Copyright 2020 The Google Earth Engine Community Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Earth Engine Developer's Guide examples
 *     from DataTable charting section
 */

// [START earthengine__charts_datatable__manual_datatable]
// Define a DataTable using a JavaScript array with a column property header.
var dataTable = [
  [
    {label: 'State', role: 'domain', type: 'string'},
    {label: 'Population', role: 'data', type: 'number'},
    {label: 'Pop. annotation', role: 'annotation', type: 'string'}
  ],
  ['CA', 37253956, '37.2e6'],
  ['NY', 19378102, '19.3e6'],
  ['IL', 12830632, '12.8e6'],
  ['MI', 9883640, '9.8e6'],
  ['OR', 3831074, '3.8e6']
];

// Define the chart and print it to the console.
var chart = ui.Chart(dataTable).setChartType('ColumnChart').setOptions({
  title: 'State Population (US census, 2010)',
  legend: {position: 'none'},
  hAxis: {title: 'State', titleTextStyle: {italic: false, bold: true}},
  vAxis: {title: 'Population', titleTextStyle: {italic: false, bold: true}},
  colors: ['1d6b99']
});
print(chart);
// [END earthengine__charts_datatable__manual_datatable]

// [START earthengine__charts_datatable__computed_datatable_by_date]
// Import the example feature collection and subset the forest feature.
var forest = ee.FeatureCollection('projects/google/charts_feature_example')
                 .filter(ee.Filter.eq('label', 'Forest'));

// Load MODIS vegetation indices data and subset a decade of images.
var vegIndices = ee.ImageCollection('MODIS/006/MOD13A1')
                     .filter(ee.Filter.date('2010-01-01', '2020-01-01'))
                     .select(['NDVI', 'EVI']);

// Define a function to format an image timestamp as a JavaScript Date string.
function formatDate(img) {
  var year = img.date().get('year').format();
  var month = img.date().get('month').subtract(1).format(); // zero-based month
  var day = img.date().get('day').format();
  return ee.String('Date(')
    .cat(year).cat(',')
    .cat(month).cat(',')
    .cat(day).cat(')');
}

// Build a feature collection where each feature has a property that represents
// a DataFrame row.
var reductionTable = vegIndices.map(function(img) {
  // Reduce the image to the mean of pixels intersecting the forest ecoregion.
  var stat = img.reduceRegion(
      {reducer: ee.Reducer.mean(), geometry: forest, scale: 500});

  // Extract the reduction results along with the image date.
  var date = formatDate(img);   // x-axis values.
  var evi = stat.get('EVI');    // y-axis series 1 values.
  var ndvi = stat.get('NDVI');  // y-axis series 2 values.

  // Make a list of observation attributes to define a row in the DataTable.
  var row = ee.List([date, evi, ndvi]);

  // Return the row as a property of an ee.Feature.
  return ee.Feature(null, {'row': row});
});

// Aggregate the 'row' property from all features in the new feature collection
// to make a server-side 2-D list (DataTable).
var dataTableServer = reductionTable.aggregate_array('row');

// Define column names and properties for the DataTable. The order should
// correspond to the order in the construction of the 'row' property above.
var columnHeader = ee.List([[
  {label: 'Date', role: 'domain', type: 'date'},
  {label: 'EVI', role: 'data', type: 'number'},
  {label: 'NDVI', role: 'data', type: 'number'}
]]);

// Concatenate the column header to the table.
dataTableServer = columnHeader.cat(dataTableServer);

// Use 'evaluate' to transfer the server-side table to the client, define the
// chart and print it to the console.
dataTableServer.evaluate(function(dataTableClient) {
  var chart = ui.Chart(dataTableClient).setOptions({
    title: 'Average Vegetation Index Value by Date for Forest',
    hAxis: {
      title: 'Date',
      titleTextStyle: {italic: false, bold: true},
    },
    vAxis: {
      title: 'Vegetation index (x1e4)',
      titleTextStyle: {italic: false, bold: true}
    },
    lineWidth: 5,
    colors: ['e37d05', '1d6b99'],
    curveType: 'function'
  });
  print(chart);
});
// [END earthengine__charts_datatable__computed_datatable_by_date]

// [START earthengine__charts_datatable__computed_datatable_by_doy_area]
// Define a point to extract an NDVI time series for.
var geometry = ee.Geometry.Point([-121.679, 36.479]);

// Define a band of interest (NDVI), import the MODIS vegetation index dataset,
// and select the band.
var band = 'NDVI';
var ndviCol = ee.ImageCollection('MODIS/006/MOD13Q1').select(band);

// Map over the collection to add a day of year (doy) property to each image.
ndviCol = ndviCol.map(function(img) {
  var doy = ee.Date(img.get('system:time_start')).getRelative('day', 'year');
  // Add 8 to day of year number so that the doy label represents the middle of
  // the 16-day MODIS NDVI composite.
  return img.set('doy', ee.Number(doy).add(8));
});

// Join all coincident day of year observations into a set of image collections.
var distinctDOY = ndviCol.filterDate('2013-01-01', '2014-01-01');
var filter = ee.Filter.equals({leftField: 'doy', rightField: 'doy'});
var join = ee.Join.saveAll('doy_matches');
var joinCol = ee.ImageCollection(join.apply(distinctDOY, ndviCol, filter));

// Calculate the absolute range, interquartile range, and median for the set
// of images composing each coincident doy observation group. The result is
// an image collection with an image representative per unique doy observation
// with bands that describe the 0, 25, 50, 75, 100 percentiles for the set of
// coincident doy images.
var comp = ee.ImageCollection(joinCol.map(function(img) {
  var doyCol = ee.ImageCollection.fromImages(img.get('doy_matches'));

  return doyCol
      .reduce(ee.Reducer.percentile(
          [0, 25, 50, 75, 100], ['p0', 'p25', 'p50', 'p75', 'p100']))
      .set({'doy': img.get('doy')});
}));

// Extract the inter-annual NDVI doy percentile statistics for the
// point of interest per unique doy representative. The result is
// is a feature collection where each feature is a doy representative that
// contains a property (row) describing the respective inter-annual NDVI
// variance, formatted as a list of values.
var reductionTable = comp.map(function(img) {
  var stats = ee.Dictionary(img.reduceRegion(
      {reducer: ee.Reducer.first(), geometry: geometry, scale: 250}));

  // Order the percentile reduction elements according to how you want columns
  // in the DataTable arranged (x-axis values need to be first).
  var row = ee.List([
    img.get('doy'),            // x-axis, day of year.
    stats.get(band + '_p50'),  // y-axis, median.
    stats.get(band + '_p0'),   // y-axis, min interval.
    stats.get(band + '_p25'),  // y-axis, 1st quartile interval.
    stats.get(band + '_p75'),  // y-axis, 3rd quartile interval.
    stats.get(band + '_p100')  // y-axis, max interval.
  ]);

  // Return the row as a property of an ee.Feature.
  return ee.Feature(null, {row: row});
});

// Aggregate the 'row' properties to make a server-side 2-D array (DataTable).
var dataTableServer = reductionTable.aggregate_array('row');

// Define column names and properties for the DataTable. The order should
// correspond to the order in the construction of the 'row' property above.
var columnHeader = ee.List([[
  {label: 'Day of year', role: 'domain'},
  {label: 'Median', role: 'data'},
  {label: 'p0', role: 'interval'},
  {label: 'p25', role: 'interval'},
  {label: 'p75', role: 'interval'},
  {label: 'p100', role: 'interval'}
]]);

// Concatenate the column header to the table.
dataTableServer = columnHeader.cat(dataTableServer);

// Use 'evaluate' to transfer the server-side table to the client, define the
// chart and print it to the console.
dataTableServer.evaluate(function(dataTableClient) {
  var chart = ui.Chart(dataTableClient).setChartType('LineChart').setOptions({
    title: 'Annual NDVI Time Series with Inter-Annual Variance',
    intervals: {style: 'area'},
    hAxis: {
      title: 'Day of year',
      titleTextStyle: {italic: false, bold: true},
    },
    vAxis: {title: 'NDVI (x1e4)', titleTextStyle: {italic: false, bold: true}},
    colors: ['0f8755'],
    legend: {position: 'none'}
  });
  print(chart);
});
// [END earthengine__charts_datatable__computed_datatable_by_doy_area]

// [START earthengine__charts_datatable__computed_datatable_by_doy_bar]
dataTableServer.evaluate(function(dataTableClient) {
  var chart = ui.Chart(dataTableClient).setChartType('LineChart').setOptions({
    title: 'Annual NDVI Time Series with Inter-Annual Variance',
    intervals: {style: 'boxes', barWidth: 1, boxWidth: 1, lineWidth: 0},
    hAxis: {
      title: 'Day of year',
      titleTextStyle: {italic: false, bold: true},
    },
    vAxis: {title: 'NDVI (x1e4)', titleTextStyle: {italic: false, bold: true}},
    colors: ['0f8755'],
    legend: {position: 'none'}
  });
  print(chart);
});
// [END earthengine__charts_datatable__computed_datatable_by_doy_bar]
<commit_msg>[Guide Example] Refactor date construction in DataTable chart example<commit_after>/**
 * Copyright 2020 The Google Earth Engine Community Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Earth Engine Developer's Guide examples
 *     from DataTable charting section
 */

// [START earthengine__charts_datatable__manual_datatable]
// Define a DataTable using a JavaScript array with a column property header.
var dataTable = [
  [
    {label: 'State', role: 'domain', type: 'string'},
    {label: 'Population', role: 'data', type: 'number'},
    {label: 'Pop. annotation', role: 'annotation', type: 'string'}
  ],
  ['CA', 37253956, '37.2e6'],
  ['NY', 19378102, '19.3e6'],
  ['IL', 12830632, '12.8e6'],
  ['MI', 9883640, '9.8e6'],
  ['OR', 3831074, '3.8e6']
];

// Define the chart and print it to the console.
var chart = ui.Chart(dataTable).setChartType('ColumnChart').setOptions({
  title: 'State Population (US census, 2010)',
  legend: {position: 'none'},
  hAxis: {title: 'State', titleTextStyle: {italic: false, bold: true}},
  vAxis: {title: 'Population', titleTextStyle: {italic: false, bold: true}},
  colors: ['1d6b99']
});
print(chart);
// [END earthengine__charts_datatable__manual_datatable]

// [START earthengine__charts_datatable__computed_datatable_by_date]
// Import the example feature collection and subset the forest feature.
var forest = ee.FeatureCollection('projects/google/charts_feature_example')
                 .filter(ee.Filter.eq('label', 'Forest'));

// Load MODIS vegetation indices data and subset a decade of images.
var vegIndices = ee.ImageCollection('MODIS/006/MOD13A1')
                     .filter(ee.Filter.date('2010-01-01', '2020-01-01'))
                     .select(['NDVI', 'EVI']);

// Define a function to format an image timestamp as a JavaScript Date string.
function formatDate(img) {
  var millis = img.date().millis().format();
  return ee.String('Date(').cat(millis).cat(')');
}

// Build a feature collection where each feature has a property that represents
// a DataFrame row.
var reductionTable = vegIndices.map(function(img) {
  // Reduce the image to the mean of pixels intersecting the forest ecoregion.
  var stat = img.reduceRegion(
      {reducer: ee.Reducer.mean(), geometry: forest, scale: 500});

  // Extract the reduction results along with the image date.
  var date = formatDate(img);   // x-axis values.
  var evi = stat.get('EVI');    // y-axis series 1 values.
  var ndvi = stat.get('NDVI');  // y-axis series 2 values.

  // Make a list of observation attributes to define a row in the DataTable.
  var row = ee.List([date, evi, ndvi]);

  // Return the row as a property of an ee.Feature.
  return ee.Feature(null, {'row': row});
});

// Aggregate the 'row' property from all features in the new feature collection
// to make a server-side 2-D list (DataTable).
var dataTableServer = reductionTable.aggregate_array('row');

// Define column names and properties for the DataTable. The order should
// correspond to the order in the construction of the 'row' property above.
var columnHeader = ee.List([[
  {label: 'Date', role: 'domain', type: 'date'},
  {label: 'EVI', role: 'data', type: 'number'},
  {label: 'NDVI', role: 'data', type: 'number'}
]]);

// Concatenate the column header to the table.
dataTableServer = columnHeader.cat(dataTableServer);

// Use 'evaluate' to transfer the server-side table to the client, define the
// chart and print it to the console.
dataTableServer.evaluate(function(dataTableClient) {
  var chart = ui.Chart(dataTableClient).setOptions({
    title: 'Average Vegetation Index Value by Date for Forest',
    hAxis: {
      title: 'Date',
      titleTextStyle: {italic: false, bold: true},
    },
    vAxis: {
      title: 'Vegetation index (x1e4)',
      titleTextStyle: {italic: false, bold: true}
    },
    lineWidth: 5,
    colors: ['e37d05', '1d6b99'],
    curveType: 'function'
  });
  print(chart);
});
// [END earthengine__charts_datatable__computed_datatable_by_date]

// [START earthengine__charts_datatable__computed_datatable_by_doy_area]
// Define a point to extract an NDVI time series for.
var geometry = ee.Geometry.Point([-121.679, 36.479]);

// Define a band of interest (NDVI), import the MODIS vegetation index dataset,
// and select the band.
var band = 'NDVI';
var ndviCol = ee.ImageCollection('MODIS/006/MOD13Q1').select(band);

// Map over the collection to add a day of year (doy) property to each image.
ndviCol = ndviCol.map(function(img) {
  var doy = ee.Date(img.get('system:time_start')).getRelative('day', 'year');
  // Add 8 to day of year number so that the doy label represents the middle of
  // the 16-day MODIS NDVI composite.
  return img.set('doy', ee.Number(doy).add(8));
});

// Join all coincident day of year observations into a set of image collections.
var distinctDOY = ndviCol.filterDate('2013-01-01', '2014-01-01');
var filter = ee.Filter.equals({leftField: 'doy', rightField: 'doy'});
var join = ee.Join.saveAll('doy_matches');
var joinCol = ee.ImageCollection(join.apply(distinctDOY, ndviCol, filter));

// Calculate the absolute range, interquartile range, and median for the set
// of images composing each coincident doy observation group. The result is
// an image collection with an image representative per unique doy observation
// with bands that describe the 0, 25, 50, 75, 100 percentiles for the set of
// coincident doy images.
var comp = ee.ImageCollection(joinCol.map(function(img) {
  var doyCol = ee.ImageCollection.fromImages(img.get('doy_matches'));

  return doyCol
      .reduce(ee.Reducer.percentile(
          [0, 25, 50, 75, 100], ['p0', 'p25', 'p50', 'p75', 'p100']))
      .set({'doy': img.get('doy')});
}));

// Extract the inter-annual NDVI doy percentile statistics for the
// point of interest per unique doy representative. The result is
// is a feature collection where each feature is a doy representative that
// contains a property (row) describing the respective inter-annual NDVI
// variance, formatted as a list of values.
var reductionTable = comp.map(function(img) {
  var stats = ee.Dictionary(img.reduceRegion(
      {reducer: ee.Reducer.first(), geometry: geometry, scale: 250}));

  // Order the percentile reduction elements according to how you want columns
  // in the DataTable arranged (x-axis values need to be first).
  var row = ee.List([
    img.get('doy'),            // x-axis, day of year.
    stats.get(band + '_p50'),  // y-axis, median.
    stats.get(band + '_p0'),   // y-axis, min interval.
    stats.get(band + '_p25'),  // y-axis, 1st quartile interval.
    stats.get(band + '_p75'),  // y-axis, 3rd quartile interval.
    stats.get(band + '_p100')  // y-axis, max interval.
  ]);

  // Return the row as a property of an ee.Feature.
  return ee.Feature(null, {row: row});
});

// Aggregate the 'row' properties to make a server-side 2-D array (DataTable).
var dataTableServer = reductionTable.aggregate_array('row');

// Define column names and properties for the DataTable. The order should
// correspond to the order in the construction of the 'row' property above.
var columnHeader = ee.List([[
  {label: 'Day of year', role: 'domain'},
  {label: 'Median', role: 'data'},
  {label: 'p0', role: 'interval'},
  {label: 'p25', role: 'interval'},
  {label: 'p75', role: 'interval'},
  {label: 'p100', role: 'interval'}
]]);

// Concatenate the column header to the table.
dataTableServer = columnHeader.cat(dataTableServer);

// Use 'evaluate' to transfer the server-side table to the client, define the
// chart and print it to the console.
dataTableServer.evaluate(function(dataTableClient) {
  var chart = ui.Chart(dataTableClient).setChartType('LineChart').setOptions({
    title: 'Annual NDVI Time Series with Inter-Annual Variance',
    intervals: {style: 'area'},
    hAxis: {
      title: 'Day of year',
      titleTextStyle: {italic: false, bold: true},
    },
    vAxis: {title: 'NDVI (x1e4)', titleTextStyle: {italic: false, bold: true}},
    colors: ['0f8755'],
    legend: {position: 'none'}
  });
  print(chart);
});
// [END earthengine__charts_datatable__computed_datatable_by_doy_area]

// [START earthengine__charts_datatable__computed_datatable_by_doy_bar]
dataTableServer.evaluate(function(dataTableClient) {
  var chart = ui.Chart(dataTableClient).setChartType('LineChart').setOptions({
    title: 'Annual NDVI Time Series with Inter-Annual Variance',
    intervals: {style: 'boxes', barWidth: 1, boxWidth: 1, lineWidth: 0},
    hAxis: {
      title: 'Day of year',
      titleTextStyle: {italic: false, bold: true},
    },
    vAxis: {title: 'NDVI (x1e4)', titleTextStyle: {italic: false, bold: true}},
    colors: ['0f8755'],
    legend: {position: 'none'}
  });
  print(chart);
});
// [END earthengine__charts_datatable__computed_datatable_by_doy_bar]
<|endoftext|>


<commit_before>
var checkLottery = function(lotteryNumber){
	var correctAnwser = 1234;
	return lotteryNumber == correctAnwser;
}

<commit_msg>Fixed missing ;<commit_after>
var checkLottery = function(lotteryNumber){
	var correctAnwser = 1234;
	return lotteryNumber == correctAnwser;
};

<|endoftext|>


<commit_before>;(function () {
  const supportsLocalStorage = (() => {
    try {
      localStorage.setItem('test', 'test');
      localStorage.removeItem('test');
      return true;
    } catch (e) {
      return false;
    }
  })();

  const settingKey = "use-dark-theme";

  function toggleDarkTheme(isDark) {
    currentlyDark = isDark
    // this triggers the `:root.theme-dark` rule from scalastyle.css,
    // which changes the values of a bunch of CSS color variables
    document.documentElement.classList.toggle("theme-dark", isDark);
    supportsLocalStorage && localStorage.setItem(settingKey, isDark);
  }

  /* Infer a dark/light theme preference from the user's system */
  const colorSchemePrefMql = window.matchMedia("(prefers-color-scheme: dark)");

  /* This needs to happen ASAP so we don't get a FOUC of bright colors before the dark theme is applied */
  const initiallyDark = (() => {
    const storedSetting = supportsLocalStorage && localStorage.getItem(settingKey);
    return (storedSetting === null) ? colorSchemePrefMql.matches : storedSetting === "true";
  })();
  let currentlyDark = initiallyDark;
  toggleDarkTheme(initiallyDark);

  /* Wait for the DOM to be loaded before we try to attach event listeners to things in the DOM */
  window.addEventListener("DOMContentLoaded", () => {
    const themeToggler = document.querySelector('#theme-toggle input');
    themeToggler.checked = !currentlyDark;
    themeToggler.addEventListener("change", e => {
      toggleDarkTheme(!e.target.checked);
    });

    /* Auto-swap the dark/light theme if the user changes it in their system */
    colorSchemePrefMql.addEventListener('change', e => {
      const preferDark = e.matches
      themeToggler.checked = !preferDark
      toggleDarkTheme(preferDark)
    })
  });
})();
<commit_msg>add some 'missing' semicolons to some JS<commit_after>;(function () {
  const supportsLocalStorage = (() => {
    try {
      localStorage.setItem('test', 'test');
      localStorage.removeItem('test');
      return true;
    } catch (e) {
      return false;
    }
  })();

  const settingKey = "use-dark-theme";

  function toggleDarkTheme(isDark) {
    currentlyDark = isDark
    // this triggers the `:root.theme-dark` rule from scalastyle.css,
    // which changes the values of a bunch of CSS color variables
    document.documentElement.classList.toggle("theme-dark", isDark);
    supportsLocalStorage && localStorage.setItem(settingKey, isDark);
  }

  /* Infer a dark/light theme preference from the user's system */
  const colorSchemePrefMql = window.matchMedia("(prefers-color-scheme: dark)");

  /* This needs to happen ASAP so we don't get a FOUC of bright colors before the dark theme is applied */
  const initiallyDark = (() => {
    const storedSetting = supportsLocalStorage && localStorage.getItem(settingKey);
    return (storedSetting === null) ? colorSchemePrefMql.matches : storedSetting === "true";
  })();
  let currentlyDark = initiallyDark;
  toggleDarkTheme(initiallyDark);

  /* Wait for the DOM to be loaded before we try to attach event listeners to things in the DOM */
  window.addEventListener("DOMContentLoaded", () => {
    const themeToggler = document.querySelector('#theme-toggle input');
    themeToggler.checked = !currentlyDark;
    themeToggler.addEventListener("change", e => {
      toggleDarkTheme(!e.target.checked);
    });

    /* Auto-swap the dark/light theme if the user changes it in their system */
    colorSchemePrefMql.addEventListener('change', e => {
      const preferDark = e.matches;
      themeToggler.checked = !preferDark;
      toggleDarkTheme(preferDark);
    });
  });
})();
<|endoftext|>


<commit_before>
angular.module('os.common.import.list', ['os.common.import.importjob'])
  .controller('MobileUploadJobsListCtrl', function($scope, cp, MobileUploadJob) {

    var ctx;

    function init() {
      ctx = $scope.ctx = {
        jobs: [],
        pagingOpts: {
          totalJobs: 0,
          currPage: 1,
          jobsPerPage: 25
        }
      };

      $scope.$watch('ctx.pagingOpts.currPage', function() { loadJobs(ctx.pagingOpts); });
    };

    function loadJobs(pagingOpts) {
      var startAt = (pagingOpts.currPage - 1) * pagingOpts.jobsPerPage;
      var maxResults = pagingOpts.jobsPerPage + 1;

      var queryParams = {cpId: cp.id, startAt: startAt, maxResults: maxResults};
      MobileUploadJob.query(queryParams).then(
        function(jobs) {
          pagingOpts.totalJobs = (pagingOpts.currPage - 1) * pagingOpts.jobsPerPage + jobs.length;

          if (jobs.length >= maxResults) {
            jobs.splice(jobs.length - 1, 1);
          }

          ctx.jobs = jobs;
          angular.forEach(jobs,
            function(job) {
              job.outputFileUrl = MobileUploadJob.url() + job.$id() + '/report';
            }
          );
        }
      );
    };

    init();
  });
<commit_msg>Fixed the module name used for mobile upload jobs. There was a conflict in the module names used for bulk import and mobile upload jobs resulting in breaking of import jobs list view.<commit_after>
angular.module('os.biospecimen.mobile')
  .controller('MobileUploadJobsListCtrl', function($scope, cp, MobileUploadJob) {

    var ctx;

    function init() {
      ctx = $scope.ctx = {
        jobs: [],
        pagingOpts: {
          totalJobs: 0,
          currPage: 1,
          jobsPerPage: 25
        }
      };

      $scope.$watch('ctx.pagingOpts.currPage', function() { loadJobs(ctx.pagingOpts); });
    };

    function loadJobs(pagingOpts) {
      var startAt = (pagingOpts.currPage - 1) * pagingOpts.jobsPerPage;
      var maxResults = pagingOpts.jobsPerPage + 1;

      var queryParams = {cpId: cp.id, startAt: startAt, maxResults: maxResults};
      MobileUploadJob.query(queryParams).then(
        function(jobs) {
          pagingOpts.totalJobs = (pagingOpts.currPage - 1) * pagingOpts.jobsPerPage + jobs.length;

          if (jobs.length >= maxResults) {
            jobs.splice(jobs.length - 1, 1);
          }

          ctx.jobs = jobs;
          angular.forEach(jobs,
            function(job) {
              job.outputFileUrl = MobileUploadJob.url() + job.$id() + '/report';
            }
          );
        }
      );
    };

    init();
  });
<|endoftext|>


<commit_before>NGApp.config(['$routeProvider', function($routeProvider) {
	$routeProvider
		.when('/orders', {
			action: 'orders',
			controller: 'OrdersCtrl',
			templateUrl: 'assets/view/orders.html',
			reloadOnSearch: false

		}).when('/order/:id', {
			action: 'order',
			controller: 'OrderCtrl',
			templateUrl: 'assets/view/orders-order.html'
		});
}]);

NGApp.controller('OrdersCtrl', function ($scope, $location, OrderService, ViewListService, SocketService, MapService, TicketService, RestaurantService, CommunityService) {
	angular.extend($scope, ViewListService);

//	var query = $location.search();
//	$scope.query.view = 'list';

	SocketService.listen('orders', $scope)
		.on('update', function(d) {
			for (var x in $scope.orders) {
				if ($scope.orders[x].id_order == d.id_order) {
					$scope.orders[x] = d;
				}
			}

		}).on('create', function(d) {
			$scope.update();
		});

	var draw = function() {
		if (!$scope.map || !$scope.orders) {
			return;
		}

		MapService.trackOrders({
			map: $scope.map,
			orders: $scope.orders,
			id: 'orders-location',
			scope: $scope
		});
	};

	$scope.ticket = function(id_order) {
		OrderService.ticket(id_order, function(json) {
			if (json.id_support) {
				ticket(json.id_support);
			} else {
				App.alert('Fail retrieving support ticket!' );
			}
		});
	}

	var ticket = function( id_support ){
		var url = '/ticket/' + id_support;
		$scope.navigation.link( url );
	}

	$scope.$on('mapInitialized', function(event, map) {
		console.log('INIT');
		$scope.map = map;
		MapService.style(map);
		draw();
	});

	$scope.view({
		scope: $scope,
		watch: {
			search: '',
			restaurant: '',
			community: '',
			date: '',
			view: 'list',
			datestart: '',
			dateend: '',
			user: '',
			phone: '',
			fullcount: false
		},
		update: function() {
			OrderService.list($scope.query, function(d) {
				$scope.orders = d.results;
				$scope.complete(d);
				draw();
			});
		}
	});

	$scope.show_more_options = false;

	$scope.exports = function(){
		var params = {};
		angular.copy( $scope.query, params );
		console.log('params',params);
		OrderService.exports( params, function(){
		} );
	}

	$scope.moreOptions = function(){
		$scope.show_more_options = !$scope.show_more_options;

		if( $scope.show_more_options) {

			if( !$scope.restaurants ){
				$scope.restaurants = [];
				RestaurantService.shortlist( function( json ){
					$scope.restaurants = json;
				} );
			}

			if( !$scope.communities ){
				CommunityService.listSimple( function( json ){
					$scope.communities = json;
				} );
			}
		}
	}

	var options = [];
	options.push( { value: '20', label: '20' } );
	options.push( { value: '50', label: '50' } );
	options.push( { value: '100', label: '100' } );
	options.push( { value: '200', label: '200' } );
	$scope.limits = options;

});

NGApp.controller('OrderCtrl', function ($scope, $rootScope, $routeParams, $interval, OrderService, MapService, SocketService) {

	SocketService.listen('order.' + $routeParams.id, $scope)
		.on('update', function(d) {
			$scope.order = d;
		});

	$scope.loading = true;

	var draw = function() {
		if (!$scope.map || !$scope.order) {
			return;
		}

		MapService.trackOrder({
			map: $scope.map,
			order: $scope.order,
			restaurant: $scope.order.restaurant,
			driver: $scope.order.driver,
			id: 'order-driver-location',
			scope: $scope
		});
	};

	var update = function() {
		var loading = true;
		OrderService.get($routeParams.id, function(d) {
			$rootScope.title = 'Order #' + d.id_order;
			$scope.order = d;
			$scope.loading = false;
			draw();
		});
	};

	$rootScope.$on( 'orderDeliveryStatusChanged', function(e, data) {
		update();
	});

	$scope.$on('mapInitialized', function(event, map) {
		$scope.map = map;
		MapService.style(map);
		draw();
	});

	var cleanup = $rootScope.$on('order-route-' + $routeParams.id, function(event, args) {
		$scope.$apply(function() {
			$scope.eta = args;
		});
		console.debug('Got route update: ', args);
	});

	$scope.updater = $interval(update, 30000); // update every 30 seconds
	$scope.$on('$destroy', function() {
		$interval.cancel($scope.updater);
		cleanup();
	});

	$scope.isRefunding = false;

	$scope.changeOrderStatus = function(){
		$rootScope.$broadcast( 'orderDeliveryStatusChange', { id_order: $routeParams.id, id_community: $scope.order.id_community }  );
	}

	$scope.refund = function(){

		if( $scope.isRefunding ){
			return;
		}

		var question = 'Are you sure you want to refund this order?';
		if( parseFloat( $scope.order.credit ) > 0 ){
			question += "\n";
			question += 'A gift card was used at this order the refund value will be $' + $scope.order.charged + ' + $' + $scope.order.credit + ' as gift card.' ;
		}

		if ( confirm( question ) ){

			$scope.isRefunding = true;
			OrderService.refund( $scope.order.id_order, function( result ){
				$scope.isRefunding = false;
				if( result.success ){
					$rootScope.reload();
				} else {
					console.log( result.responseText );
					var er = result.errors ? "
" + result.errors : 'See the console.log!';
					App.alert('Refunding fail! ' + er);
				}
			} );
		}
	}

	$scope.do_not_pay_driver = function(){
		OrderService.do_not_pay_driver( $scope.order.id_order, function( result ){
			if( result.success ){
				$scope.flash.setMessage( 'Saved!' );
				$scope.order.do_not_pay_driver = ( $scope.order.do_not_pay_driver ? 0 : 1 );
			} else {
				$scope.flash.setMessage( 'Error!' );
			}
		} );
	}

	$scope.do_not_pay_restaurant = function(){
		OrderService.do_not_pay_restaurant( $scope.order.id_order, function( result ){
			if( result.success ){
				$scope.flash.setMessage( 'Saved!' );
				$scope.order.do_not_pay_restaurant = ( $scope.order.do_not_pay_restaurant ? 0 : 1 );
			} else {
				$scope.flash.setMessage( 'Error!' );
			}
		} );
	}

	$scope.do_not_reimburse_driver = function(){
		OrderService.do_not_reimburse_driver( $scope.order.id_order, function( result ){
			if( result.success ){
				$scope.flash.setMessage( 'Saved!' );
				$scope.order.do_not_reimburse_driver = ( $scope.order.do_not_reimburse_driver ? 0 : 1 );
			} else {
				$scope.flash.setMessage( 'Error!' );
			}
		} );
	}

	$scope.resend_notification_drivers = function(){
		$scope.isDriverNotifying = true;
		OrderService.resend_notification_drivers( $scope.order, function(result) {
			$scope.isDriverNotifying = false;
		});
	}

	$scope.resend_notification = function(){
		$scope.isRestaurantNotifying = true;
		OrderService.resend_notification( $scope.order, function(result) {
			$scope.isRestaurantNotifying = false;
		});
	}

	update();
});

NGApp.controller('OrderDeliveryStatusCtrl', function ( $scope, $rootScope, OrderService, DriverService ) {

	var id_order = null;
	var id_community = null;
	var id_driver = null;

	$rootScope.$on( 'orderDeliveryStatusChange', function(e, data) {
		$scope.status = null;
		$scope.notify_customer = false;
		id_order = data.id_order;
		id_community = data.id_community;
		App.dialog.show('.change-status-dialog-container');
		load();
	} );

	$scope.driverChanged = function(){
		$scope.notify_customer = ( id_driver != $scope.status.driver.id_admin );
	}

	var load = function(){

		$scope.text5MinAwaySending = false;

		OrderService.delivery_status( id_order, function( data ){
			$scope.status = data;
			if( data && data.driver && data.driver.id_admin ){
				id_driver = data.driver.id_admin;
			}
		} );
		DriverService.byCommunity( id_community, function( data ){
			$scope.drivers = data;
		} );
	}

	$scope.statuses = OrderService.statuses;

	$scope.text5MinAway = function(){

		if( $scope.text5MinAwaySending ){
			return;
		}

		if( confirm( 'Confirm send message to customer?' ) ){
			$scope.text5MinAwaySending = true;
			OrderService.text_5_min_away( id_order, function( json ){
				if( json.success ){
					$rootScope.$broadcast( 'orderDeliveryStatusChanged', json );
				} else {
					App.alert( 'Error saving: ' + json.error );
				}
				$scope.text5MinAwaySending = false;
			} );
		}
	}

	$scope.formDeliveryStatusSave = function(){

		if( $scope.formDeliveryStatus.$invalid ){
			$scope.formDeliveryStatusSubmitted = true;
			return;
		}

		$scope.isSaving = true;

		var params = { 	id_order: id_order,
										notify_customer: $scope.notify_customer,
										status: $scope.status.status,
										id_admin: $scope.status.driver.id_admin };

		OrderService.change_delivery_status( params, function( json ){
			$scope.isSaving = false;
			if( json.error ){
				App.alert( 'Error saving: ' + json.error );
			} else {
				$rootScope.closePopup();
				$rootScope.$broadcast( 'orderDeliveryStatusChanged', json );
			}
		} );
	}

} );
<commit_msg>cockpit.la: Ability to re-assign an order and change status #5801<commit_after>NGApp.config(['$routeProvider', function($routeProvider) {
	$routeProvider
		.when('/orders', {
			action: 'orders',
			controller: 'OrdersCtrl',
			templateUrl: 'assets/view/orders.html',
			reloadOnSearch: false

		}).when('/order/:id', {
			action: 'order',
			controller: 'OrderCtrl',
			templateUrl: 'assets/view/orders-order.html'
		});
}]);

NGApp.controller('OrdersCtrl', function ($scope, $location, OrderService, ViewListService, SocketService, MapService, TicketService, RestaurantService, CommunityService) {
	angular.extend($scope, ViewListService);

//	var query = $location.search();
//	$scope.query.view = 'list';

	SocketService.listen('orders', $scope)
		.on('update', function(d) {
			for (var x in $scope.orders) {
				if ($scope.orders[x].id_order == d.id_order) {
					$scope.orders[x] = d;
				}
			}

		}).on('create', function(d) {
			$scope.update();
		});

	var draw = function() {
		if (!$scope.map || !$scope.orders) {
			return;
		}

		MapService.trackOrders({
			map: $scope.map,
			orders: $scope.orders,
			id: 'orders-location',
			scope: $scope
		});
	};

	$scope.ticket = function(id_order) {
		OrderService.ticket(id_order, function(json) {
			if (json.id_support) {
				ticket(json.id_support);
			} else {
				App.alert('Fail retrieving support ticket!' );
			}
		});
	}

	var ticket = function( id_support ){
		var url = '/ticket/' + id_support;
		$scope.navigation.link( url );
	}

	$scope.$on('mapInitialized', function(event, map) {
		console.log('INIT');
		$scope.map = map;
		MapService.style(map);
		draw();
	});

	$scope.view({
		scope: $scope,
		watch: {
			search: '',
			restaurant: '',
			community: '',
			date: '',
			view: 'list',
			datestart: '',
			dateend: '',
			user: '',
			phone: '',
			fullcount: false
		},
		update: function() {
			OrderService.list($scope.query, function(d) {
				$scope.orders = d.results;
				$scope.complete(d);
				draw();
			});
		}
	});

	$scope.show_more_options = false;

	$scope.exports = function(){
		var params = {};
		angular.copy( $scope.query, params );
		console.log('params',params);
		OrderService.exports( params, function(){
		} );
	}

	$scope.moreOptions = function(){
		$scope.show_more_options = !$scope.show_more_options;

		if( $scope.show_more_options) {

			if( !$scope.restaurants ){
				$scope.restaurants = [];
				RestaurantService.shortlist( function( json ){
					$scope.restaurants = json;
				} );
			}

			if( !$scope.communities ){
				CommunityService.listSimple( function( json ){
					$scope.communities = json;
				} );
			}
		}
	}

	var options = [];
	options.push( { value: '20', label: '20' } );
	options.push( { value: '50', label: '50' } );
	options.push( { value: '100', label: '100' } );
	options.push( { value: '200', label: '200' } );
	$scope.limits = options;

});

NGApp.controller('OrderCtrl', function ($scope, $rootScope, $routeParams, $interval, OrderService, MapService, SocketService) {

	SocketService.listen('order.' + $routeParams.id, $scope)
		.on('update', function(d) {
			$scope.order = d;
		});

	$scope.loading = true;

	var draw = function() {
		if (!$scope.map || !$scope.order) {
			return;
		}

		MapService.trackOrder({
			map: $scope.map,
			order: $scope.order,
			restaurant: $scope.order.restaurant,
			driver: $scope.order.driver,
			id: 'order-driver-location',
			scope: $scope
		});
	};

	var update = function() {
		var loading = true;
		OrderService.get($routeParams.id, function(d) {
			$rootScope.title = 'Order #' + d.id_order;
			$scope.order = d;
			$scope.loading = false;
			draw();
		});
	};

	$rootScope.$on( 'orderDeliveryStatusChanged', function(e, data) {
		update();
	});

	$scope.$on('mapInitialized', function(event, map) {
		$scope.map = map;
		MapService.style(map);
		draw();
	});

	var cleanup = $rootScope.$on('order-route-' + $routeParams.id, function(event, args) {
		$scope.$apply(function() {
			$scope.eta = args;
		});
		console.debug('Got route update: ', args);
	});

	$scope.updater = $interval(update, 30000); // update every 30 seconds
	$scope.$on('$destroy', function() {
		$interval.cancel($scope.updater);
		cleanup();
	});

	$scope.isRefunding = false;

	$scope.changeOrderStatus = function(){
		$rootScope.$broadcast( 'orderDeliveryStatusChange', { id_order: $routeParams.id, id_community: $scope.order.id_community }  );
	}

	$scope.refund = function(){

		if( $scope.isRefunding ){
			return;
		}

		var question = 'Are you sure you want to refund this order?';
		if( parseFloat( $scope.order.credit ) > 0 ){
			question += "\n";
			question += 'A gift card was used at this order the refund value will be $' + $scope.order.charged + ' + $' + $scope.order.credit + ' as gift card.' ;
		}

		if ( confirm( question ) ){

			$scope.isRefunding = true;
			OrderService.refund( $scope.order.id_order, function( result ){
				$scope.isRefunding = false;
				if( result.success ){
					$rootScope.reload();
				} else {
					console.log( result.responseText );
					var er = result.errors ? "
" + result.errors : 'See the console.log!';
					App.alert('Refunding fail! ' + er);
				}
			} );
		}
	}

	$scope.do_not_pay_driver = function(){
		OrderService.do_not_pay_driver( $scope.order.id_order, function( result ){
			if( result.success ){
				$scope.flash.setMessage( 'Saved!' );
				$scope.order.do_not_pay_driver = ( $scope.order.do_not_pay_driver ? 0 : 1 );
			} else {
				$scope.flash.setMessage( 'Error!' );
			}
		} );
	}

	$scope.do_not_pay_restaurant = function(){
		OrderService.do_not_pay_restaurant( $scope.order.id_order, function( result ){
			if( result.success ){
				$scope.flash.setMessage( 'Saved!' );
				$scope.order.do_not_pay_restaurant = ( $scope.order.do_not_pay_restaurant ? 0 : 1 );
			} else {
				$scope.flash.setMessage( 'Error!' );
			}
		} );
	}

	$scope.do_not_reimburse_driver = function(){
		OrderService.do_not_reimburse_driver( $scope.order.id_order, function( result ){
			if( result.success ){
				$scope.flash.setMessage( 'Saved!' );
				$scope.order.do_not_reimburse_driver = ( $scope.order.do_not_reimburse_driver ? 0 : 1 );
			} else {
				$scope.flash.setMessage( 'Error!' );
			}
		} );
	}

	$scope.resend_notification_drivers = function(){
		$scope.isDriverNotifying = true;
		OrderService.resend_notification_drivers( $scope.order, function(result) {
			$scope.isDriverNotifying = false;
		});
	}

	$scope.resend_notification = function(){
		$scope.isRestaurantNotifying = true;
		OrderService.resend_notification( $scope.order, function(result) {
			$scope.isRestaurantNotifying = false;
		});
	}

	update();
});

NGApp.controller('OrderDeliveryStatusCtrl', function ( $scope, $rootScope, OrderService, DriverService ) {

	var id_order = null;
	var id_community = null;
	var id_driver = null;

	$rootScope.$on( 'orderDeliveryStatusChange', function(e, data) {
		$scope.status = null;
		$scope.notify_customer = false;
		id_order = data.id_order;
		id_community = data.id_community;
		App.dialog.show('.change-status-dialog-container');
		load();
	} );

	$scope.driverChanged = function(){
		processOptions();
	}

	var processOptions = function(){
		$scope.notify_customer = ( id_driver != $scope.status.driver.id_admin );
		$scope.statuses = [];
		angular.forEach( OrderService.statuses, function( value, key ) {
			var add = true;
			if( ( value.value == 'rejected' && id_driver != $scope.status.driver.id_admin ) ){
				add = false;
			}
			if( add ){
				$scope.statuses.push( value );
			}
		} );
	}

	var load = function(){

		$scope.text5MinAwaySending = false;

		OrderService.delivery_status( id_order, function( data ){
			$scope.status = data;
			if( data && data.driver && data.driver.id_admin ){
				id_driver = data.driver.id_admin;
			}
			processOptions();
		} );
		DriverService.byCommunity( id_community, function( data ){
			$scope.drivers = data;
		} );
	}

	$scope.text5MinAway = function(){

		if( $scope.text5MinAwaySending ){
			return;
		}

		if( confirm( 'Confirm send message to customer?' ) ){
			$scope.text5MinAwaySending = true;
			OrderService.text_5_min_away( id_order, function( json ){
				if( json.success ){
					$rootScope.$broadcast( 'orderDeliveryStatusChanged', json );
				} else {
					App.alert( 'Error saving: ' + json.error );
				}
				$scope.text5MinAwaySending = false;
			} );
		}
	}

	$scope.formDeliveryStatusSave = function(){

		if( $scope.formDeliveryStatus.$invalid ){
			$scope.formDeliveryStatusSubmitted = true;
			return;
		}

		$scope.isSaving = true;

		var params = { 	id_order: id_order,
										notify_customer: $scope.notify_customer,
										status: $scope.status.status,
										id_admin: $scope.status.driver.id_admin };

		OrderService.change_delivery_status( params, function( json ){
			$scope.isSaving = false;
			if( json.error ){
				App.alert( 'Error saving: ' + json.error );
			} else {
				$rootScope.closePopup();
				$rootScope.$broadcast( 'orderDeliveryStatusChanged', json );
			}
		} );
	}

} );
<|endoftext|>


<commit_before>$(document).ready(function() {
    var $quiz = $('#quiz');

    $quiz.find('li strong').click(function(){
        var $q = $(this).parents('.question');
        var $b = $q.find('strong');
        var got_it_right = $(this).parent('li').hasClass('correct');
        var answer_text = $(this).next('.answer');
        var right_answer = $q.find('.correct');
        $q.addClass('answered');
        if (got_it_right) {
            $(this).prepend('RIGHT! ');
        } else {
            $(this).prepend('WRONG! ');
        }
        $b.each(function(v,k) {
            $(this).unbind('click');
        });
    });

    setupResponsiveChild();
});<commit_msg>reset iframe height every time a question is answered<commit_after>$(document).ready(function() {
    var $quiz = $('#quiz');

    $quiz.find('li strong').click(function(){
        var $q = $(this).parents('.question');
        var $b = $q.find('strong');
        var got_it_right = $(this).parent('li').hasClass('correct');
        var answer_text = $(this).next('.answer');
        var right_answer = $q.find('.correct');

        $q.addClass('answered');

        if (got_it_right) {
            $(this).prepend('RIGHT! ');
        } else {
            $(this).prepend('WRONG! ');
        }

        $b.each(function(v,k) {
            $(this).unbind('click');
        });

        sendHeightToParent();
    });

    setupResponsiveChild();
});<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(scope) {
  var dispatcher = scope.dispatcher;
  var pointermap = dispatcher.pointermap;
  var HAS_BITMAP_TYPE = typeof MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  var msEvents = {
    events: [
      'MSPointerDown',
      'MSPointerMove',
      'MSPointerUp',
      'MSPointerOut',
      'MSPointerOver',
      'MSPointerCancel',
      'MSGotPointerCapture',
      'MSLostPointerCapture'
    ],
    register: function(target) {
      dispatcher.listen(target, this.events);
    },
    unregister: function(target) {
      dispatcher.unlisten(target, this.events);
    },
    POINTER_TYPES: [
      '',
      'unavailable',
      'touch',
      'pen',
      'mouse'
    ],
    prepareEvent: function(inEvent) {
      var e = inEvent;
      if (HAS_BITMAP_TYPE) {
        e = dispatcher.cloneEvent(inEvent);
        e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
      }
      return e;
    },
    cleanup: function(id) {
      pointermap.delete(id);
    },
    MSPointerDown: function(inEvent) {
      pointermap.set(inEvent.pointerId, inEvent);
      var e = this.prepareEvent(inEvent);
      dispatcher.down(e);
    },
    MSPointerMove: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.move(e);
    },
    MSPointerUp: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.up(e);
      this.cleanup(inEvent.pointerId);
    },
    MSPointerOut: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.leaveOut(e);
    },
    MSPointerOver: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.enterOver(e);
    },
    MSPointerCancel: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.cancel(e);
      this.cleanup(inEvent.pointerId);
    },
    MSLostPointerCapture: function(inEvent) {
      var e = dispatcher.makeEvent('lostpointercapture', inEvent);
      dispatcher.dispatchEvent(e);
    },
    MSGotPointerCapture: function(inEvent) {
      var e = dispatcher.makeEvent('gotpointercapture', inEvent);
      dispatcher.dispatchEvent(e);
    }
  };

  scope.msEvents = msEvents;
})(window.PointerEventsPolyfill);
<commit_msg>Fix simple reference error in !IE<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(scope) {
  var dispatcher = scope.dispatcher;
  var pointermap = dispatcher.pointermap;
  var HAS_BITMAP_TYPE = window.MSPointerEvent && typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  var msEvents = {
    events: [
      'MSPointerDown',
      'MSPointerMove',
      'MSPointerUp',
      'MSPointerOut',
      'MSPointerOver',
      'MSPointerCancel',
      'MSGotPointerCapture',
      'MSLostPointerCapture'
    ],
    register: function(target) {
      dispatcher.listen(target, this.events);
    },
    unregister: function(target) {
      dispatcher.unlisten(target, this.events);
    },
    POINTER_TYPES: [
      '',
      'unavailable',
      'touch',
      'pen',
      'mouse'
    ],
    prepareEvent: function(inEvent) {
      var e = inEvent;
      if (HAS_BITMAP_TYPE) {
        e = dispatcher.cloneEvent(inEvent);
        e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
      }
      return e;
    },
    cleanup: function(id) {
      pointermap.delete(id);
    },
    MSPointerDown: function(inEvent) {
      pointermap.set(inEvent.pointerId, inEvent);
      var e = this.prepareEvent(inEvent);
      dispatcher.down(e);
    },
    MSPointerMove: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.move(e);
    },
    MSPointerUp: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.up(e);
      this.cleanup(inEvent.pointerId);
    },
    MSPointerOut: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.leaveOut(e);
    },
    MSPointerOver: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.enterOver(e);
    },
    MSPointerCancel: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.cancel(e);
      this.cleanup(inEvent.pointerId);
    },
    MSLostPointerCapture: function(inEvent) {
      var e = dispatcher.makeEvent('lostpointercapture', inEvent);
      dispatcher.dispatchEvent(e);
    },
    MSGotPointerCapture: function(inEvent) {
      var e = dispatcher.makeEvent('gotpointercapture', inEvent);
      dispatcher.dispatchEvent(e);
    }
  };

  scope.msEvents = msEvents;
})(window.PointerEventsPolyfill);
<|endoftext|>