<commit_before>/*
 * Copyright (c) 2015 Mansi Shah, Santosh Rajan
*/

var ast = {
        type: "Program",
        body: []
    }

module.exports = function(src) {

    var spaceRegEx = /^[ \t\r\n\b\f]+/,
        newLineRegEx = /\r?\n/,
        nullRegEx = /^null\b/i,
        booleanRegEx = /^(true|false)\b/i,
        numberRegEx = /^[-+]?(\d+(\.\d*)?|\.\d+)([e][+-]?\d+)?/i,
        stringRegEx = /^('|").*?[^\\]\1/,
        identifierRegEx = /^[a-z\~]+[a-z0-9_\[\]\.\*]*/i,
        openParanthesesRegEx = /^\(/,
        closingParanthesesRegEx = /^\)/,
        operatorRegEx = /^(\*|\+|\-|\/|\%)/,
        functionKeywordRegEx = /^(\()(\s)*function/,
        macroKeywordRegEx = /^(\()(\s)*macro\b/,
        varKeywordRegEx = /^(\()?(\s)*var/,
        fatArrowRegEx = /^\=\>/,
        line = 1
        macros = {}

    function spaceParser() {
        var matches = spaceRegEx.exec(src)
        if (!matches) return null
        var match = matches[0]
        while(ln = newLineRegEx.exec(match)){
            line++
            match = match.slice(ln["index"]+1)
        }
        src = src.slice(matches[0].length)
        return true
    }

    function consumer(regex, process) {
        return function() {
            var matches = regex.exec(src)
            if(!matches) return null
            src = src.slice(matches[0].length)
            if(typeof process == "function")    return process(matches[0])
            return matches[0]
        }
    }

    function parserFactory(parsers) {
        return function() {
            for(index in parsers){
                var parser = parsers[index]
                spaceParser()
                var result = parser()
                if(result)  return result
            }
            return null
        }
    }

    var nullParser = consumer(nullRegEx, function(val){return {type: "Literal", value: null}})
    var booleanParser = consumer(booleanRegEx, function(val){return {type: "Literal", value: val}})
    var numberParser = consumer(numberRegEx, function(val){return {type: "Literal", value: Number(val)}})
    var stringParser = consumer(stringRegEx, function(val){return {type: "Literal", value: val.slice(1,val.length-1)}})
    var literalParser = parserFactory([nullParser, booleanParser, numberParser, stringParser])
    var identifierParser = consumer(identifierRegEx, function(val) {return {type: "Identifier", name: val}})
    var openParanthesesParser = consumer(openParanthesesRegEx, function(val){return true})
    var closingParanthesesParser = consumer(closingParanthesesRegEx, function(val){return true})
    var operatorParser = consumer(operatorRegEx)
    var varKeywordParser = consumer(varKeywordRegEx)
    var functionKeywordParser = consumer(functionKeywordRegEx)
    var macroKeywordParser = consumer(macroKeywordRegEx)
    var fatArrowParser = consumer(fatArrowRegEx)

    function argumentsParser() {
        var args = []
        spaceParser()
        while(!closingParanthesesParser()){
            arg = argStatementParser()
            if (!arg)
                throw new SyntaxError("argumentsParser : Unexpected character at line: "+line)
            args.push(arg)
            spaceParser()
        }
        spaceParser()
        if (args.length > 0)
            return args
        return null
    }

    function elementParser() {
        return literalParser() || identifierParser()
    }

    function expressionParser() {
        if (!openParanthesesParser()) return null
        return callExpressionParser() || binaryExpressionParser() || statementParser()
    }

    function expressionStatementParser() {
        spaceParser()
        if (closingParanthesesParser())  return null
        return {type: "ExpressionStatement", expression: expressionParser()}
    }

    function dereferencer(macro, tree) {
        for(objs in tree){
            if (typeof tree[objs] == "object") {
                if (Array.isArray(tree[objs])) {
                    tree[objs].forEach(function(t){
                        tree[objs] = [dereferencer(macro, t)]
                    })
                }
                else{
                    tree[objs] = dereferencer(macro, tree[objs])
                }
            }

            if (tree[objs] == "Identifier") {
                if (tilde = /^\~.*\b/.exec(tree.name)) {
                    var ref = tilde[0].slice(1)
                    var temp = src
                    src = macro.params[ref].toString()
                    var refTree = elementParser()
                    src = temp
                    return refTree

                }
            }
        }

        return tree
    }

    function macroCallParser() {
        var temp = src
        if(!openParanthesesParser()) return null
        spaceParser()
        var expr = {}
        if (expr.callee = identifierParser()) {
            spaceParser()
            expr.arguments = argumentsParser() || []
            if (macroCopy = macros[expr.callee.name.toString()]) {
                var macro = JSON.parse(JSON.stringify(macroCopy))
                var macroName = expr.callee.name
                var args = expr.arguments.map(function(arg){
                    if(arg.value){
                        if (typeof arg.value == "string")    return '"'+arg.value+'"'
                        return arg.value
                    }
                    return arg.name
                })
                for(param in macro.params){
                    if (param != "rest")
                        macro.params[param] = args.shift()
                }
                macro.params.rest = args
                var macroExpr = dereferencer(macro, macro.body)
                return macroExpr
            }
        }

        src = temp
        return null
    }
    function callExpressionParser() {
        spaceParser()
        var expr = {type: "CallExpression"}
        if (expr.callee = identifierParser()) {
            spaceParser()
            expr.arguments = argumentsParser() || []
            spaceParser()
            return expr
        }
        return null
    }

    function binaryExpressionParser() {
        var expr = {type: "BinaryExpression"}
        if (expr.operator = operatorParser()) {
            spaceParser()
            expr.left = elementParser() //This should probably not be an elementParser. Could also be a function call.
            if (expr.left) {
                spaceParser()
                expr.right = elementParser() //same as left
                if (expr.right) {
                    spaceParser()
                    if (closingParanthesesParser())
                        return expr
                }
            }
        }
        return null
    }

    function extractExpression() {
        var found = false, parantheses = 1, i = 0
        while(!found){
            if (src[i] == '(')
                parantheses++
            if (src[i] == ')')
                parantheses--
            if (parantheses == 0)
                found = true
            i++
        }

        return src.slice(0,i)
    }

    function macroDeclarationParser() {
        if (!macroKeywordParser())    return null
        var snippet = extractExpression()
        var rest = src.slice(snippet.length)
        src = snippet
        spaceParser()

        //id
        if (id = identifierParser())
            macroId = id.name
        else
            throw new SyntaxError("Expecting a macro identifier")
        spaceParser()

        //params
        if (!openParanthesesParser())
            throw new SyntaxError("Expecting '(' after " + macroId)

        var macro = {}
        macro.params = {}
        while(!closingParanthesesParser()){
            if (param = identifierParser()) {
                var paramName = param.name
                // param[paramName.toString()] = null
                macro.params[paramName.toString()] = null
            }
            spaceParser()
        }
        macro.params["rest"] = []
        spaceParser()

        //body
        macro.body = []

        //Not very desirable, might go in infinite loop
        while(src.length != 0){
            macro.body.push(statementParser(src.slice(0,src.length-1)))
            spaceParser()
            closingParanthesesParser()
        }

        src = rest
        spaceParser()

        macros[macroId.toString()] = macro
        return null

    }

    function functionDeclarationParser() {
        if (!functionKeywordParser())    return null
        var snippet = extractExpression()
        var rest = src.slice(snippet.length)
        src = snippet
        spaceParser()
        var expr = {type: "FunctionDeclaration"}

        //id
        if (id = identifierParser())
            expr.id = id
        else
            throw new SyntaxError("Expecting a function name")
        spaceParser()

        //params
        if (!openParanthesesParser())
            throw new SyntaxError("Expecting '(' after " + expr.id)
        expr.params = argumentsParser() || []
        spaceParser() //Argumentsparser has a spaceParser at the end. so not needed here

        //defaults
        expr.defaults = []

        //body
        expr.body = {type: "BlockStatement", body: functionBodyParser()}
        src = rest
        spaceParser()

        //generator
        expr.generator = false

        //expression
        expr.expression = false

        return expr
    }

    function variableDeclarationParser() {
        if (!varKeywordParser()) return null
        var expr = {type: "VariableDeclaration", declarations: []}
        spaceParser()
        var innerExpr = {type: "VariableDeclarator"}
        if (innerExpr.id = identifierParser()) {
            spaceParser()
            if (!closingParanthesesParser()) {
                if (initVal = elementParser()) {
                    innerExpr.init = initVal
                }
                else{
                    innerExpr.init = expressionParser()
                    closingParanthesesParser()
                }
            }
            expr.declarations.push(innerExpr)
        }
        else
            throw new SyntaxError("Invalid variable name")
        expr.kind = "var"
        spaceParser()
        closingParanthesesParser()
        return expr
    }

    function arrowFunctionParser() {
        if (!fatArrowParser())   return null
        spaceParser()
        var snippet = extractExpression()
        var rest = src.slice(snippet.length)
        src = snippet
        spaceParser()
        var expr = {type: "ArrowFunctionExpression", id: null, params: [], defaults: [], body: null, generator: false, expression: false}

        if (!openParanthesesParser())
            throw new SyntaxError("Expecting '(' after " + expr.id)
        expr.params = argumentsParser() || []
        spaceParser()

        expr.body = {type: "BlockStatement", body: functionBodyParser()}
        src = rest
        return expr
    }

    function extractStatements() {
        var stmts = [], openP = 0, idx = 0
        for(var i = 0; i < src.length; i++){
            if (i != 0 && openP == 0) {
                var stmt = src.slice(idx, i)
                if (stmt.length > 0)
                    stmts.push(stmt)
                idx = i
            }
            if (src[i] == '(')
                openP++
            if (src[i] == ')')
                openP--
        }
        return stmts
    }

    function functionBodyParser() {
        var stmts = []
        var expr = []
        extractStatements().forEach(function(stmt) {
            src = stmt
            spaceParser()
            if (src.length > 0)
                stmts.push(stmt)
        })
        while(stmts.length != 0){
            src = stmts.shift()
            if (stmts.length > 0) {
                //Not a return statement
                expr.push(statementParser())
            }
            else{
                //Return statement
                expr.push({type: "ReturnStatement", argument: argStatementParser()})
            }
        }
        return expr
    }

    function statementParser() {
        return arrowFunctionParser() || macroDeclarationParser()|| functionDeclarationParser() || variableDeclarationParser() || elementParser() || macroCallParser() || expressionStatementParser()
    }

    // Have to figure out a way to remove this function
    function argStatementParser() {
        return arrowFunctionParser() || macroDeclarationParser()|| functionDeclarationParser() || variableDeclarationParser() || elementParser() || expressionParser()
    }

    function bodyParser() {
        var body = []
        while(src.length != 0){
            spaceParser()
            var stmt = statementParser()
            if (!stmt)
                throw new SyntaxError("Cannot parse statement at line: " + line)
            if(Array.isArray(stmt))
                stmt.forEach(function(s){body.push(s)})
            else
                body.push(stmt)

        }
        return body
    }

    ast.body = bodyParser()
    return ast
}<commit_msg>Changes new line counting logic<commit_after>/*
 * Copyright (c) 2015 Mansi Shah, Santosh Rajan
*/

var ast = {
        type: "Program",
        body: []
    }

module.exports = function(src) {

    var spaceRegEx = /^[ \t\r\n\b\f]+/,
        newLineRegEx = /\r?\n/g,
        nullRegEx = /^null\b/i,
        booleanRegEx = /^(true|false)\b/i,
        numberRegEx = /^[-+]?(\d+(\.\d*)?|\.\d+)([e][+-]?\d+)?/i,
        stringRegEx = /^('|").*?[^\\]\1/,
        identifierRegEx = /^[a-z\~]+[a-z0-9_\[\]\.\*]*/i,
        openParanthesesRegEx = /^\(/,
        closingParanthesesRegEx = /^\)/,
        operatorRegEx = /^(\*|\+|\-|\/|\%)/,
        functionKeywordRegEx = /^(\()(\s)*function/,
        macroKeywordRegEx = /^(\()(\s)*macro\b/,
        varKeywordRegEx = /^(\()?(\s)*var/,
        fatArrowRegEx = /^\=\>/,
        line = 1
        macros = {}

    function consumer(regex, process) {
        return function() {
            var matches = regex.exec(src)
            if(!matches) return null
            src = src.slice(matches[0].length)
            if(typeof process == "function")    return process(matches[0])
            return matches[0]
        }
    }

    function parserFactory(parsers) {
        return function() {
            for(index in parsers){
                var parser = parsers[index]
                spaceParser()
                var result = parser()
                if(result)  return result
            }
            return null
        }
    }

    function spaceParser() {
        var matches = spaceRegEx.exec(src)
        if (!matches) return null
        var match = matches[0].match(newLineRegEx)
        var l = (match)? match.length : 0
        line+=l
        src = src.slice(matches[0].length)
        return true
    }

    var nullParser = consumer(nullRegEx, function(val){
            return {type: "Literal", value: null}
        }),
        booleanParser = consumer(booleanRegEx, function(val){
            return {type: "Literal", value: val}
        }),
        numberParser = consumer(numberRegEx, function(val){
            return {type: "Literal", value: Number(val)}
        }),
        stringParser = consumer(stringRegEx, function(val){
            return {type: "Literal", value: val.slice(1,val.length-1)}
        }),
        literalParser = parserFactory([nullParser, booleanParser, numberParser, stringParser]),
        identifierParser = consumer(identifierRegEx, function(val) {
            return {type: "Identifier", name: val}
        }),
        openParanthesesParser = consumer(openParanthesesRegEx, function(val){
            return true
        }),
        closingParanthesesParser = consumer(closingParanthesesRegEx, function(val){
            return true
        }),
        operatorParser = consumer(operatorRegEx),
        varKeywordParser = consumer(varKeywordRegEx),
        functionKeywordParser = consumer(functionKeywordRegEx),
        macroKeywordParser = consumer(macroKeywordRegEx),
        fatArrowParser = consumer(fatArrowRegEx)

    function argumentsParser() {
        var args = []
        spaceParser()
        while(!closingParanthesesParser()){
            arg = argStatementParser()
            if (!arg)
                throw new SyntaxError("argumentsParser : Unexpected character at line: "+line)
            args.push(arg)
            spaceParser()
        }
        spaceParser()
        if (args.length > 0)
            return args
        return null
    }

    function elementParser() {
        return literalParser() || identifierParser()
    }

    function expressionParser() {
        if (!openParanthesesParser()) return null
        return callExpressionParser() || binaryExpressionParser() || statementParser()
    }

    function expressionStatementParser() {
        spaceParser()
        if (closingParanthesesParser())  return null
        return {type: "ExpressionStatement", expression: expressionParser()}
    }

    function dereferencer(macro, tree) {
        for(objs in tree){
            if (typeof tree[objs] == "object") {
                if (Array.isArray(tree[objs])) {
                    tree[objs].forEach(function(t){
                        tree[objs] = [dereferencer(macro, t)]
                    })
                }
                else{
                    tree[objs] = dereferencer(macro, tree[objs])
                }
            }

            if (tree[objs] == "Identifier") {
                if (tilde = /^\~.*\b/.exec(tree.name)) {
                    var ref = tilde[0].slice(1)
                    var temp = src
                    src = macro.params[ref].toString()
                    var refTree = elementParser()
                    src = temp
                    return refTree

                }
            }
        }

        return tree
    }

    function macroCallParser() {
        var temp = src
        if(!openParanthesesParser()) return null
        spaceParser()
        var expr = {}
        if (expr.callee = identifierParser()) {
            spaceParser()
            expr.arguments = argumentsParser() || []
            if (macroCopy = macros[expr.callee.name.toString()]) {
                var macro = JSON.parse(JSON.stringify(macroCopy))
                var macroName = expr.callee.name
                var args = expr.arguments.map(function(arg){
                    if(arg.value){
                        if (typeof arg.value == "string")    return '"'+arg.value+'"'
                        return arg.value
                    }
                    return arg.name
                })
                for(param in macro.params){
                    if (param != "rest")
                        macro.params[param] = args.shift()
                }
                macro.params.rest = args
                var macroExpr = dereferencer(macro, macro.body)
                return macroExpr
            }
        }

        src = temp
        return null
    }
    function callExpressionParser() {
        spaceParser()
        var expr = {type: "CallExpression"}
        if (expr.callee = identifierParser()) {
            spaceParser()
            expr.arguments = argumentsParser() || []
            spaceParser()
            return expr
        }
        return null
    }

    function binaryExpressionParser() {
        var expr = {type: "BinaryExpression"}
        if (expr.operator = operatorParser()) {
            spaceParser()
            expr.left = elementParser() //This should probably not be an elementParser. Could also be a function call.
            if (expr.left) {
                spaceParser()
                expr.right = elementParser() //same as left
                if (expr.right) {
                    spaceParser()
                    if (closingParanthesesParser())
                        return expr
                }
            }
        }
        return null
    }

    function extractExpression() {
        var found = false, parantheses = 1, i = 0
        while(!found){
            if (src[i] == '(')
                parantheses++
            if (src[i] == ')')
                parantheses--
            if (parantheses == 0)
                found = true
            i++
        }

        return src.slice(0,i)
    }

    function macroDeclarationParser() {
        if (!macroKeywordParser())    return null
        var snippet = extractExpression()
        var rest = src.slice(snippet.length)
        src = snippet
        spaceParser()

        //id
        if (id = identifierParser())
            macroId = id.name
        else
            throw new SyntaxError("Expecting a macro identifier")
        spaceParser()

        //params
        if (!openParanthesesParser())
            throw new SyntaxError("Expecting '(' after " + macroId)

        var macro = {}
        macro.params = {}
        while(!closingParanthesesParser()){
            if (param = identifierParser()) {
                var paramName = param.name
                // param[paramName.toString()] = null
                macro.params[paramName.toString()] = null
            }
            spaceParser()
        }
        macro.params["rest"] = []
        spaceParser()

        //body
        macro.body = []

        //Not very desirable, might go in infinite loop
        while(src.length != 0){
            macro.body.push(statementParser(src.slice(0,src.length-1)))
            spaceParser()
            closingParanthesesParser()
        }

        src = rest
        spaceParser()

        macros[macroId.toString()] = macro
        return null

    }

    function functionDeclarationParser() {
        if (!functionKeywordParser())    return null
        var snippet = extractExpression()
        var rest = src.slice(snippet.length)
        src = snippet
        spaceParser()
        var expr = {type: "FunctionDeclaration"}

        //id
        if (id = identifierParser())
            expr.id = id
        else
            throw new SyntaxError("Expecting a function name")
        spaceParser()

        //params
        if (!openParanthesesParser())
            throw new SyntaxError("Expecting '(' after " + expr.id)
        expr.params = argumentsParser() || []
        spaceParser() //Argumentsparser has a spaceParser at the end. so not needed here

        //defaults
        expr.defaults = []

        //body
        expr.body = {type: "BlockStatement", body: functionBodyParser()}
        src = rest
        spaceParser()

        //generator
        expr.generator = false

        //expression
        expr.expression = false

        return expr
    }

    function variableDeclarationParser() {
        if (!varKeywordParser()) return null
        var expr = {type: "VariableDeclaration", declarations: []}
        spaceParser()
        var innerExpr = {type: "VariableDeclarator"}
        if (innerExpr.id = identifierParser()) {
            spaceParser()
            if (!closingParanthesesParser()) {
                if (initVal = elementParser()) {
                    innerExpr.init = initVal
                }
                else{
                    innerExpr.init = expressionParser()
                    closingParanthesesParser()
                }
            }
            expr.declarations.push(innerExpr)
        }
        else
            throw new SyntaxError("Invalid variable name")
        expr.kind = "var"
        spaceParser()
        closingParanthesesParser()
        return expr
    }

    function arrowFunctionParser() {
        if (!fatArrowParser())   return null
        spaceParser()
        var snippet = extractExpression()
        var rest = src.slice(snippet.length)
        src = snippet
        spaceParser()
        var expr = {type: "ArrowFunctionExpression", id: null, params: [], defaults: [], body: null, generator: false, expression: false}

        if (!openParanthesesParser())
            throw new SyntaxError("Expecting '(' after " + expr.id)
        expr.params = argumentsParser() || []
        spaceParser()

        expr.body = {type: "BlockStatement", body: functionBodyParser()}
        src = rest
        return expr
    }

    function extractStatements() {
        var stmts = [], openP = 0, idx = 0
        for(var i = 0; i < src.length; i++){
            if (i != 0 && openP == 0) {
                var stmt = src.slice(idx, i)
                if (stmt.length > 0)
                    stmts.push(stmt)
                idx = i
            }
            if (src[i] == '(')
                openP++
            if (src[i] == ')')
                openP--
        }
        return stmts
    }

    function functionBodyParser() {
        var stmts = []
        var expr = []
        extractStatements().forEach(function(stmt) {
            src = stmt
            spaceParser()
            if (src.length > 0)
                stmts.push(stmt)
        })
        while(stmts.length != 0){
            src = stmts.shift()
            if (stmts.length > 0) {
                //Not a return statement
                expr.push(statementParser())
            }
            else{
                //Return statement
                expr.push({type: "ReturnStatement", argument: argStatementParser()})
            }
        }
        return expr
    }

    function statementParser() {
        return arrowFunctionParser() || macroDeclarationParser()|| functionDeclarationParser() || variableDeclarationParser() || elementParser() || macroCallParser() || expressionStatementParser()
    }

    // Have to figure out a way to remove this function
    function argStatementParser() {
        return arrowFunctionParser() || macroDeclarationParser()|| functionDeclarationParser() || variableDeclarationParser() || elementParser() || expressionParser()
    }

    function bodyParser() {
        var body = []
        while(src.length != 0){
            spaceParser()
            var stmt = statementParser()
            if (!stmt)
                throw new SyntaxError("Cannot parse statement at line: " + line)
            if(Array.isArray(stmt))
                stmt.forEach(function(s){body.push(s)})
            else
                body.push(stmt)

        }
        return body
    }

    ast.body = bodyParser()
    return ast
}<|endoftext|>


<commit_before>export default class Player {
  constructor({ x = 100, y = 100, radius = 20, color = 'blue', controls = 'arrows' } = {}, map) {
    this.x = x
    this.y = y
    this.radius = radius
    this.startAngle = 0
    this.endAngle = Math.PI * 2
    this.fill = color
    this.controls = controls
    this.map = map
  }

  draw(context) {
    context.beginPath()
    context.fillStyle = this.fill
    context.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle, true)
    context.fill()
  }

  move(keys) {
    this.wallCollision(this.x, this.y)

    if (this.controls == 'arrows') {
      if (keys.leftArrow) { this.x-- }
      if (keys.upArrow) { this.y-- }
      if (keys.rightArrow) { this.x++ }
      if (keys.downArrow) { this.y++ }
    } else {
      if (keys.A) { this.x-- }
      if (keys.W) { this.y-- }
      if (keys.D) { this.x++ }
      if (keys.S) { this.y++ }
    }
  }

  wallCollision(x, y) {
    var top = this.y - (this.radius + 1)
    var right = this.x + (this.radius + 1)
    var bottom = this.y + (this.radius + 1)
    var left = this.x - (this.radius + 1)

    if (this.map.isWallCollision(this.x, top)) {
      this.y++
    }
    if (this.map.isWallCollision(right, this.y)) {
      this.x--
    }
    if (this.map.isWallCollision(this.x, bottom)) {
      this.y--
    }
    if (this.map.isWallCollision(left, this.y)) {
      this.x++
    }
  }
}
<commit_msg>ball rendered as sprite image (#21)<commit_after>export default class Player {
  constructor({ x = 100, y = 100, radius = 20, color = 'blue', controls = 'arrows' } = {}, map) {
    this.x = x
    this.y = y
    this.radius = radius
    this.color = color
    this.playerImg = this.loadPlayerImage()
    this.controls = controls
    this.map = map
  }

  loadPlayerImage() {
    var playerImg = new Image()
    playerImg.src = './lib/assets/tiles.png'
    return playerImg
  }

  determinePlayerTilePxl() {
    if (this.color == 'blue') {
      return 600
    } else if (this.color == 'red') {
      return 560
    }
  }

  draw(context) {
    context.drawImage(
        this.playerImg,
        this.determinePlayerTilePxl(),
        0,
        this.map.tsize,
        this.map.tsize,
        this.x - this.radius,
        this.y - this.radius,
        this.map.tsize,
        this.map.tsize
    )
  }

  move(keys) {
    this.wallCollision(this.x, this.y)

    if (this.controls == 'arrows') {
      if (keys.leftArrow) { this.x-- }
      if (keys.upArrow) { this.y-- }
      if (keys.rightArrow) { this.x++ }
      if (keys.downArrow) { this.y++ }
    } else {
      if (keys.A) { this.x-- }
      if (keys.W) { this.y-- }
      if (keys.D) { this.x++ }
      if (keys.S) { this.y++ }
    }
  }

  wallCollision(x, y) {
    var top = this.y - (this.radius + 1)
    var right = this.x + (this.radius + 1)
    var bottom = this.y + (this.radius + 1)
    var left = this.x - (this.radius + 1)

    if (this.map.isWallCollision(this.x, top)) {
      this.y++
    }
    if (this.map.isWallCollision(right, this.y)) {
      this.x--
    }
    if (this.map.isWallCollision(this.x, bottom)) {
      this.y--
    }
    if (this.map.isWallCollision(left, this.y)) {
      this.x++
    }
  }
}
<|endoftext|>


<commit_before>describe('gulp-ng-config', function () {
  var expect,
      should,
      plugin = require('../gulp-ng-config'),
      gulp = require('gulp'),
      path = require('path'),
      chai = require('chai'),
      spies = require('chai-spies'),
      File = require('vinyl'),
      es = require('event-stream'),
      through = require('through2'),
      fs = require('fs');

  before(function () {
    chai.use(spies);
    expect = chai.expect;
    should = chai.should;
  });

  describe('error handling', function () {
    it('should throw an error if a module name is missing', function () {
      expect(function () {
        plugin();
      }).to.throw(Error);
    });

    it ('should only accept files in JSON format', function () {
      var mockFiles = [
        new File({
          path: 'mock/path.json',
          contents: es.readArray(['one', 'two'])
        }),
        new File({
          path: 'mock/path.json',
          contents: new Buffer('a string')
        }),
        new File({
          path: 'mock/path.json',
          contents: new Buffer(123)
        })
      ];
      mockFiles.forEach(function (file) {
        var stream = plugin('outputConfigurationName');
        stream.on('error', function (error) {
          expect(error.message).to.be.eql('invalid JSON file provided');
        });
        expect(function () {
          stream.write(file);
        }).not.to.throw();
      });
    });

    it('should emit an error on malformed JSON', function () {
      var file,
          stream;
      stream = plugin('asdf');
      stream.on('error', function (error) {
        expect(error.message).to.be.equal('invalid JSON file provided');
      });
      file = new File({
        path: 'mock/path.json',
        contents: new Buffer('{a:b}')
      });

      expect(function () {
        stream.write(file);
      }).to.not.throw();
    });
  });

  describe('config generation', function () {
    describe('json', function () {
      it('should generate the angular template with scalar properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_1.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_1.json'))
            .pipe(plugin('gulp-ng-config'))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
      it('should generate the angular template with object properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_2.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
            .pipe(plugin('gulp-ng-config'))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
    });
    describe('yml', function () {
      it('should generate the angular template with scalar properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_1.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_1.yml'))
            .pipe(plugin('gulp-ng-config', {
              parser: 'yml'
            }))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
      it('should generate the angular template with object properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_2.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_2.yml'))
            .pipe(plugin('gulp-ng-config', {
              parser: 'yml'
            }))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
      it('should generate the angular template with object properties with no parser', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_2.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_2.yml'))
            .pipe(plugin('gulp-ng-config'))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
    });
    describe('yaml', function () {
      it('should generate the angular template with object properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_2.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_2.yaml'))
            .pipe(plugin('gulp-ng-config', {
              parser: 'yaml'
            }))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
    });
  });
  describe('plugin options', function () {
    it('should generate the angular template with overridable properties', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_3.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            constants: {
              one: {
                two: 'four'
              }
            }
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate the angular template with overridable and mergable properties', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_4.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            constants: {
              one: {
                three: 'four'
              }
            }
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate the angular template without declaring a new module', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_5.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            createModule: false
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate the angular template with an IFFE if options.wrap', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_6.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            wrap: true
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate the angular template with a custom wrap function if options.wrap is a string',
        function (done) {
          var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_7.js'));
          gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
              .pipe(plugin('gulp-ng-config', {
                wrap: 'define([\'angular\', function () {\n return <%= module %>}]);\n'
              }))
              .pipe(through.obj(function (file) {
                expect(file.contents.toString()).to.equal(expectedOutput.toString());
                done();
              }));
        });
    it('should select an embedded json object if an environment key is supplied and the key exists', function (done) {
      var expectedOutputA = fs.readFileSync(path.normalize(__dirname + '/mocks/output_8.js')), // match envA
          expectedOutputB = fs.readFileSync(path.normalize(__dirname + '/mocks/output_9.js')), // match envB
          expectedOutputC = fs.readFileSync(path.normalize(__dirname + '/mocks/output_15.js')), // match envA
          streamA = gulp.src(path.normalize(__dirname + '/mocks/input_3.json')),
          streamB = gulp.src(path.normalize(__dirname + '/mocks/input_3.json')),
          streamC = gulp.src(path.normalize(__dirname + '/mocks/input_4.json'));

      // tests output with `environmentA`
      streamA.pipe(plugin('gulp-ng-config', {
        environment: 'environmentA'
      }))
      .pipe(through.obj(function (file) {
        expect(file.contents.toString()).to.equal(expectedOutputA.toString());
      }));

      // tests output with `environmentB`
      streamB.pipe(plugin('gulp-ng-config', {
        environment: 'environmentB'
      }))
      .pipe(through.obj(function (file) {
        expect(file.contents.toString()).to.equal(expectedOutputB.toString());
      }));

      // tests output with nested environment `env.environmentA`
      streamC
      .pipe(plugin('gulp-ng-config', {
        environment: 'env.environmentA'
      }))
      .pipe(through.obj(function (file) {
        expect(file.contents.toString()).to.equal(expectedOutputC.toString());
      }));

      es.merge(streamA, streamB, streamC)
      .pipe(through.obj(function () {
        done();
      }));
    });

    it('should emit an error if an environment key is supplied and the key does not exist', function (done) {
      var stream = gulp.src(path.normalize(__dirname + '/mocks/input_3.json'));

      stream.pipe(plugin('gulp-ng-config', {
        environment: 'nonExistingEnvironment'
      })).on('error', function (error) {
        expect(error.message).to.be.eql('invalid \'environment\' value');
        done();
      });
    });

    it('should merge environment keys with constant keys', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_11.js')),
          streamA = gulp.src(path.normalize(__dirname + '/mocks/input_3.json'));

      streamA
          .pipe(plugin('gulp-ng-config', {
            environment: 'environmentA',
            constants: {
              constant: 'value'
            }
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate pretty-looked content with default spaces', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_12.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            pretty: true
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate common-looked content with pretty set to false', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_14.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            pretty: false
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate pretty-looked content with number of spaces', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_13.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            pretty: 4
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    //it ('should generate an error when unacceptable value passed as pretty param', function (done) {
    //TODO should handle an error
    //var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_13.js'));
    //gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
    //    .pipe(plugin('gulp-ng-config', {
    //      pretty: 4.1
    //    }))
    //    .pipe(through.obj(function (file) {
    //      expect(file.contents.toString()).to.equal(expectedOutput.toString());
    //      done();
    //    }));
    //});
  });
});
<commit_msg>pass build<commit_after>describe('gulp-ng-config', function () {
  var expect,
      should,
      plugin = require('../gulp-ng-config'),
      gulp = require('gulp'),
      path = require('path'),
      chai = require('chai'),
      spies = require('chai-spies'),
      File = require('vinyl'),
      es = require('event-stream'),
      through = require('through2'),
      fs = require('fs');

  before(function () {
    chai.use(spies);
    expect = chai.expect;
    should = chai.should;
  });

  describe('error handling', function () {
    it('should throw an error if a module name is missing', function () {
      expect(function () {
        plugin();
      }).to.throw(Error);
    });

    it ('should only accept files in JSON format', function () {
      var mockFiles = [
        new File({
          path: 'mock/path.json',
          contents: es.readArray(['one', 'two'])
        }),
        new File({
          path: 'mock/path.json',
          contents: new Buffer('a string')
        }),
        new File({
          path: 'mock/path.json',
          contents: new Buffer(123)
        })
      ];
      mockFiles.forEach(function (file) {
        var stream = plugin('outputConfigurationName');
        stream.on('error', function (error) {
          expect(error.message).to.be.eql('invalid JSON file provided');
        });
        expect(function () {
          stream.write(file);
        }).not.to.throw();
      });
    });

    it('should emit an error on malformed JSON', function () {
      var file,
          stream;
      stream = plugin('asdf');
      stream.on('error', function (error) {
        expect(error.message).to.be.equal('invalid JSON file provided');
      });
      file = new File({
        path: 'mock/path.json',
        contents: new Buffer('{a:b}')
      });
      expect(function () {
        stream.write(file);
      }).to.not.throw();
    });
  });

  describe('config generation', function () {
    describe('json', function () {
      it('should generate the angular template with scalar properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_1.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_1.json'))
            .pipe(plugin('gulp-ng-config'))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
      it('should generate the angular template with object properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_2.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
            .pipe(plugin('gulp-ng-config'))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
    });
    describe('yml', function () {
      it('should generate the angular template with scalar properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_1.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_1.yml'))
            .pipe(plugin('gulp-ng-config', {
              parser: 'yml'
            }))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
      it('should generate the angular template with object properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_2.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_2.yml'))
            .pipe(plugin('gulp-ng-config', {
              parser: 'yml'
            }))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
      it('should generate the angular template with object properties with no parser', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_2.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_2.yml'))
            .pipe(plugin('gulp-ng-config'))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
    });
    describe('yaml', function () {
      it('should generate the angular template with object properties', function (done) {
        var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_2.js'));
        gulp.src(path.normalize(__dirname + '/mocks/input_2.yaml'))
            .pipe(plugin('gulp-ng-config', {
              parser: 'yaml'
            }))
            .pipe(through.obj(function (file) {
              expect(file.contents.toString()).to.equal(expectedOutput.toString());
              done();
            }));
      });
    });
  });
  describe('plugin options', function () {
    it('should generate the angular template with overridable properties', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_3.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            constants: {
              one: {
                two: 'four'
              }
            }
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate the angular template with overridable and mergable properties', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_4.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            constants: {
              one: {
                three: 'four'
              }
            }
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate the angular template without declaring a new module', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_5.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            createModule: false
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate the angular template with an IFFE if options.wrap', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_6.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            wrap: true
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate the angular template with a custom wrap function if options.wrap is a string',
        function (done) {
          var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_7.js'));
          gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
              .pipe(plugin('gulp-ng-config', {
                wrap: 'define([\'angular\', function () {\n return <%= module %>}]);\n'
              }))
              .pipe(through.obj(function (file) {
                expect(file.contents.toString()).to.equal(expectedOutput.toString());
                done();
              }));
        });
    it('should select an embedded json object if an environment key is supplied and the key exists', function (done) {
      var expectedOutputA = fs.readFileSync(path.normalize(__dirname + '/mocks/output_8.js')), // match envA
          expectedOutputB = fs.readFileSync(path.normalize(__dirname + '/mocks/output_9.js')), // match envB
          expectedOutputC = fs.readFileSync(path.normalize(__dirname + '/mocks/output_15.js')), // match envA
          streamA = gulp.src(path.normalize(__dirname + '/mocks/input_3.json')),
          streamB = gulp.src(path.normalize(__dirname + '/mocks/input_3.json')),
          streamC = gulp.src(path.normalize(__dirname + '/mocks/input_4.json'));

      // tests output with `environmentA`
      streamA.pipe(plugin('gulp-ng-config', {
        environment: 'environmentA'
      }))
      .pipe(through.obj(function (file) {
        expect(file.contents.toString()).to.equal(expectedOutputA.toString());
      }));

      // tests output with `environmentB`
      streamB.pipe(plugin('gulp-ng-config', {
        environment: 'environmentB'
      }))
      .pipe(through.obj(function (file) {
        expect(file.contents.toString()).to.equal(expectedOutputB.toString());
      }));

      // tests output with nested environment `env.environmentA`
      streamC
      .pipe(plugin('gulp-ng-config', {
        environment: 'env.environmentA'
      }))
      .pipe(through.obj(function (file) {
        expect(file.contents.toString()).to.equal(expectedOutputC.toString());
      }));

      es.merge(streamA, streamB, streamC)
      .pipe(through.obj(function () {
        done();
      }));
    });

    it('should emit an error if an environment key is supplied and the key does not exist', function (done) {
      var stream = gulp.src(path.normalize(__dirname + '/mocks/input_3.json'));

      stream.pipe(plugin('gulp-ng-config', {
        environment: 'nonExistingEnvironment'
      })).on('error', function (error) {
        expect(error.message).to.be.eql('invalid \'environment\' value');
        done();
      });
    });

    it('should merge environment keys with constant keys', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_11.js')),
          streamA = gulp.src(path.normalize(__dirname + '/mocks/input_3.json'));

      streamA
          .pipe(plugin('gulp-ng-config', {
            environment: 'environmentA',
            constants: {
              constant: 'value'
            }
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate pretty-looked content with default spaces', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_12.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            pretty: true
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate common-looked content with pretty set to false', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_14.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            pretty: false
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    it('should generate pretty-looked content with number of spaces', function (done) {
      var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_13.js'));
      gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
          .pipe(plugin('gulp-ng-config', {
            pretty: 4
          }))
          .pipe(through.obj(function (file) {
            expect(file.contents.toString()).to.equal(expectedOutput.toString());
            done();
          }));
    });
    //it ('should generate an error when unacceptable value passed as pretty param', function (done) {
    //TODO should handle an error
    //var expectedOutput = fs.readFileSync(path.normalize(__dirname + '/mocks/output_13.js'));
    //gulp.src(path.normalize(__dirname + '/mocks/input_2.json'))
    //    .pipe(plugin('gulp-ng-config', {
    //      pretty: 4.1
    //    }))
    //    .pipe(through.obj(function (file) {
    //      expect(file.contents.toString()).to.equal(expectedOutput.toString());
    //      done();
    //    }));
    //});
  });
});
<|endoftext|>


<commit_before>'use strict';

var ROOT = 'phrixus';
var _ = require('lodash');
var inflection = require('inflection');

var provider;
var logger;
var loggerSubscription;
var exports = {
  // basic operations
  CREATE: 'create',
  READ: 'read',
  UPDATE: 'update',
  DELETE: 'delete',
  AUTHENTICATE: 'authenticate'
};

// publishing is async
function publish(subject, op, target) {
  try {
    var type = (_.isString(target)) ? target : target.type;
    var topic = getTopic(type);
    // optimization: would be nice to tell if there are subscribers before I bother to create
    var event = new Event(subject, op, target);
    provider.publish(topic, event);
  }
  catch (err) {
    logger.error('unable to publish event', err);
  }
}

// returns subscription
function subscribe(type, subscriber) {
  return provider.subscribe(getTopic(type), subscriber);
}

function unsubscribe(subscriptionOrListener) {
  provider.unsubscribe(subscriptionOrListener);
}

function configure(config) {

  if (!provider || (config.provider && config.provider !== provider)) {
    if (provider && loggerSubscription) {
      provider.unsubscribe(loggerSubscription);
      loggerSubscription = null;
    }
    config = config || {};
    provider = config.provider || require('pubsub-js');

    if (config.sendToLogger) {
      logger = require('./logger')();
      loggerSubscription = subscribe(ROOT, function(topic, event) {
        logger.log(config.sendToLogger, 'event(%s): %j', topic, JSON.stringify(event));
      });
    }
  }

  exports.publish = publish;
  exports.subscribe = subscribe;
  exports.unsubscribe = unsubscribe;
}

module.exports = function(config) {
  if (config) { configure(config.events); }
  return exports;
};

function Event(subject, op, target) {
  this.subject = subject;
  this.op = op;             // create | read | update | delete
  this.target = target;
}

function getTopic(type) {
  if (type === ROOT) { return type; }
  return ROOT + '.' + inflection.pluralize(type);
}
<commit_msg>fix config check on events<commit_after>'use strict';

var ROOT = 'phrixus';
var _ = require('lodash');
var inflection = require('inflection');

var provider;
var logger;
var loggerSubscription;
var exports = {
  // basic operations
  CREATE: 'create',
  READ: 'read',
  UPDATE: 'update',
  DELETE: 'delete',
  AUTHENTICATE: 'authenticate'
};

// publishing is async
function publish(subject, op, target) {
  try {
    var type = (_.isString(target)) ? target : target.type;
    var topic = getTopic(type);
    // optimization: would be nice to tell if there are subscribers before I bother to create
    var event = new Event(subject, op, target);
    provider.publish(topic, event);
  }
  catch (err) {
    logger.error('unable to publish event', err);
  }
}

// returns subscription
function subscribe(type, subscriber) {
  return provider.subscribe(getTopic(type), subscriber);
}

function unsubscribe(subscriptionOrListener) {
  provider.unsubscribe(subscriptionOrListener);
}

function configure(config) {

  if (!provider || (config.provider && config.provider !== provider)) {
    if (provider && loggerSubscription) {
      provider.unsubscribe(loggerSubscription);
      loggerSubscription = null;
    }
    config = config || {};
    provider = config.provider || require('pubsub-js');

    if (config.sendToLogger) {
      logger = require('./logger')();
      loggerSubscription = subscribe(ROOT, function(topic, event) {
        logger.log(config.sendToLogger, 'event(%s): %j', topic, JSON.stringify(event));
      });
    }
  }

  exports.publish = publish;
  exports.subscribe = subscribe;
  exports.unsubscribe = unsubscribe;
}

module.exports = function(config) {
  if (config && config.events) { configure(config.events); }
  return exports;
};

function Event(subject, op, target) {
  this.subject = subject;
  this.op = op;             // create | read | update | delete
  this.target = target;
}

function getTopic(type) {
  if (type === ROOT) { return type; }
  return ROOT + '.' + inflection.pluralize(type);
}
<|endoftext|>


<commit_before>class Player {
  constructor(x, y, canvas, context) {
    this.x = x
    this.y = y
    this.height = 35
    this.width = 35
    this.canvas = canvas
    this.context = context
    this.blocks = []
  }

  draw() {
    this.context.fillRect(this.x, this.y, this.width, this.height)
  }

  move() {
    this.context.fillRect(this.x, this.y, this.width, this.height)
  }

  clear() {
    this.context.clearRect(this.x, this.y, this.width, this.height)
  }

  moveRight() {
    if (this.x < this.canvas.width - this.width) {
      const collidingBlocks = this.blocks.filter(this.rightCollide.bind(this))
      if (collidingBlocks.length === 0) {
        this.clear()
        this.x++
        this.move()
      }
    }
    return this
  }

  rightCollide(block) {
    return (this.x + this.width) === block.x &&
      ((block.y < this.y && this.y < block.y + block.height) ||
      (block.y < this.y + this.height && this.y + this.height < block.y + block.height))
  }

  leftCollide(block) {
    return this.x === (block.x + block.width) &&
      ((block.y < this.y && this.y < block.y + block.height) ||
      (block.y < this.y + this.height && this.y + this.height < block.y + block.height))
  }

  downCollide(block) {
    return (this.y + this.height) === block.y &&
      ((block.x < this.x && this.x < block.x + block.width) ||
      (block.x < this.x + this.width && this.x + this.width < block.x + block.width))
  }

  upCollide(block) {
    return this.y === (block.y + block.height) &&
      ((block.x < this.x && this.x < block.x + block.width) ||
      (block.x < this.x + this.width && this.x + this.width < block.x + block.width))
  }

  moveLeft() {
    if (this.x > 0) {
      const collidingBlocks = this.blocks.filter(this.leftCollide.bind(this))
      if (collidingBlocks.length === 0) {
        this.clear()
        this.x--
        this.move()
      }
    }
    return this
  }

  moveUp() {
    if (this.y > 0) {
      const collidingBlocks = this.blocks.filter(this.upCollide.bind(this))
      if (collidingBlocks.length === 0) {
        this.clear()
        this.y--
        this.move()
      }
    }
    return this
  }

  moveDown() {
    if (this.y < this.canvas.height - this.height) {
      const collidingBlocks = this.blocks.filter(this.downCollide.bind(this))
      if (collidingBlocks.length === 0) {
        this.clear()
        this.y++
        this.move()
      }
    }
    return this
  }
}

module.exports = Player
<commit_msg>edit collision functionality to work with higher speed<commit_after>class Player {
  constructor(x, y, canvas, context) {
    this.x = x
    this.y = y
    this.height = 35
    this.width = 35
    this.canvas = canvas
    this.context = context
    this.blocks = []
  }

  draw() {
    this.context.fillRect(this.x, this.y, this.width, this.height)
  }

  move() {
    this.context.fillRect(this.x, this.y, this.width, this.height)
  }

  clear() {
    this.context.clearRect(this.x, this.y, this.width, this.height)
  }

  moveRight() {
    if (this.x < this.canvas.width - this.width) {
      const collidingBlocks = this.blocks.filter(this.rightCollide.bind(this))
      if (collidingBlocks.length === 0) {
        this.clear()
        this.x+=3
        this.move()
      }
    }
    return this
  }

  rightCollide(block) {
    return (block.x -3 <= (this.x + this.width) && (this.x + this.width) <= block.x) &&
      ((block.y < this.y && this.y < block.y + block.height) ||
      (block.y < this.y + this.height && this.y + this.height < block.y + block.height))
  }

  leftCollide(block) {
    return (this.x <= (block.x + block.width + 3) && this.x >= (block.x + block.width)) &&
      ((block.y < this.y && this.y < block.y + block.height) ||
      (block.y < this.y + this.height && this.y + this.height < block.y + block.height))
  }

  downCollide(block) {
    return (this.y + this.height) === block.y &&
      ((block.x < this.x && this.x < block.x + block.width) ||
      (block.x < this.x + this.width && this.x + this.width < block.x + block.width))
  }

  upCollide(block) {
    return this.y === (block.y + block.height) &&
      ((block.x < this.x && this.x < block.x + block.width) ||
      (block.x < this.x + this.width && this.x + this.width < block.x + block.width))
  }

  moveLeft() {
    if (this.x > 0) {
      const collidingBlocks = this.blocks.filter(this.leftCollide.bind(this))
      if (collidingBlocks.length === 0) {
        this.clear()
        this.x-=3
        this.move()
      }
    }
    return this
  }

  moveUp() {
    if (this.y > 0) {
      const collidingBlocks = this.blocks.filter(this.upCollide.bind(this))
      if (collidingBlocks.length === 0) {
        this.clear()
        this.y--
        this.move()
      }
    }
    return this
  }

  moveDown() {
    if (this.y < this.canvas.height - this.height) {
      const collidingBlocks = this.blocks.filter(this.downCollide.bind(this))
      if (collidingBlocks.length === 0) {
        this.clear()
        this.y++
        this.move()
      }
    }
    return this
  }
}

module.exports = Player
<|endoftext|>


<commit_before>function createLoop(video, timeIn, timeOut) {
  var debug;
  var enableDebug = function() {
    debug = document.getElementById("loopdebug");
    video.controls = true;
  };

  video.controls = video.loop = false;
  video.volume = 1.0;

  if (location.hash.substr(1).toLowerCase() == "debug") {
    enableDebug();
  }

  var markers = [timeIn, timeOut];

  video.addEventListener("click", function() {
    e.preventDefault();
    video[video.paused ? "play" : "pause"]();
  }, false);

  video.addEventListener("error", function() {
    if (video.error.code < 2) {
      return;
    }
    alert("Whoops, "+(["a network error", "a decoding fault", "your browser is doodoo"])[video.error.code-2]);
  }, false);

  var checkMarkers = function() {
    if (debug) {
      debug.innerHTML = [video.currentTime, markers.join(","), video.src.split("/").splice(-1)[0], video.paused].join("
");
    }
  };

  var worker = new Worker("./worker.js");
  worker.onmessage = function(e) {
    if (e.data == "tick") {
      checkMarkers();
    }
  };

  video.play();
};
<commit_msg>FIXES ABOUND<commit_after>function createLoop(video, timeIn, timeOut) {
  var debug;
  var enableDebug = function() {
    debug = document.getElementById("loopdebug");
    console.log("DEBUGGING!");
    debug.style.visibility = "visible";
    video.controls = true;
  };

  video.controls = video.loop = false;
  video.volume = 1.0;

  if (location.hash.substr(1).toLowerCase() == "debug") {
    enableDebug();
  }

  var markers = [timeIn, timeOut];

  video.addEventListener("click", function(e) {
    e.preventDefault();
    video[video.paused ? "play" : "pause"]();
  }, false);

  video.addEventListener("error", function() {
    if (video.error.code < 2) {
      return;
    }
    alert("Whoops, "+(["a network error", "a decoding fault", "your browser is doodoo"])[video.error.code-2]);
  }, false);

  var checkMarkers = function() {
    if (debug) {
      debug.innerHTML = [video.currentTime, markers.join(","), video.src.split("/").splice(-1)[0], video.paused].join("
");
    }
    if (video.currentTime >= markers[1]) {
      video.currentTime = markers[0];
    }
  };

  var worker = new Worker("looper/worker.js");
  worker.onmessage = function(e) {
    if (e.data == "tick") {
      checkMarkers();
    }
  };

  video.play();
};
<|endoftext|>


<commit_before>this.d$ = this.jDist = (function( Math, j$ ) {

var jDist = function() {
	// TODO: finish implemenation of jDist object
	};

j$.extend( jDist, {
	beta : {
		pdf : function( x, alpha, beta ) {
			return ( Math.pow( x, alpha - 1 ) * Math.pow( 1 - x, beta - 1 ) ) / j$.betafn( alpha, beta );
		},

		cdf : function( x, alpha, beta ) {
			return j$.incompleteBeta( x, alpha, beta );
		},

		mean : function( alpha, beta ) {
			return alpha / ( alpha + beta );
		},

		median : function( alpha, beta ) {
			// TODO: implement beta median
		},

		mode : function( alpha, beta ) {
			return ( alpha * beta ) / ( Math.pow( alpha + beta, 2 ) * ( alpha + beta + 1 ));
		},

		variance : function( alpha, beta ) {
			return ( alpha * beta ) / ( Math.pow( alpha + beta, 2 ) * ( alpha + beta + 1 ) );
		}
	},

	cauchy : {
		pdf : function( x, xn, l ) {
			return ( l / ( Math.pow( x - xn, 2) + Math.pow( l, 2 ))) / Math.PI;
		},

		cdf : function( x, xn, l ) {
			return Math.atan(( x - xn) / l ) / Math.PI + 0.5;
		}
	},

	chisquare : {
		pdf : function( x, k ) {
			return (Math.pow( x, k / 2 - 1) * Math.exp( -x / 2 )) / ( Math.pow( 2, k / 2) * j$.gammafn( k / 2 ));
		},

		cdf : function( x, k ) {
			return j$.lgamma( x / 2, k / 2 ) / j$.gammafn( k / 2 );
		}
	},

	exponential : {
		pdf : function( x, rate ) {
			return x < 0 ? 0 : rate * Math.exp( -rate * x );
		},

		cdf : function( x, rate ) {
			return x < 0 ? 0 : 1 - Math.exp( -rate * x );
		},

		mean : function( rate ) {
			return 1 / rate;
		},

		median : function ( rate ) {
			return ( 1 / rate ) * Math.log(2);
		},

		mode : function( rate ) {
			return 0;
		},

		variance : function( rate ) {
			return Math.pow( rate, -2 );
		}
	},

	gamma : {
		pdf : function( x, shape, scale ) {
			return Math.pow( x, shape - 1 ) * ( Math.exp( -x / scale ) / ( j$.gammafn( shape ) * Math.pow( scale, shape ) ) );
		},

		cdf : function( x, shape, scale ) {
			return jlstat.gammap( x / scale, shape );
		},

		mean : function( shape, scale ) {
			return shape * scale;
		},

		mode : function( shape, scale ) {
			if( shape > 1 ) return ( k - 1 ) * scale;
			return undefined;
		},

		variance: function( shape, scale ) {
			return shape * scale * scale;
		}
	},

	lognormal : {
		pdf : function( x, mu, sigma ) {
			return ( 1 / ( x * sigma * Math.sqrt( 2 * Math.PI ) ) ) * Math.exp( -Math.pow( Math.log( x ) - mu, 2) / ( 2 * sigma*sigma ) );
		},

		cdf : function( x, mu, sigma ) {
			return 0.5 + ( 0.5 * j$.erf( ( Math.log( x ) - mu ) / Math.sqrt( 2 * sigma*sigma ) ) );
		},

		mean : function( mu, sigma ) {
			return Math.exp( mu + sigma*sigma / 2);
		},

		median : function( mu, sigma ) {
			return Math.exp(mu);
		},

		mode : function( mu, sigma ) {
			return Math.exp( mu - sigma*sigma );
		},

		variance : function( mu, sigma ) {
			return ( Math.exp( sigma*sigma ) - 1 ) * Math.exp( 2 * mu + sigma*sigma );
		}
	},

	normal : {
		pdf : function( x, mean, std ) {
			return ( 1 / ( Math.sqrt( 2 * Math.PI * std * std))) * Math.exp( -( Math.pow( x - mean, 2 ) / 2 * std * std ) );
		},

		cdf : function( x, mean, std ) {
			return 0.5 * ( 1 + j$.erf( ( x - mean ) / Math.sqrt( 2 * std * std ) ) );
		},

		mean : function( mean, std ) {
			return mean;
		},

		median : function( mean, std ) {
			return mean;
		},

		mode : function ( mean, std ) {
			return mean;
		},

		variance : function( mean, std ) {
			return std * std;
		}
	},

	weibull : {
		pdf : function( x, scale, shape ) {
			return x < 0 ? 0 : ( shape / scale ) * Math.pow(( x / scale ),( shape - 1 )) * Math.exp(-( Math.pow(( x / scale ), shape )));
		},

		cdf : function( x, scale, shape ) {
			return x < 0 ? 0 : 1 - Math.exp( -Math.pow(( x / scale ), shape ));
		},

		mean : function( scale, shape ) {
			return scale * j$.gammafn( 1 + 1 / shape );
		},

		median : function( scale, shape ) {
			return scale * Math.pow( Math.log( 2 ), 1 / shape );
		},

		mode : function( scale, shape ) {
			return ( shape > 1 ) ? scale * Math.pow(( shape - 1 ) / shape, 1 / shape ) : undefined;
		},

		variance : function( scale, shape ) {
			return scale * scale * j$.gammafn( 1 + 2 / shape ) - Math.pow( this.mean( scale, shape ), 2 );
		}
	},

	uniform : {
		pdf : function( x, a, b ) {
			return ( x < a || x > b ) ? 0 : 1 / ( b - a );
		},

		cdf : function( x, a, b ) {
			if ( x < a ) {
				return 0;
			} else if ( x < b ) {
				return ( x - a ) / ( b - a );
			};
			return 1;
		}
	},

	// uniform distribution in terms of mean and standard dev
	uniformmv : {
		pdf : function( x, m, s ) {
			var sqrtt = Math.sqrt( -3 );
			return ( -s * sqrtt <= x - m || x - m <= s * sqrtt )
				? 1 / ( 2 * s * sqrtt )
			: 0;
		},

		cdf : function( x, m, s ) {
			var sqrtt = Math.sqrt( -3 );
			return ( x - m < -s * sqrtt )
				? 0
			: ( x - m >= s * sqrtt )
				? 1
			: 0.5 * (( x - m ) / ( s * sqrtt ) + 1 );
		}
	},

	binomial : {
		pdf : function( k, n, p ) {
			return j$.combination( n, k ) * Math.pow( p, k ) * Math.pow( 1 - p, n - k );
		},

		cdf : function( x, n, p ) {
			var binomarr = [],
				k = 0,
				i = 0,
				sum = 0;
			if ( x < 0 ) {
				return 0;
			};
			if ( x < n ) {
				for ( ; k < n; k++ ) {
					binomarr[ k ] = j$.binomial( k, n, p );
				};
				for ( ; i <= x; i++ ) {
					sum += binomarr[ i ];
				};
				return sum;
			};
			return 1;
		}
	},

	negbin : {
		pdf : function( k, r, p ) {
			return k !== Math.floor( k )
				? false
			: k < 0
				? 0
			: j$.combination( k + r - 1, k ) * Math.pow( 1 - p, r ) * Math.pow( p, k );
		},

		cdf : function( x, r, p ) {
			var sum = 0,
				k = 0;
			if ( x < 0 ) return 0;
			for ( ; k <= x; k++ ) {
				sum += j$.negbin( k, r, p );
			};
			return sum;
		}
	},

	hypgeom : {
		pdf : function( k, N, m, n ) {
			return x !== Math.floor( x )
				? false
			: ( x < 0)
				? 0
			: j$.combination( m, k ) * j$.combination( N - m , n - k ) / j$.combination( N, n );
		},

		cdf : function( x, N, m, n ) {
			var sum = 0,
				k = 0;
			if ( x < 0 ) return 0;
			for ( ; k <= x; k++ ) {
				sum += j$.hypgeom( k, N, m, n );
			};
			return sum;
		}
	},

	poisson : {
		pdf : function( k, l ) {
			return Math.pow( l, k ) * Math.exp( -l ) / j$.factorial( k );
		},

		cdf : function( x, l ) {
			var sum = 0,
				k = 0;
			if ( x < 0 ) return 0;
			for ( ; k <= x; k++ ) {
				sum += j$.poisson( k, l );
			};
			return sum;
		}
	}
});

return jDist;
})( Math, jStat );
<commit_msg>Completed Cauchy distribution<commit_after>this.d$ = this.jDist = (function( Math, j$ ) {

var jDist = function() {
	// TODO: finish implemenation of jDist object
	};

j$.extend( jDist, {
	beta : {
		pdf : function( x, alpha, beta ) {
			return ( Math.pow( x, alpha - 1 ) * Math.pow( 1 - x, beta - 1 ) ) / j$.betafn( alpha, beta );
		},

		cdf : function( x, alpha, beta ) {
			return j$.incompleteBeta( x, alpha, beta );
		},

		mean : function( alpha, beta ) {
			return alpha / ( alpha + beta );
		},

		median : function( alpha, beta ) {
			// TODO: implement beta median
		},

		mode : function( alpha, beta ) {
			return ( alpha * beta ) / ( Math.pow( alpha + beta, 2 ) * ( alpha + beta + 1 ));
		},

		variance : function( alpha, beta ) {
			return ( alpha * beta ) / ( Math.pow( alpha + beta, 2 ) * ( alpha + beta + 1 ) );
		}
	},

	cauchy : {
		pdf : function( x, location, scale ) {
			return ( scale / ( Math.pow( x - location, 2 ) + Math.pow( scale, 2 ) ) ) / Math.PI;
		},

		cdf : function( x, location, scale ) {
			return Math.atan(( x - location) / scale ) / Math.PI + 0.5;
		},

		mean : function( location, scale ) {
			j$.xerror();
		},

		median: function( location, scale ) {
			return location;
		},

		mode : function( location, scale ) {
			return location;
		},

		variance : function( location, scale ) {
			j$.xerror();
		}
	},

	chisquare : {
		pdf : function( x, k ) {
			return (Math.pow( x, k / 2 - 1) * Math.exp( -x / 2 )) / ( Math.pow( 2, k / 2) * j$.gammafn( k / 2 ));
		},

		cdf : function( x, k ) {
			return j$.lgamma( x / 2, k / 2 ) / j$.gammafn( k / 2 );
		}
	},

	exponential : {
		pdf : function( x, rate ) {
			return x < 0 ? 0 : rate * Math.exp( -rate * x );
		},

		cdf : function( x, rate ) {
			return x < 0 ? 0 : 1 - Math.exp( -rate * x );
		},

		mean : function( rate ) {
			return 1 / rate;
		},

		median : function ( rate ) {
			return ( 1 / rate ) * Math.log(2);
		},

		mode : function( rate ) {
			return 0;
		},

		variance : function( rate ) {
			return Math.pow( rate, -2 );
		}
	},

	gamma : {
		pdf : function( x, shape, scale ) {
			return Math.pow( x, shape - 1 ) * ( Math.exp( -x / scale ) / ( j$.gammafn( shape ) * Math.pow( scale, shape ) ) );
		},

		cdf : function( x, shape, scale ) {
			return jlstat.gammap( x / scale, shape );
		},

		mean : function( shape, scale ) {
			return shape * scale;
		},

		mode : function( shape, scale ) {
			if( shape > 1 ) return ( k - 1 ) * scale;
			return undefined;
		},

		variance: function( shape, scale ) {
			return shape * scale * scale;
		}
	},

	lognormal : {
		pdf : function( x, mu, sigma ) {
			return ( 1 / ( x * sigma * Math.sqrt( 2 * Math.PI ) ) ) * Math.exp( -Math.pow( Math.log( x ) - mu, 2) / ( 2 * sigma*sigma ) );
		},

		cdf : function( x, mu, sigma ) {
			return 0.5 + ( 0.5 * j$.erf( ( Math.log( x ) - mu ) / Math.sqrt( 2 * sigma*sigma ) ) );
		},

		mean : function( mu, sigma ) {
			return Math.exp( mu + sigma*sigma / 2);
		},

		median : function( mu, sigma ) {
			return Math.exp(mu);
		},

		mode : function( mu, sigma ) {
			return Math.exp( mu - sigma*sigma );
		},

		variance : function( mu, sigma ) {
			return ( Math.exp( sigma*sigma ) - 1 ) * Math.exp( 2 * mu + sigma*sigma );
		}
	},

	normal : {
		pdf : function( x, mean, std ) {
			return ( 1 / ( Math.sqrt( 2 * Math.PI * std * std))) * Math.exp( -( Math.pow( x - mean, 2 ) / 2 * std * std ) );
		},

		cdf : function( x, mean, std ) {
			return 0.5 * ( 1 + j$.erf( ( x - mean ) / Math.sqrt( 2 * std * std ) ) );
		},

		mean : function( mean, std ) {
			return mean;
		},

		median : function( mean, std ) {
			return mean;
		},

		mode : function ( mean, std ) {
			return mean;
		},

		variance : function( mean, std ) {
			return std * std;
		}
	},

	weibull : {
		pdf : function( x, scale, shape ) {
			return x < 0 ? 0 : ( shape / scale ) * Math.pow(( x / scale ),( shape - 1 )) * Math.exp(-( Math.pow(( x / scale ), shape )));
		},

		cdf : function( x, scale, shape ) {
			return x < 0 ? 0 : 1 - Math.exp( -Math.pow(( x / scale ), shape ));
		},

		mean : function( scale, shape ) {
			return scale * j$.gammafn( 1 + 1 / shape );
		},

		median : function( scale, shape ) {
			return scale * Math.pow( Math.log( 2 ), 1 / shape );
		},

		mode : function( scale, shape ) {
			return ( shape > 1 ) ? scale * Math.pow(( shape - 1 ) / shape, 1 / shape ) : undefined;
		},

		variance : function( scale, shape ) {
			return scale * scale * j$.gammafn( 1 + 2 / shape ) - Math.pow( this.mean( scale, shape ), 2 );
		}
	},

	uniform : {
		pdf : function( x, a, b ) {
			return ( x < a || x > b ) ? 0 : 1 / ( b - a );
		},

		cdf : function( x, a, b ) {
			if ( x < a ) {
				return 0;
			} else if ( x < b ) {
				return ( x - a ) / ( b - a );
			};
			return 1;
		}
	},

	// uniform distribution in terms of mean and standard dev
	uniformmv : {
		pdf : function( x, m, s ) {
			var sqrtt = Math.sqrt( -3 );
			return ( -s * sqrtt <= x - m || x - m <= s * sqrtt )
				? 1 / ( 2 * s * sqrtt )
			: 0;
		},

		cdf : function( x, m, s ) {
			var sqrtt = Math.sqrt( -3 );
			return ( x - m < -s * sqrtt )
				? 0
			: ( x - m >= s * sqrtt )
				? 1
			: 0.5 * (( x - m ) / ( s * sqrtt ) + 1 );
		}
	},

	binomial : {
		pdf : function( k, n, p ) {
			return j$.combination( n, k ) * Math.pow( p, k ) * Math.pow( 1 - p, n - k );
		},

		cdf : function( x, n, p ) {
			var binomarr = [],
				k = 0,
				i = 0,
				sum = 0;
			if ( x < 0 ) {
				return 0;
			};
			if ( x < n ) {
				for ( ; k < n; k++ ) {
					binomarr[ k ] = j$.binomial( k, n, p );
				};
				for ( ; i <= x; i++ ) {
					sum += binomarr[ i ];
				};
				return sum;
			};
			return 1;
		}
	},

	negbin : {
		pdf : function( k, r, p ) {
			return k !== Math.floor( k )
				? false
			: k < 0
				? 0
			: j$.combination( k + r - 1, k ) * Math.pow( 1 - p, r ) * Math.pow( p, k );
		},

		cdf : function( x, r, p ) {
			var sum = 0,
				k = 0;
			if ( x < 0 ) return 0;
			for ( ; k <= x; k++ ) {
				sum += j$.negbin( k, r, p );
			};
			return sum;
		}
	},

	hypgeom : {
		pdf : function( k, N, m, n ) {
			return x !== Math.floor( x )
				? false
			: ( x < 0)
				? 0
			: j$.combination( m, k ) * j$.combination( N - m , n - k ) / j$.combination( N, n );
		},

		cdf : function( x, N, m, n ) {
			var sum = 0,
				k = 0;
			if ( x < 0 ) return 0;
			for ( ; k <= x; k++ ) {
				sum += j$.hypgeom( k, N, m, n );
			};
			return sum;
		}
	},

	poisson : {
		pdf : function( k, l ) {
			return Math.pow( l, k ) * Math.exp( -l ) / j$.factorial( k );
		},

		cdf : function( x, l ) {
			var sum = 0,
				k = 0;
			if ( x < 0 ) return 0;
			for ( ; k <= x; k++ ) {
				sum += j$.poisson( k, l );
			};
			return sum;
		}
	}
});

return jDist;
})( Math, jStat );
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE.txt file for terms.
 */

/*jslint nomen:true, node:true */

"use strict";

var core = require('./core'),
    libpath = require('path');

module.exports = {

    describe: {
        summary: 'Compile handlebars templates to yui modules',
        extensions: ['hb', 'handlebars', 'hbs'],
        partialDir: 'partials'
    },

    fileUpdated: function (evt, api) {

        var self = this,
            options = this.describe.options  || {},
            file = evt.file,
            source_path = file.fullPath,
            bundleName = file.bundleName,
            name,
            destination_path;

        // building the name of the module based on:
        // * bundle name, partial or template denomination, and filename
        name = [
            bundleName,
            core.isPartial(source_path, this.describe.partialDir) ? 'partial' : 'template',
            libpath.basename(file.relativePath, '.' + file.ext)
        ].join('-');
        // destination is not very relevant, just dropping the file in buildDirectory
        destination_path = name + '.js';

        return api.promise(function (fulfill, reject) {

            var compiled,
                partials;

            try {
                partials = core.partials(source_path);
                compiled = core.compile(source_path, options);
            } catch (e) {
                reject(e);
            }

            // trying to write the destination file which will fulfill or reject the initial promise
            api.writeFileInBundle(bundleName, destination_path,
                self._wrapAsYUI(bundleName, name, compiled, partials))
                .then(function () {
                    // provisioning the module to be used on the server side automatically
                    evt.bundle.useServerModules = evt.bundle.useServerModules || [];
                    evt.bundle.useServerModules.push(name);
                    // we are now ready to roll
                    fulfill();
                }, reject);

        });

    },

    _wrapAsYUI: function (bundleName, name, compiled, partials) {

        // base dependency
        var dependencies = ["handlebars-base"],
            partialPrefix = bundleName + '-partial-';

        // each partial should be provisioned thru another yui module
        // and the name of the partial should translate into a yui module
        // to become a dependency
        partials = partials || [];
        partials.forEach(function (name) {
            // adding prefix to each partial
            dependencies.push(partialPrefix + name);
        });

        return [
            'YUI.add("' + name + '",function(Y, NAME){',
            '   var fn = Y.Template.Handlebars.revive(' + compiled + '),',
            '       cache = Y.Template._cache = Y.Template._cache || {},',
            '       partials = {};',
            '',
            '   Y.Array.each(' + JSON.stringify(partials) + ', function (name) {',
            '       cache["' + partialPrefix + '" + name] && (partials[name] = cache["' + partialPrefix + '" + name]);',
            '   });',
            '',
            '   cache[NAME] = function (data) {',
            '       return fn(data, {',
            '           partials: partials',
            '       });',
            '   };',
            '}, "", {requires: ' + JSON.stringify(dependencies) + '});'
        ].join('\n');

    }

};<commit_msg>consolidating the plugin to work with express-yui new rules for templates and partials.<commit_after>/*
 * Copyright (c) 2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE.txt file for terms.
 */

/*jslint nomen:true, node:true */

"use strict";

var core = require('./core'),
    libpath = require('path');

module.exports = {

    describe: {
        summary: 'Compile handlebars templates to yui modules',
        extensions: ['hb', 'handlebars', 'hbs'],
        partialDir: 'partials'
    },

    fileUpdated: function (evt, api) {

        var self = this,
            options = this.describe.options  || {},
            file = evt.file,
            source_path = file.fullPath,
            bundleName = file.bundleName,
            treatItAsPartial = core.isPartial(source_path, this.describe.partialDir),
            templateName = libpath.basename(file.relativePath, '.' + file.ext),
            destination_path = (treatItAsPartial ? 'partial-' : 'template-') + templateName + '.js',
            moduleName = bundleName + (treatItAsPartial ? '-partials-' : '-templates-') + templateName;

        return api.promise(function (fulfill, reject) {

            var compiled,
                partials;

            try {
                partials = core.partials(source_path);
                compiled = core.compile(source_path, options);
            } catch (e) {
                reject(e);
            }

            // trying to write the destination file which will fulfill or reject the initial promise
            api.writeFileInBundle(bundleName, destination_path,
                self._wrapAsYUI(bundleName, templateName, moduleName, treatItAsPartial, compiled, partials))
                .then(function () {
                    // provisioning the module to be used on the server side automatically
                    evt.bundle.useServerModules = evt.bundle.useServerModules || [];
                    evt.bundle.useServerModules.push(moduleName);
                    // we are now ready to roll
                    fulfill();
                }, reject);

        });

    },

    _wrapAsYUI: function (bundleName, templateName, moduleName, isPartial, compiled, partials) {

        // base dependency
        var dependencies = ["handlebars-base"];

        // each partial should be provisioned thru another yui module
        // and the name of the partial should translate into a yui module
        // to become a dependency
        partials = partials || [];
        partials.forEach(function (name) {
            // adding prefix to each partial
            dependencies.push(bundleName + '-partials-' + name);
        });

        return [
            'YUI.add("' + moduleName + '",function(Y, NAME){',
            '   var fn = Y.Template.Handlebars.revive(' + compiled + '),',
            '       cache = Y.Template._cache = Y.Template._cache || {},',
            '       partials = {};',
            '',
            '   Y.Array.each(' + JSON.stringify(partials) + ', function (name) {',
            '       if (cache["' + bundleName + '/partials/' + '" + name]) {',
            '           partials[name] = cache["' + bundleName + '/partials/' + '" + name];',
            '       }',
            '   });',
            '',
            '   cache["' + bundleName + '/' + (isPartial ? 'partials/' : '') + templateName + '"] = function (data) {',
            '       return fn(data, {',
            '           partials: partials',
            '       });',
            '   };',
            '}, "", {requires: ' + JSON.stringify(dependencies) + '});'
        ].join('\n');

    }

};<|endoftext|>