<commit_before>var assert = require('assert')
var fs = require('fs')

var parser = require('../lib/parser.js')

describe('parser', function () {
  describe('parse', function () {
    it('should return a string', function () {
      assert.equal('string', typeof parser.parse(''))
    })
    it('should return false if there\'s invalid any javascript in the jsheets', function () {
      assert.ok(!parser.parse('asdf'))
    })
    it('should take jsheets and return css', function () {
      assert.equal('asdf', parser.parse('["a", "s", "d", "f"].forEach(function (value) { css(value) })'))
      assert.equal('div {\n  display: block;\n}\ntroll', parser.parse('div {\n  display: block;\n}\n  css(\'troll\')'))
      assert.equal('div {\n          display: block;\n        }\ntrolltrolltrolltrolltrolltrolltrolltrolltrolltroll\n        div { display: hidden; }', parser.parse('div {\n          display: block;\n        }\n        \n        for(var i = 10; i > 0; i--) {\n          css(\'troll\')\n        }\n\n        div { display: hidden; }'))
    })
    it('should return false if false is passed to it', function () {
      assert.equal(false, parser.parse(false))
    })

    it('should be able to set, use and reset variables', function () {
      var testString
      parser.parse('$.someString = \'someString\'')
      assert.equal('someString', parser.stateJcssVars['someString'])
      testString = parser.parse('$.someString = \'someOtherString\' \n div {display:$.someString}')
      assert.equal(' div {display:someOtherString}', testString)
      testString = parser.parse('\n div {display:$.someString}')
      assert.equal('\n div {display:someOtherString}', testString)
    })
  })

  describe('interpret', function () {
    it('should exec js if the first position is js', function () {
      assert.equal('asdf', parser.interpret(['js', '["a", "s", "d", "f"].forEach(function (value) { css(value) })']))
    })
    it('should return the passed string if the first position is css', function () {
      assert.equal('display: block', parser.interpret(['css', 'display: block']))
    })
  })

  describe('split', function () {
    var testJcss
    var testCss
    var parseReturn
    before(function () {
      testJcss = '\n        div {\n          display: block;\n        }\n\n        css(".class { display: none; }")\n      '
      testCss = {css:  '\n        div {\n          display: block;\n        }',
        js:'\n        css(".class { display: none; }")\n      '}
      parseReturn = parser.split(testJcss)
    })
    it('should return an array of three strings, the first is either js or css, the second is code and the third is the rest', function () {
      assert.equal('object', typeof parseReturn)
      assert.equal('string', typeof parseReturn[1])
      assert.equal('string', typeof parseReturn[0])
      assert.equal(3, parseReturn.length)
      assert.ok(parseReturn[0] == 'js' || parseReturn[0] == 'css')
    })
    it('should interpret all line endings before and after css as css', function () {
      assert.equal('\n', parseReturn[1][0])
      assert.equal('\n', parseReturn[1][parseReturn[1].length - 1])
      assert.equal('\n', parseReturn[1][parseReturn[1].length - 2])
    })
    it('should be able to handle only js or only css', function () {
      assert.equal('css("div{display:block;}")', parser.split('css("div{display:block;}")')[1])
      assert.equal('div{display:block;}', parser.split('div{display:block;}')[1])
    })
    it('should return false if the passed string is empty', function () {
      assert.equal(false, parser.split(''))
    })
    it('should mark css and js as such', function () {
      assert.equal('div {\n          display: block;\n        }\n',
        parser.split('div {\n          display: block;\n        }\n        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ')[1])
      assert.equal('        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ',
        parser.split('        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ')[1])
    })
    it('should return the rest as the third position and false if there is nothing left', function () {
      assert.equal('        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ',
        parser.split('div {\n          display: block;\n        }\n        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ')[2])
      assert.equal(false,
        parser.split('div {\n          display: block;\n        }')[2])
    })
    it('should know all css selectors', function () {
      var testCss = '{display: block;}'
      assert.equal('css', parser.split('*' + testCss)[0])
      assert.equal('css', parser.split('E' + testCss)[0])
      assert.equal('css', parser.split('E[foo]' + testCss)[0])
      assert.equal('css', parser.split('E[foo="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo~="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo^="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo$="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo*="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo|="en"]' + testCss)[0])
      assert.equal('css', parser.split('E:root' + testCss)[0])
      assert.equal('css', parser.split('E:nth-child(n)' + testCss)[0])
      assert.equal('css', parser.split('E:nth-last-child(n)' + testCss)[0])
      assert.equal('css', parser.split('E:nth-of-type(n)' + testCss)[0])
      assert.equal('css', parser.split('E:nth-last-of-type(n)' + testCss)[0])
      assert.equal('css', parser.split('E:first-child' + testCss)[0])
      assert.equal('css', parser.split('E:last-child' + testCss)[0])
      assert.equal('css', parser.split('E:first-of-type' + testCss)[0])
      assert.equal('css', parser.split('E:last-of-type' + testCss)[0])
      assert.equal('css', parser.split('E:only-child' + testCss)[0])
      assert.equal('css', parser.split('E:only-of-type' + testCss)[0])
      assert.equal('css', parser.split('E:empty' + testCss)[0])
      assert.equal('css', parser.split('E:link' + testCss)[0])
      assert.equal('css', parser.split('E:visited' + testCss)[0])
      assert.equal('css', parser.split('E:active' + testCss)[0])
      assert.equal('css', parser.split('E:hover' + testCss)[0])
      assert.equal('css', parser.split('E:focus' + testCss)[0])
      assert.equal('css', parser.split('E:target' + testCss)[0])
      assert.equal('css', parser.split('E:lang(fr)' + testCss)[0])
      assert.equal('css', parser.split('E:enabled' + testCss)[0])
      assert.equal('css', parser.split('E:disabled' + testCss)[0])
      assert.equal('css', parser.split('E:checked' + testCss)[0])
      assert.equal('css', parser.split('E::first-line' + testCss)[0])
      assert.equal('css', parser.split('E::first-letter' + testCss)[0])
      assert.equal('css', parser.split('E::before' + testCss)[0])
      assert.equal('css', parser.split('E::after' + testCss)[0])
      assert.equal('css', parser.split('E.warning' + testCss)[0])
      assert.equal('css', parser.split('E#myid' + testCss)[0])
      assert.equal('css', parser.split('E:not(s)' + testCss)[0])
      assert.equal('css', parser.split('E F' + testCss)[0])
      assert.equal('css', parser.split('E > F' + testCss)[0])
      assert.equal('css', parser.split('E + F' + testCss)[0])
      assert.equal('css', parser.split('E ~ F' + testCss)[0])
    })

    it('should recognize all js as not css', function () {
      assert.equal('js', parser.split('if(true) {return false}')[0])
      assert.equal('js', parser.split('if(x = y) return something')[0])
      assert.equal('js', parser.split('while(someFun()) {i++}')[0])
      assert.equal('js', parser.split('arr[0] = {i: y}')[0])
      assert.equal('js', parser.split('arr[\'d\'] = {i: y}')[0])
      assert.equal('js', parser.split('arr[\'d\']={i: y}')[0])
    })
  })

  describe('parseCssVars', function () {
    it('should take a string and return one', function () {
      assert.equal('string', typeof parser.parseCssVars(''))
    })
    it('should replace variables starting with `$.` with its values', function () {
      parser.stateJcssVars = { s: 'something' }
      assert.equal('something', parser.parseCssVars('$.s'))
    })
    it('should replace function calls starting with `$.` with its return values', function () {
      var someString = 'someString'
      parser.stateJcssVars = { f: function () { return someString } }
      assert.equal(someString, parser.parseCssVars('$.f()'))
    })
    it('should be able to handle arguments passed to functions', function () {
      parser.stateJcssVars = { add: function (n0, n1) { return n0 + n1 } }
      assert.equal(2, parser.parseCssVars('$.add(1,1)'))
    })
    it('should be able to pick out vars in the middle of css', function () {
      parser.stateJcssVars = { str: 'block' }
      assert.equal('div { display: block; }', parser.parseCssVars('div { display: $.str; }'))
    })
  })

  describe('splitAroundSubstring', function () {
    it('should take two strings as arguments', function () {
      assert.ok(parser.splitAroundSubstring(' 1', ' 1 '))
    })
    it('should return an array of two strings', function () {
      assert.equal('object', typeof parser.splitAroundSubstring(' 1', ' 1 '))
      assert.equal(2, parser.splitAroundSubstring(' 1', ' 1 ').length)
      assert.equal('string', typeof parser.splitAroundSubstring(' 1', ' 1 ')[0])
      assert.equal('string', typeof parser.splitAroundSubstring(' 1', ' 1 ')[1])
    })
    it('should return two substrings of the second', function () {
      var s1 = ' 1'
      var s2 = ' 1 '
      assert.ok(s2.indexOf(parser.splitAroundSubstring(s1, s2)[0]) > -1)
      assert.ok(s2.indexOf(parser.splitAroundSubstring(s1, s2)[1]) > -1)
    })
    it('should return everything before the passed substring as the first return value if there is anything', function () {
      assert.equal(' ', parser.splitAroundSubstring('1 ', ' 1 ')[0])
    })
    it('should return a string including the substring as the second return value if the substring isn\'t at the start of the string', function () {
      assert.equal('1 -', parser.splitAroundSubstring('1 ', ' 1 -')[1])
    })
  })

  describe('exec', function () {
    it('should return a string', function () {
      assert.equal('string', typeof parser.exec(''))
    })
    it('should return false if the string that is passed isn\'t valid JS.', function () {
      assert.equal(false, parser.exec('yourmum'))
    })
    it('should provide a function `css` to the JS beeing execute', function () {
      assert.equal('display: block', parser.exec('css("display: block")'))
    })
    it('should exec JS', function () {
      assert.equal('asdf', parser.exec('["a", "s", "d", "f"].forEach(function (value) { css(value) })'))
    })
  })

  describe('funcsToString', function () {
    it('should take an array of functions as an argument', function () {
      assert.ok(parser.funcsToString([function a () {}]))
    })
    it('should return a string', function () {
      assert.equal('string', typeof parser.funcsToString([function a () {}]))
    })
    it('should join the functions with newlines', function () {
      assert.ok(parser.funcsToString([function a () {}, function a () {}]).indexOf('\n') > -1)
    })
    it('should add a newline in to the beginning of the string', function () {
      assert.equal('\n', parser.funcsToString([function a () {}])[0])
    })
  })

  describe('include', function () {
    it('should read and parse a jsheets file', function () {
      var testFile = './testfile.jsheet'
      fs.writeFileSync(testFile, 'css(\'div{display: block}\')')
      assert.equal('div{display: block}', parser.include(testFile))
      fs.unlink(testFile)
    })
    it('should log an error and return an empty string if the jsheets is invalid or if the file doesn\'t exsist', function () {
      var testFile = './testfile.jsheet'
      assert.equal('', parser.include('asddgere.cevrscs'))
      fs.writeFileSync(testFile, 'css(\'div{display: block}\')yoomum')
      assert.equal('', parser.include(testFile))
      fs.unlink(testFile)
    })
  })

  describe('makeIncludes', function () {
    it('should replace calles to include in parsed jsheets files', function () {
      var testFile = './testfile.jsheet'
      fs.writeFileSync(testFile, 'css(\'div{display: block}\')')
      assert.equal('div{display: block}', parser.makeIncludes('include(\'' + testFile + '\')'))
      fs.unlink(testFile)
    })
  })
})<commit_msg>Add a few tests for media queries<commit_after>var assert = require('assert')
var fs = require('fs')

var parser = require('../lib/parser.js')

describe('parser', function () {
  describe('parse', function () {
    it('should return a string', function () {
      assert.equal('string', typeof parser.parse(''))
    })
    it('should return false if there\'s invalid any javascript in the jsheets', function () {
      assert.ok(!parser.parse('asdf'))
    })
    it('should take jsheets and return css', function () {
      assert.equal('asdf', parser.parse('["a", "s", "d", "f"].forEach(function (value) { css(value) })'))
      assert.equal('div {\n  display: block;\n}\ntroll', parser.parse('div {\n  display: block;\n}\n  css(\'troll\')'))
      assert.equal('div {\n          display: block;\n        }\ntrolltrolltrolltrolltrolltrolltrolltrolltrolltroll\n        div { display: hidden; }', parser.parse('div {\n          display: block;\n        }\n        \n        for(var i = 10; i > 0; i--) {\n          css(\'troll\')\n        }\n\n        div { display: hidden; }'))
    })
    it('should return false if false is passed to it', function () {
      assert.equal(false, parser.parse(false))
    })

    it('should be able to set, use and reset variables', function () {
      var testString
      parser.parse('$.someString = \'someString\'')
      assert.equal('someString', parser.stateJcssVars['someString'])
      testString = parser.parse('$.someString = \'someOtherString\' \n div {display:$.someString}')
      assert.equal(' div {display:someOtherString}', testString)
      testString = parser.parse('\n div {display:$.someString}')
      assert.equal('\n div {display:someOtherString}', testString)
    })
  })

  describe('interpret', function () {
    it('should exec js if the first position is js', function () {
      assert.equal('asdf', parser.interpret(['js', '["a", "s", "d", "f"].forEach(function (value) { css(value) })']))
    })
    it('should return the passed string if the first position is css', function () {
      assert.equal('display: block', parser.interpret(['css', 'display: block']))
    })
  })

  describe('split', function () {
    var testJcss
    var testCss
    var parseReturn
    before(function () {
      testJcss = '\n        div {\n          display: block;\n        }\n\n        css(".class { display: none; }")\n      '
      testCss = {css:  '\n        div {\n          display: block;\n        }',
        js:'\n        css(".class { display: none; }")\n      '}
      parseReturn = parser.split(testJcss)
    })
    it('should return an array of three strings, the first is either js or css, the second is code and the third is the rest', function () {
      assert.equal('object', typeof parseReturn)
      assert.equal('string', typeof parseReturn[1])
      assert.equal('string', typeof parseReturn[0])
      assert.equal(3, parseReturn.length)
      assert.ok(parseReturn[0] == 'js' || parseReturn[0] == 'css')
    })
    it('should interpret all line endings before and after css as css', function () {
      assert.equal('\n', parseReturn[1][0])
      assert.equal('\n', parseReturn[1][parseReturn[1].length - 1])
      assert.equal('\n', parseReturn[1][parseReturn[1].length - 2])
    })
    it('should be able to handle only js or only css', function () {
      assert.equal('css("div{display:block;}")', parser.split('css("div{display:block;}")')[1])
      assert.equal('div{display:block;}', parser.split('div{display:block;}')[1])
    })
    it('should return false if the passed string is empty', function () {
      assert.equal(false, parser.split(''))
    })
    it('should mark css and js as such', function () {
      assert.equal('div {\n          display: block;\n        }\n',
        parser.split('div {\n          display: block;\n        }\n        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ')[1])
      assert.equal('        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ',
        parser.split('        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ')[1])
    })
    it('should return the rest as the third position and false if there is nothing left', function () {
      assert.equal('        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ',
        parser.split('div {\n          display: block;\n        }\n        \n        for(var i = 10; i < 0; i--) {\n          css(\'troll\')\n        }\n        ')[2])
      assert.equal(false,
        parser.split('div {\n          display: block;\n        }')[2])
    })
    it('should know all css selectors', function () {
      var testCss = '{display: block;}'
      assert.equal('css', parser.split('*' + testCss)[0])
      assert.equal('css', parser.split('E' + testCss)[0])
      assert.equal('css', parser.split('E[foo]' + testCss)[0])
      assert.equal('css', parser.split('E[foo="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo~="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo^="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo$="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo*="bar"]' + testCss)[0])
      assert.equal('css', parser.split('E[foo|="en"]' + testCss)[0])
      assert.equal('css', parser.split('E:root' + testCss)[0])
      assert.equal('css', parser.split('E:nth-child(n)' + testCss)[0])
      assert.equal('css', parser.split('E:nth-last-child(n)' + testCss)[0])
      assert.equal('css', parser.split('E:nth-of-type(n)' + testCss)[0])
      assert.equal('css', parser.split('E:nth-last-of-type(n)' + testCss)[0])
      assert.equal('css', parser.split('E:first-child' + testCss)[0])
      assert.equal('css', parser.split('E:last-child' + testCss)[0])
      assert.equal('css', parser.split('E:first-of-type' + testCss)[0])
      assert.equal('css', parser.split('E:last-of-type' + testCss)[0])
      assert.equal('css', parser.split('E:only-child' + testCss)[0])
      assert.equal('css', parser.split('E:only-of-type' + testCss)[0])
      assert.equal('css', parser.split('E:empty' + testCss)[0])
      assert.equal('css', parser.split('E:link' + testCss)[0])
      assert.equal('css', parser.split('E:visited' + testCss)[0])
      assert.equal('css', parser.split('E:active' + testCss)[0])
      assert.equal('css', parser.split('E:hover' + testCss)[0])
      assert.equal('css', parser.split('E:focus' + testCss)[0])
      assert.equal('css', parser.split('E:target' + testCss)[0])
      assert.equal('css', parser.split('E:lang(fr)' + testCss)[0])
      assert.equal('css', parser.split('E:enabled' + testCss)[0])
      assert.equal('css', parser.split('E:disabled' + testCss)[0])
      assert.equal('css', parser.split('E:checked' + testCss)[0])
      assert.equal('css', parser.split('E::first-line' + testCss)[0])
      assert.equal('css', parser.split('E::first-letter' + testCss)[0])
      assert.equal('css', parser.split('E::before' + testCss)[0])
      assert.equal('css', parser.split('E::after' + testCss)[0])
      assert.equal('css', parser.split('E.warning' + testCss)[0])
      assert.equal('css', parser.split('E#myid' + testCss)[0])
      assert.equal('css', parser.split('E:not(s)' + testCss)[0])
      assert.equal('css', parser.split('E F' + testCss)[0])
      assert.equal('css', parser.split('E > F' + testCss)[0])
      assert.equal('css', parser.split('E + F' + testCss)[0])
      assert.equal('css', parser.split('E ~ F' + testCss)[0])
    })

    it('should be able to recognize mediaqueries as such', function () {assert.equal('css', parser.split('@media all and (min-width:500px) { … }')[0])
        assert.equal('css', parser.split('@media (min-width:500px) { … }')[0])
        assert.equal('css', parser.split('@media (orientation: portrait) { … }')[0])
        assert.equal('css', parser.split('@media all and (orientation: portrait) { … }')[0])
        assert.equal('css', parser.split('@media screen and (color), projection and (color) { … }')[0])
        assert.equal('css', parser.split('@media all and (min-color: 2) { … }')[0])
        assert.equal('css', parser.split('@media all { … }')[0])
        assert.equal('css', parser.split('@media { … }')[0])
    })

    it('should recognize all js as not css', function () {
      assert.equal('js', parser.split('if(true) {return false}')[0])
      assert.equal('js', parser.split('if(x = y) return something')[0])
      assert.equal('js', parser.split('while(someFun()) {i++}')[0])
      assert.equal('js', parser.split('arr[0] = {i: y}')[0])
      assert.equal('js', parser.split('arr[\'d\'] = {i: y}')[0])
      assert.equal('js', parser.split('arr[\'d\']={i: y}')[0])
    })
  })

  describe('parseCssVars', function () {
    it('should take a string and return one', function () {
      assert.equal('string', typeof parser.parseCssVars(''))
    })
    it('should replace variables starting with `$.` with its values', function () {
      parser.stateJcssVars = { s: 'something' }
      assert.equal('something', parser.parseCssVars('$.s'))
    })
    it('should replace function calls starting with `$.` with its return values', function () {
      var someString = 'someString'
      parser.stateJcssVars = { f: function () { return someString } }
      assert.equal(someString, parser.parseCssVars('$.f()'))
    })
    it('should be able to handle arguments passed to functions', function () {
      parser.stateJcssVars = { add: function (n0, n1) { return n0 + n1 } }
      assert.equal(2, parser.parseCssVars('$.add(1,1)'))
    })
    it('should be able to pick out vars in the middle of css', function () {
      parser.stateJcssVars = { str: 'block' }
      assert.equal('div { display: block; }', parser.parseCssVars('div { display: $.str; }'))
    })
  })

  describe('splitAroundSubstring', function () {
    it('should take two strings as arguments', function () {
      assert.ok(parser.splitAroundSubstring(' 1', ' 1 '))
    })
    it('should return an array of two strings', function () {
      assert.equal('object', typeof parser.splitAroundSubstring(' 1', ' 1 '))
      assert.equal(2, parser.splitAroundSubstring(' 1', ' 1 ').length)
      assert.equal('string', typeof parser.splitAroundSubstring(' 1', ' 1 ')[0])
      assert.equal('string', typeof parser.splitAroundSubstring(' 1', ' 1 ')[1])
    })
    it('should return two substrings of the second', function () {
      var s1 = ' 1'
      var s2 = ' 1 '
      assert.ok(s2.indexOf(parser.splitAroundSubstring(s1, s2)[0]) > -1)
      assert.ok(s2.indexOf(parser.splitAroundSubstring(s1, s2)[1]) > -1)
    })
    it('should return everything before the passed substring as the first return value if there is anything', function () {
      assert.equal(' ', parser.splitAroundSubstring('1 ', ' 1 ')[0])
    })
    it('should return a string including the substring as the second return value if the substring isn\'t at the start of the string', function () {
      assert.equal('1 -', parser.splitAroundSubstring('1 ', ' 1 -')[1])
    })
  })

  describe('exec', function () {
    it('should return a string', function () {
      assert.equal('string', typeof parser.exec(''))
    })
    it('should return false if the string that is passed isn\'t valid JS.', function () {
      assert.equal(false, parser.exec('yourmum'))
    })
    it('should provide a function `css` to the JS beeing execute', function () {
      assert.equal('display: block', parser.exec('css("display: block")'))
    })
    it('should exec JS', function () {
      assert.equal('asdf', parser.exec('["a", "s", "d", "f"].forEach(function (value) { css(value) })'))
    })
  })

  describe('funcsToString', function () {
    it('should take an array of functions as an argument', function () {
      assert.ok(parser.funcsToString([function a () {}]))
    })
    it('should return a string', function () {
      assert.equal('string', typeof parser.funcsToString([function a () {}]))
    })
    it('should join the functions with newlines', function () {
      assert.ok(parser.funcsToString([function a () {}, function a () {}]).indexOf('\n') > -1)
    })
    it('should add a newline in to the beginning of the string', function () {
      assert.equal('\n', parser.funcsToString([function a () {}])[0])
    })
  })

  describe('include', function () {
    it('should read and parse a jsheets file', function () {
      var testFile = './testfile.jsheet'
      fs.writeFileSync(testFile, 'css(\'div{display: block}\')')
      assert.equal('div{display: block}', parser.include(testFile))
      fs.unlink(testFile)
    })
    it('should log an error and return an empty string if the jsheets is invalid or if the file doesn\'t exsist', function () {
      var testFile = './testfile.jsheet'
      assert.equal('', parser.include('asddgere.cevrscs'))
      fs.writeFileSync(testFile, 'css(\'div{display: block}\')yoomum')
      assert.equal('', parser.include(testFile))
      fs.unlink(testFile)
    })
  })

  describe('makeIncludes', function () {
    it('should replace calles to include in parsed jsheets files', function () {
      var testFile = './testfile.jsheet'
      fs.writeFileSync(testFile, 'css(\'div{display: block}\')')
      assert.equal('div{display: block}', parser.makeIncludes('include(\'' + testFile + '\')'))
      fs.unlink(testFile)
    })
  })
})<|endoftext|>


<commit_before>var gulp = require('gulp');
var exec = require('child_process').exec;
var minimist = require('minimist');
var semver = require('semver');
var fs = require('fs');

// Default version data. Should be replaced as soon as the get-version task runs.
var version = {
    "Major": 0,
    "Minor": 0,
    "Patch": 1,
    "MajorMinorPatch": "0.0.1",
};

var args = minimist(process.argv);

gulp.task('get-version', function (callback) {
    if (args.overrideversion && semver.valid(args.overrideversion)) {
        console.log("Using override to get version numbers.");
        version.MajorMinorPatch = args.overrideversion;
        version.Major = semver.major(args.overrideversion);
        version.Minor = semver.minor(args.overrideversion);
        version.Patch = semver.patch(args.overrideversion);
        callback();
    } else if (process.env.GITVERSION_MajorMinorPatch) {
        console.log("Environment variables to get version numbers.");
        version.MajorMinorPatch = process.env.GITVERSION_MajorMinorPatch;
        version.Major = semver.major(process.env.GITVERSION_MajorMinorPatch);
        version.Minor = semver.minor(process.env.GITVERSION_MajorMinorPatch);
        version.Patch = semver.patch(process.env.GITVERSION_MajorMinorPatch);
        callback();
    } else {
        console.log("Running GitVersion to get version numbers.");
        exec('gitversion', function(err, stdout, stderr) {
            version = JSON.parse(stdout);
            callback(err);
        });
    }
});

function stampTaskJson(path) {
    var taskDefinitionContents = fs.readFileSync(path, 'utf8');
	var taskDefinition = JSON.parse(taskDefinitionContents);

	taskDefinition.version = {
        "Major": version.Major,
        "Minor": version.Minor,
        "Patch": version.Patch
    };

	taskDefinitionContents = JSON.stringify(taskDefinition, null, '\t');
	fs.writeFileSync(path, taskDefinitionContents);
}

gulp.task('stamp-manifest', ['get-version'], function (callback) {
    var manifestContents = fs.readFileSync('src\\vss-extension.json', 'utf8');
	var manifest = JSON.parse(manifestContents);

	manifest.version = version.MajorMinorPatch;

	manifestContents = JSON.stringify(manifest, null, '\t');
	fs.writeFileSync('src\\vss-extension.json', manifestContents);

    callback();
});

gulp.task('stamp-export-solution-task', ['get-version'], function (callback) {
    stampTaskJson('src\\tasks\\vsts-mscrm-export-solution\\task.json');
    callback();
});

gulp.task('stamp-import-solution-task', ['get-version'], function (callback) {
    stampTaskJson('src\\tasks\\vsts-mscrm-import-solution\\task.json');
    callback();
});

gulp.task('stamp-pack-solution-task', ['get-version'], function (callback) {
    stampTaskJson('src\\tasks\\vsts-mscrm-pack-solution\\task.json');
    callback();
});

gulp.task('stamp-unpack-solution-task', ['get-version'], function (callback) {
    stampTaskJson('src\\tasks\\vsts-mscrm-unpack-solution\\task.json');
    callback();
});

gulp.task('stamp', ['stamp-manifest', 'stamp-export-solution-task', 'stamp-import-solution-task', 'stamp-pack-solution-task', 'stamp-unpack-solution-task'], function(callback) {
    callback();
});

gulp.task('pack', ['stamp'], function (callback) {
    exec('node_modules\\.bin\\tfx.cmd extension create --root src', function (err, stdout, stderr) {
        if (err) {
            console.log(stderr);
            callback(err);
        } else {
            console.log(stdout);
            callback();
        }
    });
});

gulp.task('default', ['pack']);<commit_msg>Added code to publish extension.<commit_after>var gulp = require('gulp');
var exec = require('child_process').exec;
var minimist = require('minimist');
var semver = require('semver');
var fs = require('fs');
var glob = require('glob');

// Default version data. Should be replaced as soon as the get-version task runs.
var version = {
    "Major": 0,
    "Minor": 0,
    "Patch": 1,
    "MajorMinorPatch": "0.0.1",
};

var args = minimist(process.argv);

gulp.task('get-version', function (callback) {
    if (args.overrideversion && semver.valid(args.overrideversion)) {
        console.log("Using override to get version numbers.");
        version.MajorMinorPatch = args.overrideversion;
        version.Major = semver.major(args.overrideversion);
        version.Minor = semver.minor(args.overrideversion);
        version.Patch = semver.patch(args.overrideversion);
        callback();
    } else if (process.env.GITVERSION_MajorMinorPatch) {
        console.log("Environment variables to get version numbers.");
        version.MajorMinorPatch = process.env.GITVERSION_MajorMinorPatch;
        version.Major = semver.major(process.env.GITVERSION_MajorMinorPatch);
        version.Minor = semver.minor(process.env.GITVERSION_MajorMinorPatch);
        version.Patch = semver.patch(process.env.GITVERSION_MajorMinorPatch);
        callback();
    } else {
        console.log("Running GitVersion to get version numbers.");
        exec('gitversion', function(err, stdout, stderr) {
            version = JSON.parse(stdout);
            callback(err);
        });
    }
});

function stampTaskJson(path) {
    var taskDefinitionContents = fs.readFileSync(path, 'utf8');
	var taskDefinition = JSON.parse(taskDefinitionContents);

	taskDefinition.version = {
        "Major": version.Major,
        "Minor": version.Minor,
        "Patch": version.Patch
    };

	taskDefinitionContents = JSON.stringify(taskDefinition, null, '\t');
	fs.writeFileSync(path, taskDefinitionContents);
}

gulp.task('stamp-manifest', ['get-version'], function (callback) {
    var manifestContents = fs.readFileSync('src\\vss-extension.json', 'utf8');
	var manifest = JSON.parse(manifestContents);

	manifest.version = version.MajorMinorPatch;

	manifestContents = JSON.stringify(manifest, null, '\t');
	fs.writeFileSync('src\\vss-extension.json', manifestContents);

    callback();
});

gulp.task('stamp-export-solution-task', ['get-version'], function (callback) {
    stampTaskJson('src\\tasks\\vsts-mscrm-export-solution\\task.json');
    callback();
});

gulp.task('stamp-import-solution-task', ['get-version'], function (callback) {
    stampTaskJson('src\\tasks\\vsts-mscrm-import-solution\\task.json');
    callback();
});

gulp.task('stamp-pack-solution-task', ['get-version'], function (callback) {
    stampTaskJson('src\\tasks\\vsts-mscrm-pack-solution\\task.json');
    callback();
});

gulp.task('stamp-unpack-solution-task', ['get-version'], function (callback) {
    stampTaskJson('src\\tasks\\vsts-mscrm-unpack-solution\\task.json');
    callback();
});

gulp.task('stamp', ['stamp-manifest', 'stamp-export-solution-task', 'stamp-import-solution-task', 'stamp-pack-solution-task', 'stamp-unpack-solution-task'], function(callback) {
    callback();
});

gulp.task('pack', ['stamp'], function (callback) {
    exec('node_modules\\.bin\\tfx.cmd extension create --root src', function (err, stdout, stderr) {
        if (err) {
            console.log(stderr);
            callback(err);
        } else {
            console.log(stdout);
            callback();
        }
    });
});

gulp.task('publish', function (callback) {
    glob('**/*.vsix', function (err, files) {
        var vsix = files[0];
        var token = args.token;
        exec('node_modules\\.bin\\tfx.cmd extension publish --vsix ' + vsix + ' --token ' + token, function (err, stdout, stderr) {
            if (err) {
                console.log(stderr);
                callback(err);
            } else {
                console.log(stdout);
                callback();
            }
        });
    });
});

gulp.task('default', ['pack']);<|endoftext|>


<commit_before>// This file is part of Indico.
// Copyright (C) 2002 - 2019 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.

/* eslint-disable import/no-commonjs, import/unambiguous, import/newline-after-import */
/* global module:false */

const path = require('path');
const process = require('process');
const glob = require('glob');
const merge = require('webpack-merge');
const _ = require('lodash');

const config = require(path.join(process.env.INDICO_PLUGIN_ROOT, 'webpack-build-config'));
const bundles = require(path.join(process.env.INDICO_PLUGIN_ROOT, 'webpack-bundles'));
const base = require(path.join(config.build.indicoSourcePath, 'webpack'));

const entry = bundles.entry || {};
const allThemeFiles = [];

if (!_.isEmpty(config.themes)) {
  const themeFiles = base.getThemeEntryPoints(config, './themes/');
  Object.assign(entry, themeFiles);
  allThemeFiles.push(...Object.values(themeFiles).reduce((acc, current) => acc.concat(current)));
}

function generateModuleAliases() {
  return glob.sync(path.join(config.indico.build.rootPath, 'modules/**/module.json')).map(file => {
    const mod = {produceBundle: true, partials: {}, ...require(file)};
    const dirName = path.join(path.dirname(file), 'client/js');
    const modulePath = path.join('indico/modules', mod.parent || '', mod.name);
    return {
      name: modulePath,
      alias: dirName,
      onlyModule: false,
    };
  });
}

module.exports = env => {
  return merge.strategy({
    'resolve.alias': 'prepend',
  })(base.webpackDefaults(env, config, bundles), {
    entry,
    externals: {
      jquery: 'jQuery',
    },
    module: {
      rules: [
        {
          test: /.*\.(jpe?g|png|gif|svg|woff2?|ttf|eot)$/,
          use: {
            loader: 'file-loader',
          },
        },
      ],
    },
    resolve: {
      alias: generateModuleAliases(),
    },
    output: {
      jsonpFunction: 'pluginJsonp',
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
          common: module => {
            return {
              name: 'common',
              chunks: 'initial',
              // exclude themes, like we do in the core webpack config
              minChunks: allThemeFiles.includes(module.resource) ? 9999 : 2,
            };
          },
        },
      },
    },
  });
};
<commit_msg>Fix common chunk logic for plugins<commit_after>// This file is part of Indico.
// Copyright (C) 2002 - 2019 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.

/* eslint-disable import/no-commonjs, import/unambiguous, import/newline-after-import */
/* global module:false */

const path = require('path');
const process = require('process');
const glob = require('glob');
const merge = require('webpack-merge');
const _ = require('lodash');

const config = require(path.join(process.env.INDICO_PLUGIN_ROOT, 'webpack-build-config'));
const bundles = require(path.join(process.env.INDICO_PLUGIN_ROOT, 'webpack-bundles'));
const base = require(path.join(config.build.indicoSourcePath, 'webpack'));

const entry = bundles.entry || {};

if (!_.isEmpty(config.themes)) {
  const themeFiles = base.getThemeEntryPoints(config, './themes/');
  Object.assign(entry, themeFiles);
}

function generateModuleAliases() {
  return glob.sync(path.join(config.indico.build.rootPath, 'modules/**/module.json')).map(file => {
    const mod = {produceBundle: true, partials: {}, ...require(file)};
    const dirName = path.join(path.dirname(file), 'client/js');
    const modulePath = path.join('indico/modules', mod.parent || '', mod.name);
    return {
      name: modulePath,
      alias: dirName,
      onlyModule: false,
    };
  });
}

module.exports = env => {
  return merge.strategy({
    'resolve.alias': 'prepend',
  })(base.webpackDefaults(env, config, bundles), {
    entry,
    externals: {
      jquery: 'jQuery',
    },
    module: {
      rules: [
        {
          test: /.*\.(jpe?g|png|gif|svg|woff2?|ttf|eot)$/,
          use: {
            loader: 'file-loader',
          },
        },
      ],
    },
    resolve: {
      alias: generateModuleAliases(),
    },
    output: {
      jsonpFunction: 'pluginJsonp',
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
          common: {
            name: 'common',
            // exclude themes/print css from common chunk
            chunks: chunk => chunk.canBeInitial() && !/\.print$|^themes_/.test(chunk.name),
            minChunks: 2,
          },
        },
      },
    },
  });
};
<|endoftext|>


<commit_before>
var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync').create(),
    ngrok = require('ngrok'),
    Karma = require('karma').Server,
    isDev = false,
    SERVER_PORT = process.env.PORT || 7100,
    ngrokTunnel;

function webdriverCfg() {
  const service = (process.env.SELENIUM_SERVICE || '').toLowerCase();
  if (service === 'browserstack') {
    return {
      baseUrl: ngrokTunnel,
      host: 'hub-cloud.browserstack.com',
      port: 80,
      services: ['browserstack'],
      user: process.env.WDIO_USER,
      key: process.env.WDIO_KEY,
    };
  } else if (service === 'saucelabs') {
    return {
      baseUrl: ngrokTunnel,
      host: 'ondemand.saucelabs.com',
      port: 80,
      services: ['sauce'],
      user: process.env.WDIO_USER,
      key: process.env.WDIO_KEY,
    };
  }
  // seleinum server must be running on localhost
  return {
    baseUrl: `localhost:${ SERVER_PORT }`,
  };
}

function webpackCfg(overrides) {
  return Object.assign({
    quiet: true,
    module: {
      loaders: [{
        test: /\.jsx?$/i,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }]
    }
  }, overrides);
}

function noop() {}

function server(opts, cb) {
  const initOpts = Object.assign({
    server: {
      baseDir: "./tmp",
      routes: {
          "/node_modules": "node_modules",
      }
    },
    port: SERVER_PORT,
  }, opts);
  $.util.log('Starting server and proxy');
  browserSync.init(initOpts, function () {
    $.util.log('Server started');
    (cb || noop)();
  });
}

gulp.task('proxy', function (done) {
  $.util.log('Starting proxy');
  ngrok.connect({
    proto: 'http',
    addr: SERVER_PORT,
  }, function (err, url) {
    if (err) {
      $.util.log($.util.colors.red(`Failed to start proxy\n${ err }`));
    } else {
      ngrokTunnel = url;
      $.util.log(`Proxy available at: ${ url }`);
      done();
    }
  })
});

gulp.task('dist', function() {
  return gulp.src('src/index.js')
  .pipe($.webpack(webpackCfg({
    output: {
      library: 'i18n',
      libraryTarget: 'umd',
    }
  })))
  .pipe($.rename('react-i18n.js'))
  .pipe(gulp.dest('./dist'))
  .pipe($.uglify())
  .pipe($.rename('react-i18n.min.js'))
  .pipe(gulp.dest('./dist'));
});

gulp.task('build', function() {
  return gulp.src([
    'src/**/*.js',
    'src/**/*.jsx',
  ])
  .pipe($.babel())
  .pipe(gulp.dest('lib'));
});

gulp.task('examples:dist', function() {
  return gulp.src('./examples/index.jsx')
  .pipe($.webpack(webpackCfg({
    output: {
      library: 'i18n',
      libraryTarget: 'umd',
    }
  })))
  .pipe($.rename('index.js'))
  .pipe(gulp.dest('./tmp'));
});

gulp.task('examples:copy', function() {
  return gulp.src([
    'examples/*.html',
    'examples/**/*.lang.json',
  ])
  .pipe(gulp.dest('tmp'));
});

gulp.task('examples', ['examples:dist', 'examples:copy']);

gulp.task('dev', [ 'examples' ], function() {
  isDev = true;
  server({});

  gulp.watch([
    "src/*.js",
    "examples/*.jsx"
  ], [
    'examples'
  ]).on("change", function () {
    $.util.log('Rebuilt examples');
    browserSync.reload();
  });
});

gulp.task('test:unit', ['dist'], function (done) {
  new Karma({
    configFile: __dirname + '/conf/karma.conf.js',
  }, function () {
    done();
  }).start();
});

gulp.task('test:e2e:server', function (done) {
  $.util.log('Starting server');
  server({
    open: false,
  }, function () {
    $.util.log(`Server available on: localhost:${ SERVER_PORT }`);
    done();
  });
});

gulp.task('test:e2e', ['proxy', 'test:e2e:server'], function() {
  $.util.log('Running test:e2e');
  var error = false;
  return gulp
    .src('conf/wdio.js')
    .pipe($.webdriver(webdriverCfg()))
    .on('error', function (error) {
      $.util.log($.util.colors.red(`Error (${ error.plugin }):\n${ error.message }\n`));
      error = true;
      this.emit('end');
    })
    .on('end', function (error) {
      $.util.log('Killing ngrok', ngrokTunnel);
      ngrok.disconnect(ngrokTunnel);
      ngrok.kill();
      $.util.log('Killing browserSync');
      browserSync.exit();
      setTimeout(function () {
        process.exit(error ? 1 : 0);
      }, 5000);
    });
});

gulp.task('lint', () => {
  return gulp.src([
      'src/**/*.js',
      'src/**/*.jsx',
      '!node_modules/**',
    ])
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});

gulp.task('postpublish', function () {
  return gulp
    .src('./package.json')
    .pipe($.tagVersion())
    .pipe($.gitPush({
      repository: 'origin',
      refspec: 'HEAD'
    }));
});

gulp.task('default', ['build', 'examples', 'test:unit', 'test:e2e']);
<commit_msg>fix the gulp dev task<commit_after>
var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync').create(),
    ngrok = require('ngrok'),
    Karma = require('karma').Server,
    isDev = false,
    SERVER_PORT = process.env.PORT || 7100,
    ngrokTunnel;

function webdriverCfg() {
  const service = (process.env.SELENIUM_SERVICE || '').toLowerCase();
  if (service === 'browserstack') {
    return {
      baseUrl: ngrokTunnel,
      host: 'hub-cloud.browserstack.com',
      port: 80,
      services: ['browserstack'],
      user: process.env.WDIO_USER,
      key: process.env.WDIO_KEY,
    };
  } else if (service === 'saucelabs') {
    return {
      baseUrl: ngrokTunnel,
      host: 'ondemand.saucelabs.com',
      port: 80,
      services: ['sauce'],
      user: process.env.WDIO_USER,
      key: process.env.WDIO_KEY,
    };
  }
  // seleinum server must be running on localhost
  return {
    baseUrl: `localhost:${ SERVER_PORT }`,
  };
}

function webpackCfg(overrides) {
  return Object.assign({
    quiet: true,
    module: {
      loaders: [{
        test: /\.jsx?$/i,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }]
    }
  }, overrides);
}

function noop() {}

function server(opts, cb) {
  const initOpts = Object.assign({
    server: {
      baseDir: "./tmp",
      routes: {
          "/node_modules": "node_modules",
      }
    },
    port: SERVER_PORT,
  }, opts);
  $.util.log('Starting server and proxy');
  browserSync.init(initOpts, function () {
    $.util.log('Server started');
    (cb || noop)();
  });
}

gulp.task('proxy', function (done) {
  $.util.log('Starting proxy');
  ngrok.connect({
    proto: 'http',
    addr: SERVER_PORT,
  }, function (err, url) {
    if (err) {
      $.util.log($.util.colors.red(`Failed to start proxy\n${ err }`));
    } else {
      ngrokTunnel = url;
      $.util.log(`Proxy available at: ${ url }`);
      done();
    }
  })
});

gulp.task('dist', function() {
  return gulp.src('src/index.js')
  .pipe($.webpack(webpackCfg({
    output: {
      library: 'i18n',
      libraryTarget: 'umd',
    }
  })))
  .pipe($.rename('react-i18n.js'))
  .pipe(gulp.dest('./dist'))
  .pipe($.uglify())
  .pipe($.rename('react-i18n.min.js'))
  .pipe(gulp.dest('./dist'));
});

gulp.task('build', function() {
  return gulp.src([
    'src/**/*.js',
    'src/**/*.jsx',
  ])
  .pipe($.babel())
  .pipe(gulp.dest('lib'));
});

gulp.task('examples:dist', function() {
  return gulp.src('./examples/index.jsx')
  .pipe($.webpack(webpackCfg({
    output: {
      library: 'i18n',
      libraryTarget: 'umd',
    }
  })))
  .pipe($.rename('index.js'))
  .pipe(gulp.dest('./tmp'));
});

gulp.task('examples:copy', function() {
  return gulp.src([
    'examples/*.html',
    'examples/**/*.lang.json',
  ])
  .pipe(gulp.dest('tmp'));
});

gulp.task('examples', ['examples:dist', 'examples:copy']);

const devTasks = [ 'build', 'dist', 'examples' ];
gulp.task('dev', devTasks, function() {
  isDev = true;
  server({});

  gulp.watch([
    "src/*.js",
    "examples/*.jsx",
    "examples/*.html",
  ], devTasks).on("change", function () {
    $.util.log('Rebuilt examples');
    browserSync.reload();
  });
});

gulp.task('test:unit', ['dist'], function (done) {
  new Karma({
    configFile: __dirname + '/conf/karma.conf.js',
  }, function () {
    done();
  }).start();
});

gulp.task('test:e2e:server', function (done) {
  $.util.log('Starting server');
  server({
    open: false,
  }, function () {
    $.util.log(`Server available on: localhost:${ SERVER_PORT }`);
    done();
  });
});

gulp.task('test:e2e', ['proxy', 'test:e2e:server'], function() {
  $.util.log('Running test:e2e');
  var error = false;
  return gulp
    .src('conf/wdio.js')
    .pipe($.webdriver(webdriverCfg()))
    .on('error', function (error) {
      $.util.log($.util.colors.red(`Error (${ error.plugin }):\n${ error.message }\n`));
      error = true;
      this.emit('end');
    })
    .on('end', function (error) {
      $.util.log('Killing ngrok', ngrokTunnel);
      ngrok.disconnect(ngrokTunnel);
      ngrok.kill();
      $.util.log('Killing browserSync');
      browserSync.exit();
      setTimeout(function () {
        process.exit(error ? 1 : 0);
      }, 5000);
    });
});

gulp.task('lint', () => {
  return gulp.src([
      'src/**/*.js',
      'src/**/*.jsx',
      '!node_modules/**',
    ])
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});

gulp.task('postpublish', function () {
  return gulp
    .src('./package.json')
    .pipe($.tagVersion())
    .pipe($.gitPush({
      repository: 'origin',
      refspec: 'HEAD'
    }));
});

gulp.task('default', ['build', 'examples', 'test:unit', 'test:e2e']);
<|endoftext|>


<commit_before>'use strict';

var blogophonMustacheQuoters = {
  icsQuote: function() {
    return function(text, render) {
      var newText = render(text)
        .replace(/(\n|\r|\r\n)/g, "\\n")
        .replace(/(,|;)/g, '\\$1');
      if (newText.length > 30) {
        newText = newText.match(/[\s\S]{1,72}/g).join("\r\n ");
        newText = "\r\n "+newText;
      }
      return newText;
    };
  },
  ymlQuote: function() {
    return function(text, render) {
      text = render(text);
      console.log(text);
      if (text.match(/:\s/)) {
        text = "'" + text.replace(/(')/g, '\\$1') + "'";
      }
      return text;
    };
  },
  noLineBreak: function() {
    return function(text, render) {
      return render(text).replace(/\s*[\n|\r]+/g, ' ');
    };
  },
  nl2br: function() {
    return function(text, render) {
      return render(text).replace(/[\n|\r]+/g, '
$0');
    };
  },
  encodeURIComponent: function() {
    return function(text, render) {
      return encodeURIComponent(render(text));
    };
  }
};

module.exports = blogophonMustacheQuoters;
<commit_msg>Multiline YAML parser added, fixed broken YAML generation<commit_after>'use strict';

var blogophonMustacheQuoters = {
  icsQuote: function() {
    return function(text, render) {
      var newText = render(text)
        .replace(/(\n|\r|\r\n)/g, "\\n")
        .replace(/(,|;)/g, '\\$1');
      if (newText.length > 30) {
        newText = newText.match(/[\s\S]{1,72}/g).join("\r\n ");
        newText = "\r\n "+newText;
      }
      return newText;
    };
  },
  ymlQuote: function() {
    return function(text, render) {
      text = render(text);
      console.log(text);
      if (text.match(/:\s/)) {
        text = "'" + text.replace(/(')/g, '\\$1') + "'";
      } else if (text.match(/#/)) {
        text = text.replace(/(#)/g, '\\$1');
      }
      return text;
    };
  },
  noLineBreak: function() {
    return function(text, render) {
      return render(text).replace(/\s*[\n|\r]+/g, ' ');
    };
  },
  nl2br: function() {
    return function(text, render) {
      return render(text).replace(/[\n|\r]+/g, '
$0');
    };
  },
  encodeURIComponent: function() {
    return function(text, render) {
      return encodeURIComponent(render(text));
    };
  }
};

module.exports = blogophonMustacheQuoters;
<|endoftext|>


<commit_before>
var util = require('util'),
    stream = require('stream'),
    IndexError = require('./IndexError');

var BufferedBulkStream = function( client, options )
{
  this.client = client;
  this.buffer = [];
  this.flooding = false;
  this.options = { buffer: 500, timeout: 1000, throttle: 20 }
  this.stats = { written: 0, inserted: 0, ok: 0, error: 0, active_requests: 0, retries: 0 }
  this.timeout = null;

  // merge injected options
  if( 'object' == typeof options ){
    for( var prop in options ) {
      this.options[ prop ] = options[ prop ];
    }
  }

  // Call constructor from stream.Writable
  stream.Writable.call( this, { objectMode: true } );

  // Log errors to stderr
  this.on( 'failure', console.error.bind( console ) );

  // Try to flush when the stream ends
  this.on( 'end', this.flush.bind( this, true ) );
  this.on( 'close', this.flush.bind( this, true ) );

  // resume function (for flood control)
  this.resumeFunction = function(){};

  // allow the client to exit cleanly when complete
  this.on( 'finish', function(){
    var interval;
    this.resumeFunction = function(){}; // disable calls to next();

    var release = function(){
      clearInterval( interval );
      if( !this.buffer.length && !this.stats.active_requests ){
        this.client.close(); // close the underlying client
        this.emit( 'release' );
      } else {
        interval = setInterval( release, 1000 );
        this.flush( true );
      }
    }.bind( this );

    release();
  });
}

// Inherit prototype from stream.Writable
util.inherits( BufferedBulkStream, stream.Writable )

// Backoff on the 'throttle' with failures, scale up with successes.
BufferedBulkStream.prototype.batch = function( hasFailures ){
  if( hasFailures ){
    this.options.throttle -= 2;
    if( this.options.throttle < 20 ) this.options.throttle = 20;
  }
  else if( Math.random() > 0.9 ){
    this.options.throttle++;
  }
}

// Handle new messages on the stream
BufferedBulkStream.prototype._write = function( chunk, enc, next )
{
  // BufferedBulkStream accepts Objects or JSON encoded strings
  var record = this.parseChunk( chunk );

  // Record message error stats
  this.stats[ record? 'ok':'error' ]++;

  if( record )
  {
    // Push command to buffer
    this.buffer.push({ index: {
      _index: record._index,
      _type: record._type,
      _id: record._id
    }}, record.data );

    this.flush();
  }

  // Handle partial flushes due to inactivity
  clearTimeout( this.timeout );
  this.timeout = setTimeout( function(){
    this.flush( true );
  }.bind(this), this.options.timeout );

  this.resumeFunction = next;
  if( !this.flooding ) next();
};

// Flush buffer to client
BufferedBulkStream.prototype.flush = function( force )
{
  // Buffer not full
  if( this.buffer.length < 2 ){ return; } // Prevent 'Failed to derive xcontent from org.elasticsearch.common.bytes.BytesArray@0'
  if( !force && ( this.buffer.length / 2 ) < this.options.buffer ){ return; }

  // Move commands out of main buffer
  var writeBuffer = this.buffer.splice( 0, this.options.buffer * 2 );
  writeBufferTotal = ( writeBuffer.length / 2 );

  // Write buffer to client
  this.stats.written += writeBufferTotal;
  this.stats.active_requests++;

  // flood control backoff
  if( this.stats.active_requests >= this.options.throttle ){
    this.flooding = true;
  }

  this.client.bulk( { body: writeBuffer }, function( err, resp ){

    this.stats.active_requests--;

    // major error
    // @todo: retry whole batch?
    if( err ){
      this.stats.error += writeBufferTotal;
       return this.emit( 'failure', new IndexError( err || 'bulk index error', null, resp ));
    }

    // response does not contain items
    // @todo: retry whole batch?
    if( !resp || !resp.items ){
      this.stats.error += writeBufferTotal; // consider them as failed
      return this.emit( 'failure', new IndexError( 'invalid resp from es bulk index operation', null, resp ));
    }

    // process response
    this.validateBulkResponse( writeBuffer, resp );

    // flood control resume
    if( this.stats.active_requests < this.options.throttle && this.flooding ){
      this.flooding = false;
      if( 'function' == typeof this.resumeFunction ) this.resumeFunction();
    }

    // Stats
    this.emitStats();

  }.bind(this));

  // Stats
  this.emitStats();
}

BufferedBulkStream.prototype.validateBulkResponse = function( writeBuffer, resp ){

  // create a map of response codes -> query positions
  var responseCodes = resp.items.reduce( function( codes, item, i ){
    if( !codes[ item.index.status ] ){ codes[ item.index.status ] = []; }
    codes[ item.index.status ].push( i );
    return codes;
  }, {});

  this.batch( responseCodes.hasOwnProperty('503') );

  // iterate over ES responses for each item in bulk request
  for( var code in responseCodes ){

    // Successfully updated index
    if( code == '200' ){
      this.stats.inserted += responseCodes['200'].length;
    }

    // Successfully created index
    else if( code == '201' ){
      this.stats.inserted += responseCodes['201'].length;
    }

    // Retry-able failure
    else if( code == '503' ){
      responseCodes['503'].forEach( function( i ){
        var startIndex = i * 2;
        // Push back in to buffer to try again
        this.buffer.push(
          writeBuffer.slice( startIndex +0, startIndex +1 )[0],
          writeBuffer.slice( startIndex +1, startIndex +2 )[0]
        );
        this.stats.retries++;
      }, this);
    }

    // Elasticsearch returned an error
    else if( code == '400' ){
      this.stats.error += responseCodes['400'].length;

      // Format error info and emit
      responseCodes['400'].forEach( function( i ){
        this.emit( 'failure', new IndexError(
          resp.items[ i ].index.error,
          writeBuffer.slice( (i*2)+1, (i*2)+2 )[0],
          resp.items[ i ]
        ));
      }, this);
    }

    // Unknown response code
    else {
      this.stats.error += responseCodes[code].length;

      // Format error info and emit
      responseCodes[code].forEach( function( i ){
        this.emit( 'failure', new IndexError(
          'unknown response code',
          writeBuffer.slice( (i*2)+1, (i*2)+2 )[0],
          resp.items[ i ]
        ));
      }, this);
    }

  }
}

// Stats
BufferedBulkStream.prototype.emitStats = function()
{
  this.emit( 'stats', {
    written: this.stats.written - this.stats.retries,
    indexed: this.stats.inserted,
    errored: this.stats.error,
    retries: this.stats.retries,
    active_requests: this.stats.active_requests,
    queued: this.stats.written - this.stats.inserted - this.stats.error - this.stats.retries
  });
}

// BufferedBulkStream accepts Objects or JSON encoded strings
BufferedBulkStream.prototype.parseChunk = function( chunk )
{
  if( 'string' === typeof chunk ){
    try {
      chunk = JSON.parse( chunk.toString() );
    } catch( e ){
      this.emit( 'failure', 'failed to parse JSON chunk' );
      return;
    }
  }

  if( 'object' === typeof chunk ){
    if( !chunk._index ){
      this.emit( 'failure', 'invalid index specified' );
      return;
    } else if( !chunk._type ){
      this.emit( 'failure', 'invalid type specified' );
      return;
    } else if( !chunk._id ){
      this.emit( 'failure', 'invalid id specified' );
      return;
    }

    // Chunk is valid
    return chunk;
  }

  this.emit( 'failure', 'invalid bulk API message' );
  return;
}

module.exports = BufferedBulkStream;<commit_msg>modify default throttle value<commit_after>
var util = require('util'),
    stream = require('stream'),
    IndexError = require('./IndexError');

var BufferedBulkStream = function( client, options )
{
  this.client = client;
  this.buffer = [];
  this.flooding = false;
  this.options = { buffer: 500, timeout: 1000, throttle: 5 }
  this.currentThrottle = this.options.throttle;
  this.stats = { written: 0, inserted: 0, ok: 0, error: 0, active_requests: 0, retries: 0 }
  this.timeout = null;

  // merge injected options
  if( 'object' == typeof options ){
    for( var prop in options ) {
      this.options[ prop ] = options[ prop ];
    }
  }

  // Call constructor from stream.Writable
  stream.Writable.call( this, { objectMode: true } );

  // Log errors to stderr
  this.on( 'failure', console.error.bind( console ) );

  // Try to flush when the stream ends
  this.on( 'end', this.flush.bind( this, true ) );
  this.on( 'close', this.flush.bind( this, true ) );

  // resume function (for flood control)
  this.resumeFunction = function(){};

  // allow the client to exit cleanly when complete
  this.on( 'finish', function(){
    var interval;
    this.resumeFunction = function(){}; // disable calls to next();

    var release = function(){
      clearInterval( interval );
      if( !this.buffer.length && !this.stats.active_requests ){
        this.client.close(); // close the underlying client
        this.emit( 'release' );
      } else {
        interval = setInterval( release, 1000 );
        this.flush( true );
      }
    }.bind( this );

    release();
  });
}

// Inherit prototype from stream.Writable
util.inherits( BufferedBulkStream, stream.Writable )

// Backoff on the 'throttle' with failures, scale up with successes.
BufferedBulkStream.prototype.batch = function( hasFailures ){
  if( hasFailures ){
    this.currentThrottle -= 2;
    if( this.currentThrottle < this.options.throttle ){
      this.currentThrottle = this.options.throttle;
    }
  }
  else if( Math.random() > 0.9 ){
    this.currentThrottle++;
  }
}

// Handle new messages on the stream
BufferedBulkStream.prototype._write = function( chunk, enc, next )
{
  // BufferedBulkStream accepts Objects or JSON encoded strings
  var record = this.parseChunk( chunk );

  // Record message error stats
  this.stats[ record? 'ok':'error' ]++;

  if( record )
  {
    // Push command to buffer
    this.buffer.push({ index: {
      _index: record._index,
      _type: record._type,
      _id: record._id
    }}, record.data );

    this.flush();
  }

  // Handle partial flushes due to inactivity
  clearTimeout( this.timeout );
  this.timeout = setTimeout( function(){
    this.flush( true );
  }.bind(this), this.options.timeout );

  this.resumeFunction = next;
  if( !this.flooding ) next();
};

// Flush buffer to client
BufferedBulkStream.prototype.flush = function( force )
{
  // Buffer not full
  if( this.buffer.length < 2 ){ return; } // Prevent 'Failed to derive xcontent from org.elasticsearch.common.bytes.BytesArray@0'
  if( !force && ( this.buffer.length / 2 ) < this.options.buffer ){ return; }

  // Move commands out of main buffer
  var writeBuffer = this.buffer.splice( 0, this.options.buffer * 2 );
  writeBufferTotal = ( writeBuffer.length / 2 );

  // Write buffer to client
  this.stats.written += writeBufferTotal;
  this.stats.active_requests++;

  // flood control backoff
  if( this.stats.active_requests >= this.currentThrottle ){
    this.flooding = true;
  }

  this.client.bulk( { body: writeBuffer }, function( err, resp ){

    this.stats.active_requests--;

    // major error
    // @todo: retry whole batch?
    if( err ){
      this.stats.error += writeBufferTotal;
       return this.emit( 'failure', new IndexError( err || 'bulk index error', null, resp ));
    }

    // response does not contain items
    // @todo: retry whole batch?
    if( !resp || !resp.items ){
      this.stats.error += writeBufferTotal; // consider them as failed
      return this.emit( 'failure', new IndexError( 'invalid resp from es bulk index operation', null, resp ));
    }

    // process response
    this.validateBulkResponse( writeBuffer, resp );

    // flood control resume
    if( this.stats.active_requests < this.currentThrottle && this.flooding ){
      this.flooding = false;
      if( 'function' == typeof this.resumeFunction ) this.resumeFunction();
    }

    // Stats
    this.emitStats();

  }.bind(this));

  // Stats
  this.emitStats();
}

BufferedBulkStream.prototype.validateBulkResponse = function( writeBuffer, resp ){

  // create a map of response codes -> query positions
  var responseCodes = resp.items.reduce( function( codes, item, i ){
    if( !codes[ item.index.status ] ){ codes[ item.index.status ] = []; }
    codes[ item.index.status ].push( i );
    return codes;
  }, {});

  this.batch( responseCodes.hasOwnProperty('503') );

  // iterate over ES responses for each item in bulk request
  for( var code in responseCodes ){

    // Successfully updated index
    if( code == '200' ){
      this.stats.inserted += responseCodes['200'].length;
    }

    // Successfully created index
    else if( code == '201' ){
      this.stats.inserted += responseCodes['201'].length;
    }

    // Retry-able failure
    else if( code == '503' ){
      responseCodes['503'].forEach( function( i ){
        var startIndex = i * 2;
        // Push back in to buffer to try again
        this.buffer.push(
          writeBuffer.slice( startIndex +0, startIndex +1 )[0],
          writeBuffer.slice( startIndex +1, startIndex +2 )[0]
        );
        this.stats.retries++;
      }, this);
    }

    // Elasticsearch returned an error
    else if( code == '400' ){
      this.stats.error += responseCodes['400'].length;

      // Format error info and emit
      responseCodes['400'].forEach( function( i ){
        this.emit( 'failure', new IndexError(
          resp.items[ i ].index.error,
          writeBuffer.slice( (i*2)+1, (i*2)+2 )[0],
          resp.items[ i ]
        ));
      }, this);
    }

    // Unknown response code
    else {
      this.stats.error += responseCodes[code].length;

      // Format error info and emit
      responseCodes[code].forEach( function( i ){
        this.emit( 'failure', new IndexError(
          'unknown response code',
          writeBuffer.slice( (i*2)+1, (i*2)+2 )[0],
          resp.items[ i ]
        ));
      }, this);
    }

  }
}

// Stats
BufferedBulkStream.prototype.emitStats = function()
{
  this.emit( 'stats', {
    written: this.stats.written - this.stats.retries,
    indexed: this.stats.inserted,
    errored: this.stats.error,
    retries: this.stats.retries,
    active_requests: this.stats.active_requests,
    queued: this.stats.written - this.stats.inserted - this.stats.error - this.stats.retries
  });
}

// BufferedBulkStream accepts Objects or JSON encoded strings
BufferedBulkStream.prototype.parseChunk = function( chunk )
{
  if( 'string' === typeof chunk ){
    try {
      chunk = JSON.parse( chunk.toString() );
    } catch( e ){
      this.emit( 'failure', 'failed to parse JSON chunk' );
      return;
    }
  }

  if( 'object' === typeof chunk ){
    if( !chunk._index ){
      this.emit( 'failure', 'invalid index specified' );
      return;
    } else if( !chunk._type ){
      this.emit( 'failure', 'invalid type specified' );
      return;
    } else if( !chunk._id ){
      this.emit( 'failure', 'invalid id specified' );
      return;
    }

    // Chunk is valid
    return chunk;
  }

  this.emit( 'failure', 'invalid bulk API message' );
  return;
}

module.exports = BufferedBulkStream;<|endoftext|>


<commit_before>'use strict';
var scene, camera, renderer;

var CONSTANTS = Object.freeze({
 INNER_RADIUS: 200,
 OUTER_RADIUS: 300,
 BLOCK_HEIGHT: 50,
 SEGMENT_COUNT: 12,
 LINE_HEIGHT: 50
});

var MATERIALS = Object.freeze({
  RED: new THREE.MeshPhongMaterial({
    color: 0xcc0015,
    emissive: 0x402030,
    side: THREE.DoubleSide,
    shading: THREE.FlatShading
  }),
  BLUE: new THREE.MeshPhongMaterial({
    color: 0x156289,
    emissive: 0x072534,
    side: THREE.DoubleSide,
    shading: THREE.FlatShading
  }),
  GREEN: new THREE.MeshPhongMaterial({
    color: 0x158950,
    emissive: 0x078820,
    side: THREE.DoubleSide,
    shading: THREE.FlatShading
  })
});

var model = {
  blocks: [ // A 2D matrix of CONSTANTS.SEGMENT_COUNT long rows
    [
      undefined,
      undefined,
      {
        material: MATERIALS.RED
      },
      {
        material: MATERIALS.BLUE
      },
      undefined,
      {
        material: MATERIALS.BLUE
      }
    ],
    [
      undefined,
      undefined,
      {
        material: MATERIALS.GREEN
      }
    ]
  ]
};

var sliceAngle = Math.PI*2 / CONSTANTS.SEGMENT_COUNT;

//TODO: describe geometry
// 8 points total, 4-4 on outer and inner rectangular face
function constructSliceGeometry(lineIndex, segmentIndex) {
  var points = [];

  var angle1 = sliceAngle * segmentIndex;
  var angle2 = sliceAngle * (segmentIndex + 1);

  var x0_outer = Math.cos(angle1) * CONSTANTS.OUTER_RADIUS;
  var y0_outer = Math.sin(angle1) * CONSTANTS.OUTER_RADIUS;

  var x1_outer = Math.cos(angle2) * CONSTANTS.OUTER_RADIUS;
  var y1_outer = Math.sin(angle2) * CONSTANTS.OUTER_RADIUS;

  var x0_inner = Math.cos(angle1) * CONSTANTS.INNER_RADIUS;
  var y0_inner = Math.sin(angle1) * CONSTANTS.INNER_RADIUS;

  var x1_inner = Math.cos(angle2) * CONSTANTS.INNER_RADIUS;
  var y1_inner = Math.sin(angle2) * CONSTANTS.INNER_RADIUS;

  var z0 = lineIndex*CONSTANTS.LINE_HEIGHT;
  var z1 = (lineIndex+1)*CONSTANTS.LINE_HEIGHT;

  points.push( new THREE.Vector3(x0_outer, y0_outer, z0) );
  points.push( new THREE.Vector3(x1_outer, y1_outer, z0) );
  points.push( new THREE.Vector3(x0_inner, y0_inner, z0) );
  points.push( new THREE.Vector3(x1_inner, y1_inner, z0) );

  points.push( new THREE.Vector3(x0_outer, y0_outer, z1) );
  points.push( new THREE.Vector3(x1_outer, y1_outer, z1) );
  points.push( new THREE.Vector3(x0_inner, y0_inner, z1) );
  points.push( new THREE.Vector3(x1_inner, y1_inner, z1) );

  return new THREE.ConvexGeometry(points);
}

function init() {
  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 1000;

  for(var rowIndex = 0; rowIndex < model.blocks.length; rowIndex++){
    for(var colIndex = 0; colIndex < model.blocks[rowIndex].length; colIndex++){
      var block = model.blocks[rowIndex][colIndex];
      if (block) {
        var geometry = constructSliceGeometry(rowIndex, colIndex);
        var mesh = new THREE.Mesh( geometry, block.material );
        mesh.position.set( 0, 0, 0 );
        scene.add( mesh );
      }
    }
  }

  var lights = [];
  lights[ 0 ] = new THREE.PointLight( 0xffffff );
  lights[ 1 ] = new THREE.PointLight( 0xffffff );
  lights[ 2 ] = new THREE.PointLight( 0xffffff );

  lights[ 0 ].position.set( 0, 500, 0 );
  lights[ 1 ].position.set( 200, 500, 200 );
  lights[ 2 ].position.set( -200, -500, -200 );

  scene.add( lights[ 0 ] );
  scene.add( lights[ 1 ] );
  scene.add( lights[ 2 ] );

  // X red, Y green, Z blue
  scene.add( new THREE.AxisHelper( 150 ) );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );

  var orbit = new THREE.OrbitControls( camera, renderer.domElement );
	orbit.enableZoom = false;

  document.getElementById('main-renderer-target').appendChild( renderer.domElement );
}

function animate() {
  requestAnimationFrame( animate );

  scene.rotation.z += 0.001;

  renderer.render( scene, camera );
}

init();
animate();<commit_msg>add board rotation<commit_after>'use strict';
var scene, camera, renderer;

var CONSTANTS = Object.freeze({
 INNER_RADIUS: 200,
 OUTER_RADIUS: 300,
 BLOCK_HEIGHT: 50,
 SEGMENT_COUNT: 12,
 LINE_HEIGHT: 50
});

var MATERIALS = Object.freeze({
  RED: new THREE.MeshPhongMaterial({
    color: 0xcc0015,
    emissive: 0x402030,
    side: THREE.DoubleSide,
    shading: THREE.FlatShading
  }),
  BLUE: new THREE.MeshPhongMaterial({
    color: 0x156289,
    emissive: 0x072534,
    side: THREE.DoubleSide,
    shading: THREE.FlatShading
  }),
  GREEN: new THREE.MeshPhongMaterial({
    color: 0x158950,
    emissive: 0x078820,
    side: THREE.DoubleSide,
    shading: THREE.FlatShading
  })
});

var model = {
  blocks: [ // A 2D matrix of CONSTANTS.SEGMENT_COUNT long rows
    [
      undefined,
      undefined,
      {
        material: MATERIALS.RED
      },
      {
        material: MATERIALS.BLUE
      },
      undefined,
      {
        material: MATERIALS.BLUE
      }
    ],
    [
      undefined,
      undefined,
      {
        material: MATERIALS.GREEN
      }
    ]
  ]
};

document.onkeypress = function(event) {
  switch (event.code) {
    case 'KeyW':
      console.warn('ROTATE not implemented');
      break;
    case 'KeyA':
      rotateBoard('left');
      break;
    case 'KeyS':
      console.warn('DROP not implemented');
      break;
    case 'KeyD':
      rotateBoard('right');
      break;
  }
};

var sliceAngle = Math.PI*2 / CONSTANTS.SEGMENT_COUNT;

function rotateBoard(direction) {
  switch (direction) {
    case 'left':
      scene.rotation.z += sliceAngle;
      break;
    case 'right':
      scene.rotation.z -= sliceAngle;
      break;
    default:
      console.error('unknown direction ',direction);
  }
}
//TODO: describe geometry
// 8 points total, 4-4 on outer and inner rectangular face
function constructSliceGeometry(lineIndex, segmentIndex) {
  var points = [];

  var angle1 = sliceAngle * segmentIndex;
  var angle2 = sliceAngle * (segmentIndex + 1);

  var x0_outer = Math.cos(angle1) * CONSTANTS.OUTER_RADIUS;
  var y0_outer = Math.sin(angle1) * CONSTANTS.OUTER_RADIUS;

  var x1_outer = Math.cos(angle2) * CONSTANTS.OUTER_RADIUS;
  var y1_outer = Math.sin(angle2) * CONSTANTS.OUTER_RADIUS;

  var x0_inner = Math.cos(angle1) * CONSTANTS.INNER_RADIUS;
  var y0_inner = Math.sin(angle1) * CONSTANTS.INNER_RADIUS;

  var x1_inner = Math.cos(angle2) * CONSTANTS.INNER_RADIUS;
  var y1_inner = Math.sin(angle2) * CONSTANTS.INNER_RADIUS;

  var z0 = lineIndex*CONSTANTS.LINE_HEIGHT;
  var z1 = (lineIndex+1)*CONSTANTS.LINE_HEIGHT;

  points.push( new THREE.Vector3(x0_outer, y0_outer, z0) );
  points.push( new THREE.Vector3(x1_outer, y1_outer, z0) );
  points.push( new THREE.Vector3(x0_inner, y0_inner, z0) );
  points.push( new THREE.Vector3(x1_inner, y1_inner, z0) );

  points.push( new THREE.Vector3(x0_outer, y0_outer, z1) );
  points.push( new THREE.Vector3(x1_outer, y1_outer, z1) );
  points.push( new THREE.Vector3(x0_inner, y0_inner, z1) );
  points.push( new THREE.Vector3(x1_inner, y1_inner, z1) );

  return new THREE.ConvexGeometry(points);
}

function init() {
  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 1000;

  for(var rowIndex = 0; rowIndex < model.blocks.length; rowIndex++){
    for(var colIndex = 0; colIndex < model.blocks[rowIndex].length; colIndex++){
      var block = model.blocks[rowIndex][colIndex];
      if (block) {
        var geometry = constructSliceGeometry(rowIndex, colIndex);
        var mesh = new THREE.Mesh( geometry, block.material );
        mesh.position.set( 0, 0, 0 );
        scene.add( mesh );
      }
    }
  }

  var lights = [];
  lights[ 0 ] = new THREE.PointLight( 0xffffff );
  lights[ 1 ] = new THREE.PointLight( 0xffffff );
  lights[ 2 ] = new THREE.PointLight( 0xffffff );

  lights[ 0 ].position.set( 0, 500, 0 );
  lights[ 1 ].position.set( 200, 500, 200 );
  lights[ 2 ].position.set( -200, -500, -200 );

  scene.add( lights[ 0 ] );
  scene.add( lights[ 1 ] );
  scene.add( lights[ 2 ] );

  // X red, Y green, Z blue
  scene.add( new THREE.AxisHelper( 150 ) );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );

  var orbit = new THREE.OrbitControls( camera, renderer.domElement );
	orbit.enableZoom = false;

  document.getElementById('main-renderer-target').appendChild( renderer.domElement );
}

function animate() {
  requestAnimationFrame( animate );

  scene.rotation.z += 0.001;

  renderer.render( scene, camera );
}

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


<commit_before>/// Modules
const defaultsDeep = require('lodash.defaultsdeep');
///
/// Predefined Types
const ST_NONE = 0, ST_RESTRICTED = 1, ST_MINIMAL = 2, ST_UNRESTRICTED = 3;
///

// Build a restricted require
function restrictedRequire(allow) {
    return function(name) {
        if ((name) && (typeof name === 'string') && (allow.indexOf(name) !== -1)) {
            return require(name);
        }
    };
}

// Warning: Try to avoid setting context using permissions as much as possible
// Providing a unique context with the required globals to a task is a much better
// option that keeps the calls clean and improves performance of tasks
module.exports = function ST__CREATE_CONTEXT_P(context, type) {
    if (type === ST_NONE) return context;
    switch(type) {
        case ST_RESTRICTED:
            // Allow stream module
            context.require = restrictedRequire(['stream']);
            return defaultsDeep(context, {
                setTimeout: global.setTimeout,
                setInterval: global.setInterval,
                setImmediate: global.setImmediate,
                clearTimeout: global.clearTimeout,
                clearInterval: global.clearInterval,
                Buffer: Buffer
            });
        case ST_MINIMAL:
            // Allow some core modules
            context.require = restrictedRequire(['http', 'https', 'util', 'os', 'path', 'events', 'stream', 'string_decoder', 'url', 'zlib']);
            return defaultsDeep(context, {
                setTimeout: global.setTimeout,
                setInterval: global.setInterval,
                setImmediate: global.setImmediate,
                clearTimeout: global.clearTimeout,
                clearInterval: global.clearInterval,
                Buffer: Buffer,
                __dirname: __dirname,
                __filename: __filename,
                console: console
            });
        case ST_UNRESTRICTED:
            // Allow all core modules & most globals
            return defaultsDeep(context, {
                setTimeout: global.setTimeout,
                setInterval: global.setInterval,
                setImmediate: global.setImmediate,
                clearTimeout: global.clearTimeout,
                clearInterval: global.clearInterval,
                Buffer: Buffer,
                __dirname: __dirname,
                __filename: __filename,
                process: global.process,
                require: global.require,
                console: console
            });
        default:
            return context;
    }
};<commit_msg>Significantly improved performance by flattening contexts<commit_after>/// Modules
const defaultsDeep = require('lodash.defaultsdeep');
///
/// Predefined Types
const ST_NONE = 0, ST_RESTRICTED = 1, ST_MINIMAL = 2, ST_UNRESTRICTED = 3;
///

// Build a restricted require
function restrictedRequire(allow) {
    return function(name) {
        if ((name) && (typeof name === 'string') && (allow.indexOf(name) !== -1)) {
            return require(name);
        }
    };
}

// Warning: Try to avoid setting context using permissions as much as possible
// Providing a unique context with the required globals to a task is a much better
// option that keeps the calls clean and improves performance of tasks
module.exports = function ST__CREATE_CONTEXT_P(context, type) {
    if (type === ST_NONE) return context;
    switch(type) {
        case ST_RESTRICTED:
            // Allow stream module
            if(!context.require) context.require = restrictedRequire(['stream']);
            if(!context.setTimeout) context.setTimeout = global.setTimeout;
            if(!context.setInterval) context.setInterval = global.setInterval;
            if(!context.setImmediate) context.setImmediate = global.setImmediate;
            if(!context.clearTimeout) context.clearTimeout = global.clearTimeout;
            if(!context.clearInterval) context.clearInterval = global.clearInterval;
            if(!context.Buffer) context.Buffer = Buffer;
            return context;
        case ST_MINIMAL:
            // Allow some core modules
            if(!context.require) context.require = restrictedRequire(['http', 'https', 'util', 'os', 'path', 'events', 'stream', 'string_decoder', 'url', 'zlib']);
            if(!context.setTimeout) context.setTimeout = global.setTimeout;
            if(!context.setInterval) context.setInterval = global.setInterval;
            if(!context.setImmediate) context.setImmediate = global.setImmediate;
            if(!context.clearTimeout) context.clearTimeout = global.clearTimeout;
            if(!context.clearInterval) context.clearInterval = global.clearInterval;
            if(!context.Buffer) context.Buffer = Buffer;
            if(!context.console) context.console = global.console;
            return context;
        case ST_UNRESTRICTED:
            // Allow all core modules & most globals
            if(!context.require) context.require = require;
            if(!context.setTimeout) context.setTimeout = global.setTimeout;
            if(!context.setInterval) context.setInterval = global.setInterval;
            if(!context.setImmediate) context.setImmediate = global.setImmediate;
            if(!context.clearTimeout) context.clearTimeout = global.clearTimeout;
            if(!context.clearInterval) context.clearInterval = global.clearInterval;
            if(!context.Buffer) context.Buffer = Buffer;
            if(!context.console) context.console = global.console;
            if(!context.process) context.process = global.process;
            return context;
        default:
            return context;
    }
};<|endoftext|>


<commit_before>exports.drop = function (driver, opts, cb) {
	var i, queries = [], pending;

	queries.push("DROP TABLE IF EXISTS " + driver.query.escapeId(opts.table));

	for (i = 0; i < opts.many_associations.length; i++) {
		queries.push("DROP TABLE IF EXISTS " + driver.query.escapeId(opts.many_associations[i].mergeTable));
	}

	pending = queries.length;
	for (i = 0; i < queries.length; i++) {
		driver.db.all(queries[i], function (err) {
			if (--pending === 0) {
				return cb(err);
			}
		});
	}
};

exports.sync = function (driver, opts, cb) {
	var queries = [];
	var definitions = [];
	var k, i, pending;
	var primary_keys = opts.keys.map(function (k) { return driver.query.escapeId(k); });
	var keys = [];

	for (i = 0; i < opts.keys.length; i++) {
		if (opts.properties.hasOwnProperty(opts.keys[i])) continue;

		keys.push(driver.query.escapeId(opts.keys[i]));
	}

	for (i = 0; i < keys.length; i++) {
		definitions.push(keys[i] + " INTEGER UNSIGNED NOT NULL");
	}
	if (opts.keys.length == 1) {
		definitions[definitions.length - 1] = keys[0] + " INTEGER PRIMARY KEY AUTOINCREMENT";
	}

	for (k in opts.properties) {
		definitions.push(buildColumnDefinition(driver, k, opts.properties[k]));
	}

	for (i = 0; i < opts.one_associations.length; i++) {
		if (opts.one_associations[i].reversed) continue;
		definitions.push(
			driver.query.escapeId(opts.one_associations[i].field) + " INTEGER UNSIGNED" +
			(opts.one_associations[i].required ? ' NOT NULL' : '')
		);
	}

	if (keys.length > 1) {
		definitions.push("PRIMARY KEY (" + primary_keys.join(", ") + ")");
	}

	queries.push(
		"CREATE TABLE IF NOT EXISTS " + driver.query.escapeId(opts.table) +
		" (" + definitions.join(", ") + ")"
	);
	for (k in opts.properties) {
		if (opts.properties[k].unique === true) {
			queries.push(
				"CREATE UNIQUE INDEX IF NOT EXISTS " + driver.query.escapeId(k) +
				" ON " + driver.query.escapeId(opts.table) +
				" (" + driver.query.escapeId(k) + ")"
			);
		} else if (opts.properties[k].index) {
			queries.push(
				"CREATE INDEX IF NOT EXISTS " + driver.query.escapeId(k) +
				" ON " + driver.query.escapeId(opts.table) +
				" (" + driver.query.escapeId(k) + ")"
			);
		}
	}

	for (i = 0; i < opts.one_associations.length; i++) {
		if (opts.one_associations[i].reversed) continue;
		queries.push(
			"CREATE INDEX IF NOT EXISTS " + driver.query.escapeId(opts.table + "_" + opts.one_associations[i].field) +
			" ON " + driver.query.escapeId(opts.table) +
			" (" + driver.query.escapeId(opts.one_associations[i].field) + ")"
		);
	}

	for (i = 0; i < opts.indexes.length; i++) {
		queries.push(
			"CREATE INDEX IF NOT EXISTS " + driver.query.escapeId(opts.table + "_index" + i) +
			" ON " + driver.query.escapeId(opts.table) +
			" (" + opts.indexes[i].split(/[,;]+/).map(function (el) {
				return driver.query.escapeId(el);
			}).join(", ") + ")"
		);
	}

	for (i = 0; i < opts.many_associations.length; i++) {
		definitions = [];

		definitions.push(driver.query.escapeId(opts.many_associations[i].mergeId) + " INTEGER UNSIGNED NOT NULL");
		definitions.push(driver.query.escapeId(opts.many_associations[i].mergeAssocId) + " INTEGER UNSIGNED NOT NULL");

		for (k in opts.many_associations[i].props) {
			definitions.push(buildColumnDefinition(driver, k, opts.many_associations[i].props[k]));
		}

		queries.push(
			"CREATE TABLE IF NOT EXISTS " + driver.query.escapeId(opts.many_associations[i].mergeTable) +
			" (" + definitions.join(", ") + ")"
		);
		queries.push(
			"CREATE INDEX IF NOT EXISTS " + driver.query.escapeId(opts.many_associations[i].mergeTable) +
			" ON " + driver.query.escapeId(opts.table) +
			" (" + driver.query.escapeId(opts.many_associations[i].mergeId) + ", " + driver.query.escapeId(opts.many_associations[i].mergeAssocId) + ")"
		);
	}

	pending = queries.length;
	for (i = 0; i < queries.length; i++) {
		driver.db.all(queries[i], function (err) {
			if (err) console.log(err);
			if (--pending === 0) {
				return cb(err);
			}
		});
	}
};

function buildColumnDefinition(driver, name, prop) {
	var def;

	switch (prop.type) {
		case "text":
			def = driver.query.escapeId(name) + " TEXT";
			break;
		case "number":
			if (prop.rational === false) {
				def = driver.query.escapeId(name) + " INTEGER";
			} else {
				def = driver.query.escapeId(name) + " REAL";
			}
			break;
		case "boolean":
			def = driver.query.escapeId(name) + " INTEGER UNSIGNED";
			break;
		case "date":
			def = driver.query.escapeId(name) + " DATETIME";
			break;
		case "binary":
		case "object":
			def = driver.query.escapeId(name) + " BLOB";
			break;
		case "enum":
			def = driver.query.escapeId(name) + " INTEGER";
			break;
		default:
			throw new Error("Unknown property type: '" + prop.type + "'");
	}
	if (prop.required === true) {
		def += " NOT NULL";
	}
	if (prop.hasOwnProperty("defaultValue")) {
		def += " DEFAULT " + driver.query.escapeVal(prop.defaultValue);
	}
	return def;
}
<commit_msg>Removes console.log(err) in sqlite DDL<commit_after>exports.drop = function (driver, opts, cb) {
	var i, queries = [], pending;

	queries.push("DROP TABLE IF EXISTS " + driver.query.escapeId(opts.table));

	for (i = 0; i < opts.many_associations.length; i++) {
		queries.push("DROP TABLE IF EXISTS " + driver.query.escapeId(opts.many_associations[i].mergeTable));
	}

	pending = queries.length;
	for (i = 0; i < queries.length; i++) {
		driver.db.all(queries[i], function (err) {
			if (--pending === 0) {
				return cb(err);
			}
		});
	}
};

exports.sync = function (driver, opts, cb) {
	var queries = [];
	var definitions = [];
	var k, i, pending;
	var primary_keys = opts.keys.map(function (k) { return driver.query.escapeId(k); });
	var keys = [];

	for (i = 0; i < opts.keys.length; i++) {
		if (opts.properties.hasOwnProperty(opts.keys[i])) continue;

		keys.push(driver.query.escapeId(opts.keys[i]));
	}

	for (i = 0; i < keys.length; i++) {
		definitions.push(keys[i] + " INTEGER UNSIGNED NOT NULL");
	}
	if (opts.keys.length == 1) {
		definitions[definitions.length - 1] = keys[0] + " INTEGER PRIMARY KEY AUTOINCREMENT";
	}

	for (k in opts.properties) {
		definitions.push(buildColumnDefinition(driver, k, opts.properties[k]));
	}

	for (i = 0; i < opts.one_associations.length; i++) {
		if (opts.one_associations[i].reversed) continue;
		definitions.push(
			driver.query.escapeId(opts.one_associations[i].field) + " INTEGER UNSIGNED" +
			(opts.one_associations[i].required ? ' NOT NULL' : '')
		);
	}

	if (keys.length > 1) {
		definitions.push("PRIMARY KEY (" + primary_keys.join(", ") + ")");
	}

	queries.push(
		"CREATE TABLE IF NOT EXISTS " + driver.query.escapeId(opts.table) +
		" (" + definitions.join(", ") + ")"
	);
	for (k in opts.properties) {
		if (opts.properties[k].unique === true) {
			queries.push(
				"CREATE UNIQUE INDEX IF NOT EXISTS " + driver.query.escapeId(k) +
				" ON " + driver.query.escapeId(opts.table) +
				" (" + driver.query.escapeId(k) + ")"
			);
		} else if (opts.properties[k].index) {
			queries.push(
				"CREATE INDEX IF NOT EXISTS " + driver.query.escapeId(k) +
				" ON " + driver.query.escapeId(opts.table) +
				" (" + driver.query.escapeId(k) + ")"
			);
		}
	}

	for (i = 0; i < opts.one_associations.length; i++) {
		if (opts.one_associations[i].reversed) continue;
		queries.push(
			"CREATE INDEX IF NOT EXISTS " + driver.query.escapeId(opts.table + "_" + opts.one_associations[i].field) +
			" ON " + driver.query.escapeId(opts.table) +
			" (" + driver.query.escapeId(opts.one_associations[i].field) + ")"
		);
	}

	for (i = 0; i < opts.indexes.length; i++) {
		queries.push(
			"CREATE INDEX IF NOT EXISTS " + driver.query.escapeId(opts.table + "_index" + i) +
			" ON " + driver.query.escapeId(opts.table) +
			" (" + opts.indexes[i].split(/[,;]+/).map(function (el) {
				return driver.query.escapeId(el);
			}).join(", ") + ")"
		);
	}

	for (i = 0; i < opts.many_associations.length; i++) {
		definitions = [];

		definitions.push(driver.query.escapeId(opts.many_associations[i].mergeId) + " INTEGER UNSIGNED NOT NULL");
		definitions.push(driver.query.escapeId(opts.many_associations[i].mergeAssocId) + " INTEGER UNSIGNED NOT NULL");

		for (k in opts.many_associations[i].props) {
			definitions.push(buildColumnDefinition(driver, k, opts.many_associations[i].props[k]));
		}

		queries.push(
			"CREATE TABLE IF NOT EXISTS " + driver.query.escapeId(opts.many_associations[i].mergeTable) +
			" (" + definitions.join(", ") + ")"
		);
		queries.push(
			"CREATE INDEX IF NOT EXISTS " + driver.query.escapeId(opts.many_associations[i].mergeTable) +
			" ON " + driver.query.escapeId(opts.table) +
			" (" + driver.query.escapeId(opts.many_associations[i].mergeId) + ", " + driver.query.escapeId(opts.many_associations[i].mergeAssocId) + ")"
		);
	}

	pending = queries.length;
	for (i = 0; i < queries.length; i++) {
		driver.db.all(queries[i], function (err) {
			// if (err) console.log(err);
			if (--pending === 0) {
				return cb(err);
			}
		});
	}
};

function buildColumnDefinition(driver, name, prop) {
	var def;

	switch (prop.type) {
		case "text":
			def = driver.query.escapeId(name) + " TEXT";
			break;
		case "number":
			if (prop.rational === false) {
				def = driver.query.escapeId(name) + " INTEGER";
			} else {
				def = driver.query.escapeId(name) + " REAL";
			}
			break;
		case "boolean":
			def = driver.query.escapeId(name) + " INTEGER UNSIGNED";
			break;
		case "date":
			def = driver.query.escapeId(name) + " DATETIME";
			break;
		case "binary":
		case "object":
			def = driver.query.escapeId(name) + " BLOB";
			break;
		case "enum":
			def = driver.query.escapeId(name) + " INTEGER";
			break;
		default:
			throw new Error("Unknown property type: '" + prop.type + "'");
	}
	if (prop.required === true) {
		def += " NOT NULL";
	}
	if (prop.hasOwnProperty("defaultValue")) {
		def += " DEFAULT " + driver.query.escapeVal(prop.defaultValue);
	}
	return def;
}
<|endoftext|>


<commit_before>app.controller('DashboardController',['$scope', 'dashboardService', function($scope, dashboardService) {
	var makeURL, campusPrevSelected, buildingPrevSelected, floorPrevSelected, campusSelected, buildingSelected, floorSelected;
	dashboardService.success(function(data) {
		$scope.campuses = data;
	});
	$scope.campusSelectedModal = '';
	$scope.buildingSelectedModal = '';
	$scope.floorSelectedModal = '';
	$scope.campusIs = false;
	$scope.buildingIs = false;
	$scope.floorIs = false;
    $scope.header = 'Edit Campus';
    $scope.body = 'Selected Campus';
    $scope.btnType = 'Save Changes';

	$scope.campusSelect = function(campus) {
		$scope.campusSelected = campus.name;
		$scope.editorURL();
		$scope.campusIs = true;
		$scope.buildingIs = false;
		$scope.floorIs = false;
		$scope.buildingPrevSelected = "1";
		if ($scope.campusPrevSelected != $scope.campusSelected) {
			$scope.campusPrevSelected = campus.name;
		} else {
			$scope.campusIs = false;
			$scope.buildingIs = false;
			$scope.floorIs = false;
			$scope.campusPrevSelected = "1";
			$scope.floorPrevSelected = "1";
		}
		console.log('campus: ' + $scope.campusIs);
		console.log('building: ' + $scope.buildingIs);
		console.log('floor: ' + $scope.floorIs);
	}
	$scope.buildingSelect = function(building) {
		$scope.buildingSelected = building.name;
		$scope.editorURL();
		$scope.buildingIs = true;
		$scope.floorIs = false;
		if ($scope.buildingPrevSelected != $scope.buildingSelected) {
			$scope.buildingPrevSelected = building.name;
		} else {
			$scope.buildingIs = false;
			$scope.floorIs = false;
			$scope.buildingPrevSelected = "3";
			$scope.floorPrevSelected = "3";
		}
		console.log('campus: ' + $scope.campusIs);
		console.log('building: ' + $scope.buildingIs);
		console.log('floor: ' + $scope.floorIs);
	}
	$scope.floorSelect = function(floor) {
		$scope.floorSelected = floor.name;
		$scope.editorURL();
		$scope.floorIs = true;
		if ($scope.floorPrevSelected != $scope.floorSelected) {
			$scope.floorPrevSelected = floor.name;
		} else {
			$scope.floorIs = false;
			$scope.floorPrevSelected = "4";
		}
		console.log('campus: ' + $scope.campusIs);
		console.log('building: ' + $scope.buildingIs);
		console.log('floor: ' + $scope.floorIs);
	}
	$scope.editorURL = function() {
		//$scope.makeURL = '/' + $scope.campusSelected + '/'+ $scope.buildingSelected + '/' + $scope.floorSelected + '/';
		//angular.lowercase($scope.makeURL);
		//$scope.makeURL.replace(/\s/g, '');
		//console.log($scope.makeURL);
	}
	/*$scope.myRightButton = function (bool) {
		alert('');
	};*/
	$scope.changeCampus = function(type) {
		switch(type) {
			case 0:
				$scope.header = 'Create Campus';
				$scope.campusSelectedModal = '';
				$scope.buildingSelectedModal = '';
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Create';
				break;
			case 1:
				$scope.header = 'Edit Campus';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = '';
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Save Changes';
				break;
			case 2:
				$scope.header = 'Create Buidling';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = '';
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Create';
				break;
			case 3:
				$scope.header = 'Edit Building';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = $scope.buildingSelected;
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Save Changes';
				break;
			case 4:
				$scope.header = 'Create Floor';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = $scope.buildingSelected;
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Create';
				break;
			case 5:
				$scope.header = 'Edit Floor';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = $scope.buildingSelected;
				$scope.floorSelectedModal = $scope.floorSelected;
				$scope.btnType = 'Save Changes';
				break;
		}
	}
}]);<commit_msg>removed console logs<commit_after>app.controller('DashboardController',['$scope', 'dashboardService', function($scope, dashboardService) {
	var makeURL, campusPrevSelected, buildingPrevSelected, floorPrevSelected, campusSelected, buildingSelected, floorSelected;
	dashboardService.success(function(data) {
		$scope.campuses = data;
	});
	$scope.campusSelectedModal = '';
	$scope.buildingSelectedModal = '';
	$scope.floorSelectedModal = '';
	$scope.campusIs = false;
	$scope.buildingIs = false;
	$scope.floorIs = false;
    $scope.header = 'Edit Campus';
    $scope.body = 'Selected Campus';
    $scope.btnType = 'Save Changes';

	$scope.campusSelect = function(campus) {
		$scope.campusSelected = campus.name;
		$scope.editorURL();
		$scope.campusIs = true;
		$scope.buildingIs = false;
		$scope.floorIs = false;
		$scope.buildingPrevSelected = "1";
		if ($scope.campusPrevSelected != $scope.campusSelected) {
			$scope.campusPrevSelected = campus.name;
		} else {
			$scope.campusIs = false;
			$scope.buildingIs = false;
			$scope.floorIs = false;
			$scope.campusPrevSelected = "1";
			$scope.floorPrevSelected = "1";
		}
	}
	$scope.buildingSelect = function(building) {
		$scope.buildingSelected = building.name;
		$scope.editorURL();
		$scope.buildingIs = true;
		$scope.floorIs = false;
		if ($scope.buildingPrevSelected != $scope.buildingSelected) {
			$scope.buildingPrevSelected = building.name;
		} else {
			$scope.buildingIs = false;
			$scope.floorIs = false;
			$scope.buildingPrevSelected = "3";
			$scope.floorPrevSelected = "3";
		}
	}
	$scope.floorSelect = function(floor) {
		$scope.floorSelected = floor.name;
		$scope.editorURL();
		$scope.floorIs = true;
		if ($scope.floorPrevSelected != $scope.floorSelected) {
			$scope.floorPrevSelected = floor.name;
		} else {
			$scope.floorIs = false;
			$scope.floorPrevSelected = "4";
		}
	}
	$scope.editorURL = function() {
		//$scope.makeURL = '/' + $scope.campusSelected + '/'+ $scope.buildingSelected + '/' + $scope.floorSelected + '/';
		//angular.lowercase($scope.makeURL);
		//$scope.makeURL.replace(/\s/g, '');
		//console.log($scope.makeURL);
	}
	/*$scope.myRightButton = function (bool) {
		alert('');
	};*/
	$scope.changeCampus = function(type) {
		switch(type) {
			case 0:
				$scope.header = 'Create Campus';
				$scope.campusSelectedModal = '';
				$scope.buildingSelectedModal = '';
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Create';
				break;
			case 1:
				$scope.header = 'Edit Campus';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = '';
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Save Changes';
				break;
			case 2:
				$scope.header = 'Create Buidling';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = '';
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Create';
				break;
			case 3:
				$scope.header = 'Edit Building';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = $scope.buildingSelected;
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Save Changes';
				break;
			case 4:
				$scope.header = 'Create Floor';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = $scope.buildingSelected;
				$scope.floorSelectedModal = '';
				$scope.btnType = 'Create';
				break;
			case 5:
				$scope.header = 'Edit Floor';
				$scope.campusSelectedModal = $scope.campusSelected;
				$scope.buildingSelectedModal = $scope.buildingSelected;
				$scope.floorSelectedModal = $scope.floorSelected;
				$scope.btnType = 'Save Changes';
				break;
		}
	}
}]);<|endoftext|>